AgentScope Runtime
AgentScope Runtime is a production-ready framework for deploying agent applications, providing secure sandboxed execution environments, scalable deployment solutions (local, Kubernetes, serverless), and multi-framework support. It exposes agents as streaming, production-ready APIs with full-stack observability. The current version is 1.1.3, and it maintains an active development and release cadence.
Common errors
-
Failed to build image: Runner image build failed: Command '['docker', 'build', '-t', ...']' returned non-zero exit status 1. (Error response from daemon: dockerfile parse error line 19: unknown instruction: EOF)
cause This error typically indicates an issue during the Docker image build process for deploying an agent, possibly due to malformed Dockerfile generation or specific Docker environment issues.fixInspect the generated Dockerfile for syntax errors or unexpected characters. Ensure your Docker daemon is running correctly and has sufficient permissions. Check for common Docker build environment issues. -
Pyright reports issue when there is no py.typed file in the package, and it is currently missing. (Error: '找不到 "agentscope_runtime.engine.helpers.agent_api_builder" 的 Stub 文件 Pylance (reportMissingTypeStubs)')
cause The `agentscope-runtime` package is missing a `py.typed` marker file, which prevents static type checkers like Pyright or Pylance from correctly finding and using type stubs.fixThis is a library-level issue. Users can work around it by configuring their type checker to ignore missing type stubs for `agentscope_runtime` (e.g., add `"agentscope_runtime"` to `reportMissingTypeStubs` in Pyright/Pylance settings) or wait for a future library update that includes the `py.typed` file.
Warnings
- breaking AgentApp's architecture was refactored in v1.1.0 to directly inherit from FastAPI, deprecating the previous factory pattern. Code using `create_agent_app` will break.
- breaking Future AgentScope 2.0.0 (core framework) plans to consolidate some `agentscope-runtime` deployment capabilities directly into the core `agentscope` library. This will involve breaking changes and refactoring of core data structures and tool execution.
- gotcha Using sandboxed tools (e.g., `BrowserSandbox`, `FilesystemSandbox`) often requires a running Docker daemon and pulling specific Docker images. The quickstart examples using sandboxes might not work out-of-the-box without Docker setup.
- gotcha The quickstart and examples often use `fakeredis` for local session management. This is for development/testing only. For production deployments, a robust Redis client and connection to a real Redis instance are required.
Install
-
pip install agentscope-runtime -
pip install "agentscope-runtime[ext]"
Imports
- AgentApp
from agentscope_runtime.factory import create_agent_app
from agentscope_runtime.engine import AgentApp
- LocalDeployManager
from agentscope_runtime.engine.deployers import LocalDeployManager
- ReActAgent
from agentscope.agent import ReActAgent
- RedisSession
from agentscope.session import RedisSession
Quickstart
import os
import uvicorn
from contextlib import asynccontextmanager
from fastapi import FastAPI
from agentscope.agent import ReActAgent
from agentscope.model import DashScopeChatModel
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.session import RedisSession
from agentscope_runtime.engine import AgentApp
from agentscope_runtime.engine.schemas.agent_schemas import AgentRequest
from agentscope.pipeline import stream_printing_messages
import fakeredis # For local development/testing
# Configure API key (replace with your actual key or other LLM provider config)
# os.environ['DASHSCOPE_API_KEY'] = 'YOUR_API_KEY_HERE'
@asynccontextmanager
async def lifespan(app: FastAPI):
# Initialize Session manager (using fakeredis for demonstration)
fake_redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
app.state.session = RedisSession(connection_pool=fake_redis.connection_pool)
print("\n🚀 AgentApp starting up...")
yield
print("\n🛑 AgentApp shutting down...")
agent_app = AgentApp(lifespan=lifespan)
@agent_app.query(framework="agentscope")
async def query_agent(msgs, request: AgentRequest = None, **kwargs):
# Example agent setup - customize with your model, tools, and memory
dashscope_api_key = os.environ.get('DASHSCOPE_API_KEY', 'sk-example') # Use actual key in production
if not dashscope_api_key or dashscope_api_key == 'sk-example':
print("Warning: DASHSCOPE_API_KEY not set. Using dummy key. Model interactions may fail.")
model = DashScopeChatModel(
model_name="qwen-plus", # Or your preferred model
api_key=dashscope_api_key,
# Other model parameters like `temperature`, `max_tokens` can be set here
)
agent = ReActAgent(
name="SimpleAgent",
model=model,
memory=InMemoryMemory(), # Or RedisSession for persistence
formatter=DashScopeChatFormatter(),
)
# Load session context (if using RedisSession in app.state.session)
if hasattr(request, 'session_id') and app.state.session:
session_id = request.session_id
# In a real scenario, you'd load context using session_id
# For this simple example, we'll just acknowledge it.
print(f"Processing request for session_id: {session_id}")
# Stream responses
async for msg, last in stream_printing_messages(agent.reply(msgs, **kwargs)):
yield msg, last
# To run this: save as e.g., `main.py` and run `uvicorn main:agent_app --reload --port 8090`
# Test with curl:
# curl -N -X POST "http://localhost:8090/process" \
# -H "Content-Type: application/json" \
# -d '{ "input": [ { "role": "user", "content": [ { "type": "text", "text": "What is the capital of France?" } ] } ], "session_id": "session_1" }'