With a single command, deploy an agent application built with the AgentScope framework to Knative in Container Service for Kubernetes (ACK). Knative Serverless capabilities such as automatic scaling (scale to zero) and version management let you host AI agents elastically and at low cost.
How it works
agentscope deploy knative wraps the complex process of containerizing an agent application and deploying it to a cluster. The core workflow is as follows:
-
Application packaging: Packages the code, dependencies (
requirements.txt), and environment variables of the specified Python agent application. -
Image build: Builds a container image that includes the agent application in your local Docker environment, based on the specified base image.
-
Image push: Pushes the built image to the specified container image registry, such as Container Registry (ACR).
-
Service deployment: Generates and applies a Knative Service (
ksvc) manifest in the target cluster. Knative uses this manifest to create a Deployment and Pods, and automatically configures network routing, load balancing, and automatic scaling policies.
Preparations
-
You have deployed Knative components in the cluster.
-
You have Docker installed and running on your local machine to build container images.
-
You have installed AgentScope Runtime by using the
pipcommand.# Basic installation pip install agentscope-runtime>=1.1.0 # Kubernetes deployment dependencies pip install "agentscope-runtime[ext]>=1.1.0"
Step 1: Create an agent project
If you do not have an agent application ready, see the following example file structure and code.
-
Create the project directory structure:
my-agent-project/ ├── app_agent.py # Main file of the agent application ├── requirements.txt # Python dependencies (optional) └── .env # Environment variables (optional) -
Write the agent code in the
app_agent.pyfile.The following code creates an agent that uses a Qwen model and supports code execution and multi-turn conversations.
# -*- coding: utf-8 -*- import os from contextlib import asynccontextmanager from fastapi import FastAPI from agentscope.agent import ReActAgent from agentscope.formatter import DashScopeChatFormatter from agentscope.model import DashScopeChatModel from agentscope.pipeline import stream_printing_messages from agentscope.tool import Toolkit, execute_python_code from agentscope.memory import InMemoryMemory from agentscope.session import JSONSession from agentscope_runtime.engine.app import AgentApp from agentscope_runtime.engine.schemas.agent_schemas import AgentRequest @asynccontextmanager async def lifespan(app: FastAPI): """Initialize the service.""" app.state.session = JSONSession( save_dir="./", # Directory that stores all session files ) try: yield finally: print("AgentApp is shutting down...") # Create an AgentApp agent_app = AgentApp( app_name="MyAssistant", app_description="A helpful assistant agent", lifespan=lifespan, ) @agent_app.query(framework="agentscope") async def query_func( self, msgs, request: AgentRequest = None, **kwargs, ): """Process user queries.""" session_id = request.session_id user_id = request.user_id # Create toolkit with Python execution toolkit = Toolkit() toolkit.register_tool_function(execute_python_code) # Create agent agent = ReActAgent( name="MyAssistant", model=DashScopeChatModel( "qwen-turbo", api_key=os.getenv("DASHSCOPE_API_KEY"), enable_thinking=True, stream=True, ), sys_prompt="You're a helpful assistant.", toolkit=toolkit, memory=InMemoryMemory(), formatter=DashScopeChatFormatter(), ) agent.set_console_output_enabled(False) await agent_app.state.session.load_session_state( session_id=session_id, user_id=user_id, agent=agent, ) async for msg, last in stream_printing_messages( agents=[agent], coroutine_task=agent(msgs), ): yield msg, last await agent_app.state.session.save_session_state( session_id=session_id, user_id=user_id, agent=agent, ) if __name__ == "__main__": agent_app.run()
Step 2: Deploy the agent application
Use the agentscope deploy command to deploy a local agent application as a Knative Service in one step.
-
Run the deployment command.
Go to the
my-agent-projectdirectory and use the following example to deploy the Service.Replace
DASHSCOPE_API_KEYwith its actual value.agentscope deploy knative app_agent.py \ --image-name agent_app \ --env DASHSCOPE_API_KEY=sk-xxx \ --image-tag linux-amd64-18 \ --registry-url registry.cn-hangzhou.aliyuncs.com \ --base-image registry.cn-hangzhou.aliyuncs.com/knative-sample/python:3.10-slim-bookworm \ --registry-namespace knative-sample \ --namespace default \ --push -
View the deployment result.
After the deployment succeeds, the terminal outputs information such as the Service access URL. Record this URL to access the Service in the next step.
Deployment successful! Deployment ID: d4b4a54d-9976-443c-a1da-a77643****** Resource Name: agent-d4b4***** URL: http://agent-03e*****.default.example.com Namespace: default
Step 3: Access the deployed agent
-
Obtain the access gateway.
-
On the ACK Clusters page, click the name of your cluster. In the left navigation pane, click .
-
On the Services or Component Management page, obtain the Gateway.
The IP address of the Access Gateway (for example,
120.xxx.159) is displayed at the bottom of the page. Before you access the Service, configure a Host binding between the Service domain name and the access gateway.
-
-
Send a request to the agent Service by using the
curlcommand.In the following command, replace
115.29.xxx.xxxwith the Knative access gateway, and replaceHostwith the access URL that you obtained earlier.curl -i -X POST "http://115.29.xxx.xxx:80/process" \ -H "Content-Type: application/json" \ -H "Host: agent-03e*****.default.example.com" \ -d '{ "input": [ { "role": "user", "content": [ { "type": "text", "text": "Hello, how are you?" } ] } ], "session_id": "123" }' -
View the returned streaming response, which includes the agent's thinking process and the final computed result.
Step 4: Observe automatic scaling
-
Automatic scale-down: After a period without requests, Knative automatically reduces the number of Pods for the Service to 0 to save resources. Run the following command to observe the changes in the Pods.
# In the specified namespace, continuously watch each Pod kubectl get pods -n default -wYou can also click Services on the Knative page, and then click the service name. The bottom of the page shows the running status of the Pods for the current revision.
On the Revision Information tab, the Ready/requested pods column displays
0/0, which confirms that the Pods have scaled to zero. -
Automatic scale-up: When a new request arrives, Knative automatically starts new Pods within seconds to handle the request.
Production recommendations
-
State persistence: The
InMemoryStateServiceandInMemorySessionHistoryServicein the example code lose all state and conversation history when a Pod restarts, which makes them unsuitable for production. For a production deployment, switch to an implementation based on Redis or another persistent storage solution. -
Secret management: Avoid passing sensitive information, such as
API_KEY, directly on the command line or hard-coding it in your code. Use Kubernetes Secrets and mount them as environment variables in the container through the Knative Service configuration. -
Resource planning: Based on your workload, use stress testing to evaluate and appropriately configure parameters such as
--cpu-request,--cpu-limit,--memory-request, and--memory-limitto maintain Service performance and stability. -
Observability: Configure log collection, such as Simple Log Service (SLS) for ACK, and monitoring and alerting, such as Application Real-Time Monitoring Service (ARMS). This helps you troubleshoot issues and monitor the health of the Service.
Related operations
-
Update the agent: After you modify the code, use a new image tag, for example,
--image-tag v1.1, and run theagentscope deploy knativecommand again to complete a rolling update. -
Uninstall the agent:
# Replace resource-name and namespace with your actual values kubectl delete ksvc <resource-name> -n <namespace>This operation deletes only the Service in Kubernetes. It does not delete the container image pushed to the container image registry.