### Install agentscope-runtime Source: https://runtime.agentscope.io/zh/sandbox Installs the AgentScope Runtime library using pip. This is the primary step to get started with AgentScope. ```shell pip install agentscope-runtime ``` -------------------------------- ### Install AgentScope Runtime with Deployment Dependencies Source: https://runtime.agentscope.io/zh/advanced_deployment Installation commands for AgentScope Runtime with various optional dependencies. Includes base installation, Kubernetes deployment dependencies, and optional sandbox tools for different deployment scenarios. ```bash # 基础安装 pip install agentscope-runtime # Kubernetes部署依赖 pip install "agentscope-runtime[deployment]" # 沙箱工具(可选) pip install "agentscope-runtime[sandbox]" ``` -------------------------------- ### Install AgentScope Runtime from Source Source: https://runtime.agentscope.io/zh/install Installs AgentScope Runtime directly from its GitHub repository. This method is useful for obtaining the latest development versions or for contributing to the project. ```bash git clone https://github.com/agentscope-ai/agentscope-runtime.git cd agentscope-runtime pip install . ``` -------------------------------- ### Install AgentScope Runtime with Optional Features (PyPI) Source: https://runtime.agentscope.io/zh/install Installs AgentScope Runtime along with optional dependencies for enhanced functionality, such as langgraph, agno, and autogen integrations. This provides a fuller feature set for complex agent interactions. ```bash pip install "agentscope-runtime[langgraph,agno,autogen]" ``` -------------------------------- ### Install AgentScope Runtime with Development Dependencies Source: https://runtime.agentscope.io/zh/install Installs AgentScope Runtime from source, including development-specific dependencies. This is essential for developers working on the project, enabling tasks like testing and linting. ```bash pip install ".[dev]" ``` -------------------------------- ### Verify AgentScope Runtime Installation Source: https://runtime.agentscope.io/zh/install Checks if the AgentScope Runtime has been successfully installed by importing the library and printing its version. This is a fundamental step to confirm the installation. ```python import agentscope_runtime print(f"AgentScope Runtime {agentscope_runtime.__version__} is ready!") ``` -------------------------------- ### Python:使用生产服务配置进行高级独立部署 Source: https://runtime.agentscope.io/zh/advanced_deployment 使用 ServicesConfig 进行高级独立进程部署,支持 Redis 进行持久化。这对于需要更健壮的内存和会话历史管理的生产环境至关重要。它还允许指定端点路径、流式传输和协议适配器。 ```python from agentscope_runtime.engine.deployers.utils.service_utils import ServicesConfig # 生产服务配置 production_services = ServicesConfig( # 使用Redis实现持久化 memory_provider="redis", session_history_provider="redis", redis_config={ "host": "redis.production.local", "port": 6379, "db": 0, } ) # 使用生产服务进行部署 deployment_info = await runner.deploy( deploy_manager=deploy_manager, endpoint_path="/process", stream=True, mode=DeploymentMode.DETACHED_PROCESS, services_config=production_services, # 使用生产配置 protocol_adapters=[a2a_protocol], ) ``` -------------------------------- ### Shell:Kubernetes 部署先决条件检查 Source: https://runtime.agentscope.io/zh/advanced_deployment 在将 AgentApp 部署到 Kubernetes 之前,请验证 Docker、kubectl 和镜像仓库的访问权限。这些命令确保您的开发环境已正确配置以进行容器化部署和 Kubernetes 集成。 ```shell # 确保Docker正在运行 docker --version # 验证Kubernetes访问 kubectl cluster-info # 检查镜像仓库访问(以阿里云为例) docker login your-registry ``` -------------------------------- ### Shell:ModelStudio 部署环境变量设置 Source: https://runtime.agentscope.io/zh/advanced_deployment 在通过 ModelStudio 部署之前,设置必要的阿里云和 DashScope API 密钥以及工作区 ID。这些环境变量对于使用阿里云服务和 DashScope LLM 进行托管云部署至关重要。还包括用于 OSS 集成的可选凭证。 ```shell # 确保设置环境变量 export DASHSCOPE_API_KEY="your-dashscope-api-key" export ALIBABA_CLOUD_ACCESS_KEY_ID="your-access-key-id" export ALIBABA_CLOUD_ACCESS_KEY_SECRET="your-access-key-secret" export MODELSTUDIO_WORKSPACE_ID="your-workspace-id" # 可选的OSS专用凭证 export OSS_ACCESS_KEY_ID="your-oss-access-key-id" export OSS_ACCESS_KEY_SECRET="your-oss-access-key-secret" ``` -------------------------------- ### Verify Appworld Installation using get_env_profile Source: https://runtime.agentscope.io/zh/training_sandbox Verify that the Training Sandbox is correctly installed by calling get_env_profile to retrieve the dataset ID from the Appworld environment. This confirms that all setup is correct and the sandbox is ready for use. ```python from agentscope_runtime.sandbox.box.training_box.training_box import APPWorldSandbox box = APPWorldSandbox() profile_list = box.get_env_profile(env_type="appworld", split="train") print(profile_list[0]) ``` -------------------------------- ### Configure Environment Variables for AgentScope Runtime Source: https://runtime.agentscope.io/zh/advanced_deployment Setup environment variables required for LLM functionality (DASHSCOPE_API_KEY) and optional cloud deployment settings (DOCKER_REGISTRY, KUBECONFIG). These variables enable API access and container registry configuration. ```bash # LLM功能必需 export DASHSCOPE_API_KEY="your_qwen_api_key" # 云部署可选 export DOCKER_REGISTRY="your_registry_url" export KUBECONFIG="/path/to/your/kubeconfig" ``` -------------------------------- ### Python:独立进程部署 AgentApp Source: https://runtime.agentscope.io/zh/advanced_deployment 使用 LocalDeployManager 以独立进程模式部署 AgentApp。此模式将应用作为单独的进程运行,直到被显式停止。它返回部署 URL 和部署 ID,并提供用于健康检查和关闭服务的命令。 ```python import asyncio from agentscope_runtime.engine.deployers.local_deployer import LocalDeployManager from agentscope_runtime.engine.deployers.utils.deployment_modes import DeploymentMode from agent_app import app # 导入已配置的 app async def main(): """以独立进程模式部署应用""" print("🚀 以独立进程模式部署 AgentApp...") # 以独立模式部署 deployment_info = await app.deploy( LocalDeployManager(host="127.0.0.1", port=8080), mode=DeploymentMode.DETACHED_PROCESS, ) print(f"✅ 部署成功:{deployment_info['url']}") print(f"📍 部署ID:{deployment_info['deploy_id']}") print(f""" 🎯 服务已启动,测试命令: curl {deployment_info['url']}/health curl -X POST {deployment_info['url']}/admin/shutdown # 停止服务 ⚠️ 注意:服务在独立进程中运行,直到被停止。 """) return deployment_info if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### AgentApp Initialization and Basic Usage Source: https://runtime.agentscope.io/zh/agent_app Initializes an AgentApp to start an HTTP API service for an Agent, listening on a specified port and providing a main processing interface. ```APIDOC ## AgentApp Initialization and Basic Usage ### Description Starts an HTTP API service containing an Agent, listening on a specified port, and providing a main processing interface (default: `/process`). ### Method POST ### Endpoint `/process` (default) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (array) - Required - The input to the agent, typically a list of message objects. ### Request Example ```json { "input": [ { "role": "user", "content": [{ "type": "text", "text": "Hello Friday" }] } ] } ``` ### Response #### Success Response (200) - **sequence_number** (int) - The sequence number of the message. - **object** (string) - The type of object being returned (e.g., 'response', 'content', 'message'). - **status** (string) - The status of the processing step (e.g., 'created', 'in_progress', 'completed'). - **text** (string) - The content of the message or response. #### Response Example ```json { "sequence_number": 0, "object": "response", "status": "created" } ``` ```json { "sequence_number": 2, "object": "content", "status": "in_progress", "text": "Hello" } ``` ```json { "sequence_number": 4, "object": "message", "status": "completed", "text": "Hello world!" } ``` ``` -------------------------------- ### Python:将 AgentApp 部署到 Kubernetes Source: https://runtime.agentscope.io/zh/advanced_deployment 使用 KubernetesDeployManager 将 AgentApp 部署到 Kubernetes 集群。此脚本配置镜像仓库、Kubernetes 名称空间,并指定应用程序的容器映像、版本、要求和环境变量。它还包括资源请求和限制。 ```python # k8s_deploy.py import asyncio import os from agentscope_runtime.engine.deployers.kubernetes_deployer import ( KubernetesDeployManager, RegistryConfig, K8sConfig, ) from agent_app import app # 导入已配置的 app async def deploy_to_k8s(): """将 AgentApp 部署到 Kubernetes""" # 配置镜像仓库和 K8s 连接 deployer = KubernetesDeployManager( kube_config=K8sConfig( k8s_namespace="agentscope-runtime", kubeconfig_path=None, ), registry_config=RegistryConfig( registry_url="your-registry-url", namespace="agentscope-runtime", ), use_deployment=True, ) # 执行部署 result = await app.deploy( deployer, port="8080", replicas=1, image_name="agent_app", image_tag="v1.0", requirements=["agentscope", "fastapi", "uvicorn"], base_image="python:3.10-slim-bookworm", environment={ "PYTHONPATH": "/app", "DASHSCOPE_API_KEY": os.environ.get("DASHSCOPE_API_KEY"), }, runtime_config={ "resources": { "requests": {"cpu": "200m", "memory": "512Mi"}, "limits": {"cpu": "1000m", "memory": "2Gi"}, }, }, platform="linux/amd64", push_to_registry=True, ) print(f"✅ 部署成功:{result['url']}") return result, deployer if __name__ == "__main__": asyncio.run(deploy_to_k8s()) ``` -------------------------------- ### Multi-Handler Tracing Setup (Python) Source: https://runtime.agentscope.io/zh/tracing Demonstrates configuring a Tracer with multiple handlers, including a base handler and a local logging handler. This allows events to be processed by different logging mechanisms simultaneously. The example shows tracing a search event. ```python from agentscope_runtime.engine.tracing import Tracer, TraceType from agentscope_runtime.engine.tracing.base import BaseLogHandler from agentscope_runtime.engine.tracing.local_logging_handler import LocalLogHandler # Create a tracer with multiple handlers tracer = Tracer(handlers=[ BaseLogHandler(), LocalLogHandler(enable_console=True) ]) with tracer.event( event_type=TraceType.SEARCH, payload={"query": "test query", "source": "database"}, ) as event: tracer.log("Search started") # Simulate search operation search_results = ["result1", "result2", "result3"] # For cases requiring additional logged information event.on_log(payload={"results": search_results, "count": len(search_results)}) ``` -------------------------------- ### Deploy AgentApp to ModelStudio with OSS Configuration Source: https://runtime.agentscope.io/zh/advanced_deployment Deploys an AgentScope application to Alibaba Cloud ModelStudio using ModelstudioDeployManager. Configures OSS (Object Storage Service) and ModelStudio credentials from environment variables, executes deployment with specified dependencies and environment settings, and returns deployment URL and artifact information. Requires valid Alibaba Cloud credentials and DashScope API key. ```python import asyncio import os from agentscope_runtime.engine.deployers.modelstudio_deployer import ( ModelstudioDeployManager, OSSConfig, ModelstudioConfig, ) from agent_app import app async def deploy_to_modelstudio(): """Deploy AgentApp to Alibaba Cloud ModelStudio""" deployer = ModelstudioDeployManager( oss_config=OSSConfig( access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"), access_key_secret=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), ), modelstudio_config=ModelstudioConfig( workspace_id=os.environ.get("MODELSTUDIO_WORKSPACE_ID"), access_key_id=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID"), access_key_secret=os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), dashscope_api_key=os.environ.get("DASHSCOPE_API_KEY"), ), ) result = await app.deploy( deployer, deploy_name="agent-app-example", telemetry_enabled=True, requirements=["agentscope", "fastapi", "uvicorn"], environment={ "PYTHONPATH": "/app", "DASHSCOPE_API_KEY": os.environ.get("DASHSCOPE_API_KEY"), }, ) print(f"✅ Deployed to ModelStudio: {result['url']}") print(f"📦 Artifact: {result['artifact_url']}") return result if __name__ == "__main__": asyncio.run(deploy_to_modelstudio()) ``` -------------------------------- ### User Query Example (JSON) Source: https://runtime.agentscope.io/zh/protocol An example of a user query formatted for the Agent API, including input messages with text content and specifying the model to use. It also indicates that streaming is enabled. ```json { "input": [{ "role": "user", "content": [{"type": "text", "text": "描述这张图片"}], "type": "message" }], "stream": true, "model": "gpt-4-vision" } ``` -------------------------------- ### Service Lifecycle Management - Python Source: https://runtime.agentscope.io/zh/manager Shows how to register multiple services with ServiceManager and manage their lifecycle using async context manager. Includes examples of listing services and performing health checks on all registered services. ```python from agentscope_runtime.engine.services.manager import ServiceManager class MyServiceManager(ServiceManager): def _register_default_services(self): pass manager = MyServiceManager() manager.register(MockService, name="service1") manager.register(MockService, name="service2") async def run(): async with manager as services: names = services.list_services() health = await services.health_check() print(names, health) ``` -------------------------------- ### Test Agent Endpoints with OpenAI SDK Source: https://runtime.agentscope.io/zh/advanced_deployment Test deployed agent endpoints using OpenAI Python SDK client. Connects to the compatible-mode API endpoint and creates responses with specified model and input parameters. ```python from openai import OpenAI client = OpenAI(base_url="http://0.0.0.0:8080/compatible-mode/v1") response = client.responses.create( model="any_name", input="杭州天气如何?" ) print(response) ``` -------------------------------- ### Create Context Manager using Async Factory Helper Source: https://runtime.agentscope.io/zh/context_manager Illustrates using the `create_context_manager` asynchronous factory function to instantiate the ContextManager. This approach simplifies setup and usage within an async context. ```python from agentscope_runtime.engine.services.context_manager import create_context_manager from agentscope_runtime.engine.services.session_history_service import InMemorySessionHistoryService from agentscope_runtime.engine.services.memory_service import InMemoryMemoryService async with create_context_manager( session_history_service=InMemorySessionHistoryService(), memory_service=InMemoryMemoryService(), ) as manager: session = await manager.compose_session(user_id="u1", session_id="s1") await manager.compose_context(session, request_input=[]) ``` -------------------------------- ### Configure TablestoreSessionHistoryService in Python Source: https://runtime.agentscope.io/zh/context_manager Provides an example of how to configure and initialize the `TablestoreSessionHistoryService`, which uses Alibaba Cloud Tablestore for persistent storage. This involves creating a Tablestore client with necessary credentials and endpoint information, then passing this client to the service constructor. Dependencies include `TablestoreSessionHistoryService` and utility functions for creating the client. ```python from agentscope_runtime.engine.services.tablestore_session_history_service import TablestoreSessionHistoryService from agentscope_runtime.engine.services.utils.tablestore_service_utils import create_tablestore_client tablestore_session_history_service = TablestoreSessionHistoryService( tablestore_client=create_tablestore_client( end_point="your_endpoint", instance_name="your_instance_name", access_key_id="your_access_key_id", access_key_secret="your_access_key_secret", ), ) ``` -------------------------------- ### 手动构建 Jupyter Book 项目 Source: https://runtime.agentscope.io/zh/README 使用 jupyter-book build 命令手动构建 Cookbook 项目。输出的 HTML 文件将生成在 _build/html 目录中。 ```bash jupyter-book build . ``` -------------------------------- ### 使用 Bash 脚本构建和预览 Jupyter Book Source: https://runtime.agentscope.io/zh/README 执行提供的 build.sh 脚本来清理、构建并预览 Jupyter Book。-p 选项会在本地启动服务器以在浏览器中预览 Cookbook。 ```bash bash ./build.sh -p ``` -------------------------------- ### Check LangGraph Agent Import Source: https://runtime.agentscope.io/zh/install Verifies the successful import of the LangGraphAgent class. An import error suggests that the 'langgraph' extra dependency for AgentScope Runtime has not been installed. ```python try: from agentscope_runtime.engine.agents.langgraph_agent import LangGraphAgent print(f"✅ {LangGraphAgent.__name__} - 导入成功") except ImportError as e: print(f"❌ LangGraphAgent -导入失败:{e}") print('💡尝试通过以下命令安装:pip install "agentscope-runtime[langgraph]"') ``` -------------------------------- ### Check AgentScope Agent Import Source: https://runtime.agentscope.io/zh/install Verifies the successful import of the AgentScopeAgent class. If the import fails, it suggests that the base 'agentscope-runtime' or the 'agentscope' extra might not be installed correctly. ```python try: from agentscope_runtime.engine.agents.agentscope_agent import AgentScopeAgent print(f"✅ {AgentScopeAgent.__name__} - 导入成功") except ImportError as e: print(f"❌ AgentScopeAgent - 导入失败:{e}") print('💡 尝试通过以下命令安装:pip install "agentscope-runtime[agentscope]"') ``` -------------------------------- ### Initialize BFCLSandbox and Create Instance Source: https://runtime.agentscope.io/zh/training_sandbox Initializes the BFCLSandbox and creates a new instance for interaction. It retrieves environment profiles and sets up the initial state for the instance, returning an instance ID and the initial query. ```python from agentscope_runtime.sandbox.box.training_box.training_box import BFCLSandbox #initialize sandbox box = BFCLSandbox() profile_list = box.get_env_profile(env_type="bfcl") init_response = box.create_instance( env_type="bfcl", task_id=profile_list[0], ) inst_id = init_response["info"]["instance_id"] query = init_response["state"] ``` -------------------------------- ### Create Appworld Training Instance with create_instance Source: https://runtime.agentscope.io/zh/training_sandbox Create a training instance from the first query in the training set using create_instance method. The instance is assigned a unique Instance ID, and both system prompt and user prompt are returned in the state field as a Message List. ```python profile_list = box.get_env_profile(env_type="appworld", split="train") init_response = box.create_instance( env_type="appworld", task_id=profile_list[0], ) instance_id = init_response["info"]["instance_id"] query = init_response["state"] print(f"Created instance {instance_id} with query: {query}") ``` -------------------------------- ### Check Agno Agent Import Source: https://runtime.agentscope.io/zh/install Confirms the successful import of the AgnoAgent class. Failure to import indicates that the 'agno' extra dependency for AgentScope Runtime may be missing. ```python try: from agentscope_runtime.engine.agents.agno_agent import AgnoAgent print(f"✅ {AgnoAgent.__name__} - 导入成功") except ImportError as e: print(f"❌ AgnoAgent - 导入失败:{e}") print('💡尝试通过以下命令安装:pip install "agentscope-runtime[agno]"') ``` -------------------------------- ### Agent Response Stream Example (JSON) Source: https://runtime.agentscope.io/zh/protocol Illustrates a typical agent response stream, starting with creation status, progressing through content chunks, and ending with completion status for both messages and the overall response. ```json {"id":"response_123","object":"response","status":"created"} {"id":"msg_abc","object":"message","type":"assistant","status":"created"} {"status":"in_progress","type":"text","index":0,"delta":true,"text":"这张","object":"content","msg_id":"msg_abc"} {"status":"in_progress","type":"text","index":0,"delta":true,"text":"图片显示...","object":"content","msg_id":"msg_abc"} {"status":"completed","type":"text","index":0,"delta":false,"text":"这张图片显示...","object":"content","msg_id":"msg_abc"} {"id":"msg_abc","status":"completed","object":"message"} {"id":"response_123","status":"completed","object":"response"} ``` -------------------------------- ### Verify AgentScope Sandbox Setup with run_ipython_cell Source: https://runtime.agentscope.io/zh/sandbox This Python code snippet verifies the AgentScope sandbox installation by executing a simple print statement within an IPython cell. It imports necessary modules and prints the JSON-formatted result. ```python import json from agentscope_runtime.sandbox.tools.base import run_ipython_cell # Model Context Protocol (MCP) compatible tool call result result = run_ipython_cell(code="print('Setup successful!')") print(json.dumps(result, indent=4, ensure_ascii=False)) ``` -------------------------------- ### 本地构建内置 AgentScope 沙箱镜像 Source: https://runtime.agentscope.io/zh/sandbox_advanced 使用 `runtime-sandbox-builder` 在本地构建 AgentScope 的内置沙箱镜像。支持构建所有镜像、基础镜像、GUI 镜像、浏览器镜像或文件系统镜像。 ```shell # 构建所有内置镜像 runtime-sandbox-builder all # 构建基础镜像(约1GB) runtime-sandbox-builder base # 构建GUI镜像(约2GB) runtime-sandbox-builder gui # 构建浏览器镜像(约2GB) runtime-sandbox-builder browser # 构建文件系统镜像(约2GB) runtime-sandbox-builder filesystem ``` -------------------------------- ### Troubleshoot Sandbox Startup Timeout Source: https://runtime.agentscope.io/zh/sandbox_troubleshooting Diagnoses 'TimeoutError: Runtime service did not start within the specified timeout' by guiding users to inspect container logs. This involves listing running containers, executing into the relevant container, navigating to the log directory, and viewing specific log files like agentscope_runtime.err.log and supervisord.log. ```shell docker ps ``` ```shell docker exec -it /bin/bash ``` ```shell cd /var/log && ls -l ``` ```shell cat agentscope_runtime.err.log ``` -------------------------------- ### 克隆 AgentScope Runtime 仓库并安装开发依赖 Source: https://runtime.agentscope.io/zh/README 克隆 AgentScope Runtime GitHub 仓库并安装开发环境所需的依赖包。此命令需要已安装 Git 和 Python 3.10+。 ```bash git clone https://github.com/agentscope-ai/agentscope-runtime.git cd agentscope-runtime pip install -e ".[dev]" ``` -------------------------------- ### 直接启动服务器(使用 .env 文件) Source: https://runtime.agentscope.io/zh/sandbox_advanced 在配置好 `.env` 文件后,可以直接启动服务器。服务器将自动加载 `.env` 文件中的配置,包括自定义设置。 ```shell runtime-sandbox-server ``` -------------------------------- ### Manage Service Lifecycle in Python Source: https://runtime.agentscope.io/zh/context_manager Explains how to manage the lifecycle of the session history service, including starting and stopping it. While these operations might be optional for simple in-memory implementations, they are crucial for services that interact with external resources. The example also shows how to check the health status of the service. Dependencies include AgentScope's session history service implementation. ```python # 启动服务(对于InMemorySessionHistoryService是可选的) await session_history_service.start() # 检查服务健康状态 is_healthy = await session_history_service.health() # 停止服务(对于InMemorySessionHistoryService是可选的) await session_history_service.stop() ``` -------------------------------- ### 构建自定义沙箱镜像 - runtime-sandbox-builder Source: https://runtime.agentscope.io/zh/sandbox_advanced 使用 `runtime-sandbox-builder` 工具构建自定义沙箱镜像。需要提供镜像名称、Dockerfile 路径以及沙箱模块的扩展路径。 ```shell runtime-sandbox-builder my_custom_sandbox --dockerfile_path examples/custom_sandbox/Dockerfile --extension PATH_TO_YOUR_SANDBOX_MODULE ``` -------------------------------- ### AgentScope Runtime Integration Example (Python) Source: https://runtime.agentscope.io/zh/tracing Shows how the tracing module integrates with the AgentScope Runtime, specifically within a runner context. It includes an example of a stream_query method decorated with @trace and demonstrates its usage within an agent context. ```python from agentscope_runtime.engine.tracing import trace, TraceType # Example from runner.py @trace(TraceType.AGENT_STEP) async def stream_query( self, user_id: str, request: dict, tools: list = None, **kwargs: Any, ): """Stream query method with automatic tracing.""" # Agent step logic here response = {"user_id": user_id, "status": "processing"} return response # Usage within an agent context async def example_agent_usage(): """Example demonstrating the usage of a traced method.""" result = await stream_query( user_id="user123", request={"query": "Hello, agent!"}, tools=[] ) return result # Execution result = await example_agent_usage() print("Agent result:", result) ``` -------------------------------- ### Initialize Sandbox Service (Python) Source: https://runtime.agentscope.io/zh/environment_manager Shows how to initialize a SandboxService instance. It covers both local instantiation and configuration for a remote sandbox service using a base URL and bearer token. ```python from agentscope_runtime.engine.services.sandbox_service import SandboxService # 创建并启动沙盒服务 sandbox_service = SandboxService() # 或者使用远程沙盒服务 # sandbox_service = SandboxService( # base_url="http://sandbox-server:8000", # bearer_token="your-auth-token" # ) ``` -------------------------------- ### Create Service with Lifecycle Manager - Python Source: https://runtime.agentscope.io/zh/manager Demonstrates how to create a custom service that implements the ServiceWithLifecycleManager interface with async start, stop, and health check methods. The service tracks its lifecycle state and provides a health status based on whether it has been started and not stopped. ```python from agentscope_runtime.engine.services.base import ServiceWithLifecycleManager class MockService(ServiceWithLifecycleManager): def __init__(self, name: str): self.name = name self.started = False self.stopped = False async def start(self): self.started = True async def stop(self): self.stopped = True async def health(self) -> bool: return self.started and not self.stopped ``` -------------------------------- ### Build BFCL Docker Image from Dockerfile Source: https://runtime.agentscope.io/zh/training_sandbox Build the BFCL Training Sandbox Docker image locally from the Dockerfile. Run this command from the root directory to build the image with a custom or standard configuration. ```bash docker build -f src/agentscope_runtime/sandbox/box/training_box/environments/bfcl/Dockerfile -t agentscope/runtime-sandbox-bfcl:latest . ``` -------------------------------- ### Lifecycle Hooks Source: https://runtime.agentscope.io/zh/agent_app Execute custom logic before the application starts and after it finishes, useful for resource initialization and cleanup. ```APIDOC ## Lifecycle Hooks ### Description Allows execution of custom logic before the API service starts (`before_start`) and after it finishes (`after_finish`), useful for initializing resources or performing cleanup. ### Method POST (for the main processing endpoint) ### Endpoint `/process` (default) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **before_start** (function) - Optional - A callback function executed before the API service starts. - **after_finish** (function) - Optional - A callback function executed after the API service finishes. ### Request Example ```python async def init_resources(app, **kwargs): print("🚀 服务启动中,初始化资源...") async def cleanup_resources(app, **kwargs): print("🛑 服务即将关闭,释放资源...") app = AgentApp( agent=agent, before_start=init_resources, after_finish=cleanup_resources ) ``` ### Response #### Success Response (200) Standard AgentApp processing response. #### Response Example (Depends on the main processing endpoint's response) ``` -------------------------------- ### Best Practices Source: https://runtime.agentscope.io/zh/protocol Recommendations for effectively using the Agent API. ```APIDOC ## Best Practices 1. **Stream Handling**: * Buffer incremental fragments until `status=completed` is received. * Use `msg_id` to associate content with its parent message. * Maintain the order of fragments for multi-part messages using `index`. 2. **Error Handling**: * Check the `error` field in responses for detailed error information. * Monitor for `failed` state transitions. * Implement retry logic for recoverable errors. 3. **State Management**: * Use `session_id` to maintain session continuity. * Track `created_at` and `completed_at` to monitor latency. * Use `sequence_number` for ordering if implemented. ``` -------------------------------- ### 连接远程沙箱服务器 - Python BaseSandbox Source: https://runtime.agentscope.io/zh/sandbox 使用Python中的BaseSandbox类连接到远程沙箱服务器。通过指定base_url参数连接到远程服务器,并执行IPython单元代码。需要替换IP地址为实际的服务器地址,服务器需运行在8000端口。 ```python with BaseSandbox(base_url="http://your_IP_address:8000") as box: print(box.run_ipython_cell(code="print('hi')")) ``` -------------------------------- ### Usage Example: User Query and Agent Response Stream Source: https://runtime.agentscope.io/zh/protocol Illustrates a typical request-response cycle for a user query. ```APIDOC ## Usage Example: User Query and Agent Response Stream **User Query Example**: ```json { "input": [{ "role": "user", "content": [{"type": "text", "text": "Describe this image"}], "type": "message" }], "stream": true, "model": "gpt-4-vision" } ``` **Agent Response Stream Example**: ```json {"id":"response_123","object":"response","status":"created"} {"id":"msg_abc","object":"message","type":"assistant","status":"created"} {"status":"in_progress","type":"text","index":0,"delta":true,"text":"This","object":"content","msg_id":"msg_abc"} {"status":"in_progress","type":"text","index":0,"delta":true,"text":" image shows...","object":"content","msg_id":"msg_abc"} {"status":"completed","type":"text","index":0,"delta":false,"text":"This image shows...","object":"content","msg_id":"msg_abc"} {"id":"msg_abc","status":"completed","object":"message"} {"id":"response_123","status":"completed","object":"response"} ``` ``` -------------------------------- ### Pull and Tag BFCL Docker Images for ARM64 and X86_64 Source: https://runtime.agentscope.io/zh/training_sandbox Pull the BFCL Training Sandbox Docker images from Alibaba Cloud Container Registry (ACR) for both ARM64 and X86_64 architectures, then retag them with standard names for seamless integration with AgentScope Runtime. ```bash # Pull and tag BFCL ARM64 architecture image docker pull agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-bfcl:latest-arm64 && docker tag agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-bfcl:latest-arm64 agentscope/runtime-sandbox-bfcl:latest-arm64 # Pull and tag BFCL X86_64 architecture image docker pull agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-bfcl:latest && docker tag agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-bfcl:latest agentscope/runtime-sandbox-bfcl:latest ``` -------------------------------- ### Create and Use Environment Manager (Python) Source: https://runtime.agentscope.io/zh/environment_manager Demonstrates the basic usage of EnvironmentManager to create, connect, and release sandboxes. It initializes the manager with a SandboxService instance and shows how to interact with sandboxes using session and user IDs. ```python from agentscope_runtime.engine.services.environment_manager import ( create_environment_manager, ) from agentscope_runtime.engine.services.sandbox_service import SandboxService async def quickstart(): async with create_environment_manager( sandbox_service=SandboxService() ) as manager: boxes = manager.connect_sandbox( session_id="s1", user_id="u1", env_types=[], tools=[], ) # 使用 boxes manager.release_sandbox(session_id="s1", user_id="u1") ``` -------------------------------- ### Get Session (Python) Source: https://runtime.agentscope.io/zh/context_manager Retrieves a specific conversation session using the user ID and session ID. For the in-memory implementation, if a session does not exist, it will be automatically created. ```python import asyncio async def main(): user_id = "u1" # 检索现有会话(在内存实现中如果不存在会自动创建) retrieved_session = await session_history_service.get_session(user_id, "s1") assert retrieved_session is not None await main() ``` -------------------------------- ### Pull and Tag Appworld Docker Images for ARM64 and X86_64 Source: https://runtime.agentscope.io/zh/training_sandbox Pull the Appworld Training Sandbox Docker images from Alibaba Cloud Container Registry (ACR) for both ARM64 and X86_64 architectures, then retag them with standard names for seamless integration with AgentScope Runtime. ```bash # Pull and tag Appworld ARM64 architecture image docker pull agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-appworld:latest-arm64 && docker tag agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-appworld:latest-arm64 agentscope/runtime-sandbox-appworld:latest-arm64 # Pull and tag Appworld X86_64 architecture image docker pull agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-appworld:latest && docker tag agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-appworld:latest agentscope/runtime-sandbox-appworld:latest ``` -------------------------------- ### 设置 Sandbox 镜像版本标签环境变量 Source: https://runtime.agentscope.io/zh/sandbox_advanced 配置 Docker 镜像版本标签(Tag)。默认值为 'latest',可修改为特定版本号或自定义标签以使用不同版本的 Sandbox 镜像。 ```bash export RUNTIME_SANDBOX_IMAGE_TAG="my_custom" ``` -------------------------------- ### Streaming Response Example (JSON) Source: https://runtime.agentscope.io/zh/protocol Demonstrates the structure of streaming responses, showing incremental content updates with status indicators. This format allows for real-time delivery of generated content. ```json {"status":"created","id":"response_...","object":"response"} {"status":"created","id":"msg_...","object":"message","type":"assistant"} {"status":"in_progress","type":"text","index":0,"delta":true,"text":"Hello","object":"content"} {"status":"in_progress","type":"text","index":0,"delta":true,"text":", ","object":"content"} {"status":"in_progress","type":"text","index":0,"delta":true,"text":"world","object":"content"} {"status":"completed","type":"text","index":0,"delta":false,"text":"Hello, world!","object":"content"} {"status":"completed","id":"msg_...","object":"message", ...} {"status":"completed","id":"response_...","object":"response", ...} ``` -------------------------------- ### 导入AgentScope Runtime依赖 Source: https://runtime.agentscope.io/zh/quickstart 导入AgentScope Runtime框架所需的关键模块,包括AgentApp、AgentScopeAgent、LocalDeployManager、OpenAIChatModel和ReActAgent。这些是构建智能体应用的基础。 ```python import os from agentscope_runtime.engine import AgentApp from agentscope_runtime.engine.agents.agentscope_agent import AgentScopeAgent from agentscope_runtime.engine.deployers import LocalDeployManager from agentscope.model import OpenAIChatModel from agentscope.agent import ReActAgent print("✅ 依赖导入成功") ``` -------------------------------- ### Take Screenshot with BrowserSandbox in Python Source: https://runtime.agentscope.io/zh/api/sandbox Captures a screenshot of the browser window or a specific element using BrowserSandbox. Options include saving to a file or getting raw image data. ```python browser_sandbox.browser_take_screenshot( filename="screenshot.png", element=".main-content", raw=False ) ```