All Products
Search
Document Center

Container Service for Kubernetes:Deploy an agent application as a Knative Service

Last Updated:Oct 13, 2026

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:

  1. Application packaging: Packages the code, dependencies (requirements.txt), and environment variables of the specified Python agent application.

  2. Image build: Builds a container image that includes the agent application in your local Docker environment, based on the specified base image.

  3. Image push: Pushes the built image to the specified container image registry, such as Container Registry (ACR).

  4. 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 pip command.

    # 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.

  1. 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)
  2. Write the agent code in the app_agent.py file.

    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.

  1. Run the deployment command.

    Go to the my-agent-project directory and use the following example to deploy the Service.

    Replace DASHSCOPE_API_KEY with 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

    Expand to view the command syntax

    agentscope deploy knative SOURCE [OPTIONS]
    • SOURCE: The path to a Python file, such as app_agent.py.

    • [OPTIONS]: The following table describes the common parameters.

      For more parameters, run agentscope deploy knative --help.

      Parameter

      Type

      Default

      Description

      --namespace

      string

      agentscope-runtime

      Specifies the namespace in which to deploy the agent.

      --kube-config-path, -c

      path

      None

      Specifies the path to the kubeconfig file used to connect to the cluster. If this parameter is not specified, the default path is used.

      --port

      integer

      8080

      Specifies the port on which the agent application listens in the container.

      --image-name

      string

      agent_app

      Specifies the name of the container image built for the agent application.

      --image-tag

      string

      linux-amd64

      Specifies the container image tag built for the agent application.

      --registry-url

      string

      localhost

      Specifies the target container image registry address to which the image is pushed, for example, registry.cn-hangzhou.aliyuncs.com.

      --registry-namespace

      string

      agentscope-runtime

      Specifies the namespace (or project) used in the container image registry.

      --push

      flag

      False

      Specifies whether to push the built image to a remote registry. This flag is usually required when you deploy to a remote cluster.

      --base-image

      string

      python:3.10-slim-bookworm

      Specifies the base image used to build the application. The image must include a Python environment.

      --requirements

      string

      None

      Specifies the Python dependencies for the application. This can be a requirements.txt file path or a comma-separated list of packages.

      --cpu-request

      string

      200m

      Sets the CPU resource request for the Pod. The unit is m (one thousandth of a core) or an integer number of cores, for example, 200m or 1.

      --cpu-limit

      string

      1000m

      Sets the CPU resource limit for the Pod, for example, 1000m or 2.

      --memory-request

      string

      512Mi

      Sets the memory resource request for the Pod. Common units are Mi or Gi, for example, 512Mi or 1Gi.

      --memory-limit

      string

      2Gi

      Sets the memory resource limit for the Pod, for example, 2Gi or 4Gi.

      --image-pull-policy

      choice

      IfNotPresent

      Sets the image pull policy for the Pod. Valid values are Always, IfNotPresent, and Never.

      --deploy-timeout

      integer

      300

      Specifies the timeout, in seconds, for waiting for the Knative Service to be deployed.

      --health-check

      flag

      None

      Specifies whether to enable a health check for the Knative Service.

      --platform

      string

      linux/amd64

      Specifies the target hardware platform for building the image, for example, linux/amd64 or linux/arm64.

      --pypi-mirror

      string

      None

      Specifies the PyPI mirror used to install Python packages, for example, https://pypi.tuna.tsinghua.edu.cn/simple.

  2. 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

  1. Obtain the access gateway.

    1. On the ACK Clusters page, click the name of your cluster. In the left navigation pane, click Applications > Knative.

    2. 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.

  2. Send a request to the agent Service by using the curl command.

    In the following command, replace 115.29.xxx.xxx with the Knative access gateway, and replace Host with 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"
      }'
  3. 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 -w

    You 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 InMemoryStateService and InMemorySessionHistoryService in 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-limit to 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 the agentscope deploy knative command 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.