### Start AgentRun Server (Python) Source: https://docs.agent.run/docs/tutorial/quickstart/manual This Python snippet demonstrates how to start the AgentRun server with a single line of code. It requires an `invoke_agent` function to be defined elsewhere. This is the simplest way to integrate AgentRun with other projects. ```python from agentrun import AgentRunServer # Assuming invoke_agent is defined elsewhere # def invoke_agent(...): # ... AgentRunServer(invoke_agent=invoke_agent).start() ``` -------------------------------- ### Data Analysis Agent Example (Python) Source: https://docs.agent.run/docs/tutorial/core/sandbox This comprehensive example demonstrates building a data analysis agent using the code interpreter sandbox. It includes creating a sandbox, uploading data, installing necessary libraries, performing statistical analysis, and generating a summary. ```python from agentrun.sandbox import Sandbox, TemplateType from agentrun.integration.langchain import model, sandbox_toolset # 创建沙箱 sandbox = Sandbox.create( template_type=TemplateType.CODE_INTERPRETER, template_name="data-analysis-sandbox", sandbox_idle_timeout_seconds=1800 ) # 上传数据文件 sandbox.file_system.upload( local_file_path="./sales_data.csv", target_file_path="/home/user/sales_data.csv" ) # 创建执行上下文 context = sandbox.context.create() # 安装分析所需的库(如果模板中未预装) context.execute(""" import subprocess subprocess.run(['pip', 'install', 'pandas', 'matplotlib', 'seaborn']) """) # 执行数据分析 analysis_code = """ import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 加载数据 df = pd.read_csv('/home/user/sales_data.csv') # 基础统计 stats = { 'total_rows': len(df), 'columns': list(df.columns), 'summary': df.describe().to_dict() } ``` -------------------------------- ### Distributed Deployment Startup Commands Source: https://docs.agent.run/docs/tutorial/advanced/best-practices-a2a-by-me-a-coffee This set of shell commands outlines the sequence for starting services in a distributed deployment. It includes starting the coffee backend, delivery backend, their respective A2A services, and finally the gateway, with necessary environment variables set for inter-service communication. ```bash # 终端 1:启动咖啡店后端 API python -m coffee.main # 终端 2:启动配送后端 API python -m delivery.main # 终端 3:启动咖啡店 A2A 服务 python -m coffee.a2a # 终端 4:启动配送 A2A 服务 python -m delivery.a2a # 终端 5:启动网关 export COFFEE_A2A_URL="http://localhost:8003/.well-known/agent-card.json" export DELIVERY_A2A_URL="http://localhost:8004/.well-known/agent-card.json" python -m gateway.main ``` -------------------------------- ### Recommended Parameter Handling Strategy (Python) Source: https://docs.agent.run/docs/tutorial/integration/openai-compatibility Presents a Python code example for implementing a recommended parameter handling strategy in the `invoke_agent` function. This includes documenting supported parameters, validating input, logging ignored parameters, and graceful degradation. ```python def invoke_agent(request: AgentRequest): # 参数分类处理 SUPPORTED = ['temperature', 'max_tokens', 'top_p'] IGNORED = ['model', 'n', 'tools'] # 记录被忽略的参数 for param in IGNORED: if hasattr(request, param): logger.warning(f"参数 '{param}' 在 Agent 模式下不支持,将被忽略") # 处理支持的参数 config_params = {} for param in SUPPORTED: if hasattr(request, param): value = getattr(request, param) # 参数验证(示例) if param == 'temperature' and not (0 <= value <= 2): logger.warning(f"temperature={value} 超出范围 [0,2],使用默认值") continue config_params[param] = value logger.debug(f"应用参数: {param}={value}") # 继续执行... ``` -------------------------------- ### Customizing Parameter Handling Source: https://docs.agent.run/docs/tutorial/integration/openai-compatibility Guides on how to modify the Agent service to handle OpenAI parameters like `temperature`, `max_tokens`, and `model` dynamically. ```APIDOC ## Customizing OpenAI Parameter Handling ### Description This section details how to modify the `invoke_agent` function to enable or dynamically handle specific OpenAI API parameters that are ignored by default. ### Handling Standard Parameters (e.g., temperature, max_tokens) To make parameters like `temperature`, `max_tokens`, `top_p`, etc., effective, they need to be explicitly passed to the underlying agent's configuration. ```python def invoke_agent(request: AgentRequest): content = request.messages[0].content input = {"messages": [{"role": "user", "content": content}]} # Collect OpenAI standard parameters config_params = {} openai_params = [ 'temperature', 'max_tokens', 'top_p', 'frequency_penalty', 'presence_penalty', 'stop', 'seed' ] for param in openai_params: if hasattr(request, param): config_params[param] = getattr(request, param) # Pass parameters to the agent runtime configuration runtime_config = {"configurable": config_params} if config_params else {} try: if request.stream: def stream_generator(): result = agent.stream( input, config=runtime_config, # ← Key: Pass configuration stream_mode="messages" ) for chunk in result: yield pydash.get(chunk, "[0].content") return stream_generator() else: result = agent.invoke( input, config=runtime_config # ← Key: Pass configuration ) return pydash.get(result, "messages.-1.content") except Exception as e: logger.error("调用出错: %s", e) raise e ``` **Note:** The actual effectiveness of these parameters depends on the underlying model's support. ### Handling Dynamic `model` Parameter To support switching models dynamically based on the request: ```python def invoke_agent(request: AgentRequest): content = request.messages[0].content input = {"messages": [{"role": "user", "content": content}]} # Dynamically handle model parameter model_name = getattr(request, 'model', MODEL_NAME) # Use MODEL_NAME as default # If the requested model differs from the preset, create a new agent if model_name != MODEL_NAME: dynamic_agent = create_agent( model=model(model_name), # Use the requested model tools=[*code_interpreter_tools], system_prompt="你是一个 AgentRun 的 AI 专家..." ) else: dynamic_agent = agent # Process other parameters... config_params = {} for param in ['temperature', 'max_tokens', 'top_p']: if hasattr(request, param): config_params[param] = getattr(request, param) runtime_config = {"configurable": config_params} if config_params else {} # Execute using dynamic_agent if request.stream: result = dynamic_agent.stream(input, config=runtime_config, stream_mode="messages") # ... stream processing ... else: result = dynamic_agent.invoke(input, config=runtime_config) # ... invoke processing ... ``` **Note:** Dynamically creating agents can increase response latency; use this approach only when necessary. ### Recommended Parameter Handling Strategy 1. **Clear Documentation**: Inform users which parameters are effective. 2. **Parameter Validation**: Check parameter ranges and types. 3. **Logging**: Record ignored or transformed parameters. 4. **Graceful Degradation**: Provide warnings for unsupported parameters instead of errors. ```python def invoke_agent(request: AgentRequest): # Categorize parameters SUPPORTED = ['temperature', 'max_tokens', 'top_p'] IGNORED = ['model', 'n', 'tools'] # Log ignored parameters for param in IGNORED: if hasattr(request, param): logger.warning(f"Parameter '{param}' is not supported in Agent mode and will be ignored") # Process supported parameters config_params = {} for param in SUPPORTED: if hasattr(request, param): value = getattr(request, param) # Parameter validation (example) if param == 'temperature' and not (0 <= value <= 2): logger.warning(f"temperature={value} is out of range [0,2], using default value") continue config_params[param] = value logger.debug(f"Applying parameter: {param}={value}") # Continue execution... ``` ``` -------------------------------- ### AgentRunServer Start Method Source: https://docs.agent.run/docs/api/python/server Starts the AgentRunServer HTTP server, specifying the host, port, and log level. Additional keyword arguments can be passed to `uvicorn.run`. ```python def start(self, host: str = '0.0.0.0', port: int = 9000, log_level: str = 'info', **kwargs: Any) ``` -------------------------------- ### Execute Python Code in a Context (Python) Source: https://docs.agent.run/docs/tutorial/core/sandbox This example illustrates how to create an execution context within a sandbox and execute Python code. It demonstrates calculating circle area and getting the current time. The results, including stdout and stderr, are captured. ```python # 创建执行上下文 context = sandbox.context.create( language="python", cwd="/home/user" ) # 在上下文中执行代码 result = context.execute(""" import math import datetime # 计算圆的面积 radius = 5 area = math.pi * radius ** 2 # 获取当前时间 current_time = datetime.datetime.now() print(f"半径为 {radius} 的圆面积: {area:.2f}") print(f"当前时间: {current_time}") """) print("执行结果:") print(result.get("stdout")) ``` -------------------------------- ### Synchronous and Asynchronous Tool Invocation Source: https://docs.agent.run/docs/tutorial/core/toolset Shows how to call a tool within a toolset using its name and arguments. It covers both synchronous calls that wait for a response and asynchronous calls using `call_tool_async` for concurrent operations. The example also includes parsing the tool's result, checking for success, and extracting data or error messages. ```python import asyncio from agentrun.toolset import ToolSetClient # 获取工具集 toolset = ToolSetClient().get("weather-api") # 同步调用工具查询天气 result_sync = toolset.call_tool( name="get_current_weather", arguments={ "location": "杭州", "unit": "celsius" } ) print(f"同步查询结果: {result_sync}") # 异步调用工具查询天气 async def query_weather_async(): toolset_async = ToolSetClient().get("weather-api") result = await toolset_async.call_tool_async( name="get_current_weather", arguments={"location": "杭州"} ) return result # 运行异步任务 result_async = asyncio.run(query_weather_async()) print(f"异步查询结果: {result_async}") # 解析结果 (以同步结果为例) if result_sync.get("success"): weather_data = result_sync.get("data", {}) temperature = weather_data.get("temperature") description = weather_data.get("description") print(f"当前温度: {temperature}°C") print(f"天气状况: {description}") else: error_msg = result_sync.get("error", "未知错误") print(f"查询失败: {error_msg}") ``` -------------------------------- ### Create and Call ReActAgent Source: https://docs.agent.run/docs/tutorial/discover/framework-langchain-deployment Demonstrates how to create a ReActAgent with a system prompt, model, and toolkit, and then call it asynchronously to get a reply. ```python from agentscope.agents import ReActAgent from agentrun.msg import Msg # Assuming 'llm' and 'toolkit' are defined elsewhere # llm = ... # toolkit = ... # Create Agentagent = ReActAgent( name="assistant", sys_prompt="您是一个智能助手", model=llm, toolkit=toolkit, ) # Call Agent result = await agent.reply(Msg(name="user", content="查询上海天气", role="user")) ``` -------------------------------- ### Dockerfile for Service Containerization Source: https://docs.agent.run/docs/tutorial/advanced/best-practices-a2a-by-me-a-coffee This Dockerfile provides a template for containerizing individual services. It sets up the Python environment, installs dependencies, copies the application code, and defines the command to run the service, using `python -m coffee.main` as an example. ```dockerfile FROM python:3.10-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . ENV PYTHONPATH=/app CMD ["python", "-m", "coffee.main"] ``` -------------------------------- ### Agent Invocation Example (Python) Source: https://docs.agent.run/docs/api/python/server/invoker An example demonstrating how to use the AgentInvoker. It shows defining a simple agent function and then using the invoker to call it with an AgentRequest, illustrating the automatic conversion of the return value to an AgentRunResult. ```python >>> def my_agent(request: AgentRequest) -> str: ... return "Hello" # 自动转换为 AgentRunResult >>> >>> invoker = AgentInvoker(my_agent) >>> result = await invoker.invoke(AgentRequest(...)) >>> # result 是 AgentRunResult 对象 ``` -------------------------------- ### Retrieve and Inspect ToolSets using ToolSetClient Source: https://docs.agent.run/docs/tutorial/core/toolset Demonstrates how to initialize a ToolSetClient, fetch a specific toolset by name, and then list all tools within that toolset, including their names, descriptions, and parameter definitions. It also shows how to list all available toolsets on the platform. ```python from agentrun.toolset import ToolSetClient # 创建客户端 client = ToolSetClient() # 获取指定名称的工具集 toolset = client.get("weather-api") print(f"工具集: {toolset.name}") print(f"描述: {toolset.description}") # 列出工具集中的所有工具 tools = toolset.list_tools() for tool in tools: print(f"工具名称: {tool.name}") print(f"工具描述: {tool.description}") print(f"参数: {tool.parameters}") print("---") # 列出所有工具集 all_toolsets = client.list() for ts in all_toolsets: print(f"{ts.name}: {ts.description}") ``` -------------------------------- ### Example: Create CommonModel from ModelProxy Source: https://docs.agent.run/docs/api/python/integration/builtin/model Illustrates creating a `CommonModel` object from a `ModelProxy` instance. This involves first getting the `ModelProxy` by name and then passing it to the `model` function. ```python >>> proxy = ModelProxy.get_by_name("my-proxy") >>> m = model(proxy) ``` -------------------------------- ### Python Agent Setup with Web Search Source: https://docs.agent.run/docs/tutorial/quickstart/manual This Python code configures an AgentRun agent to assist users by performing web searches. It uses the 'qwen3-max' model and integrates with the AgentRun browser sandbox to navigate and extract information from web pages. The agent is designed to search, gather relevant information from multiple sources, and cite its findings. ```python from agentrun import AgentRequest from agentrun.integration.langchain import ( model, sandbox_toolset, AgentRunConverter, ) from agentrun.server import AgentRunServer from agentrun.sandbox import TemplateType from langchain.agents import create_agent import os MODEL_SERVICE = os.getenv("MODEL_SERVICE", "") MODEL_NAME = os.getenv("MODEL_NAME", "qwen3-max") SANDBOX_NAME = os.getenv("SANDBOX_NAME", "") agent = create_agent( # 只需要一行代码,即可在您喜爱的框架中使用 AgentRun 注册的模型 model=model(MODEL_SERVICE, model=MODEL_NAME), system_prompt=""" 你是 AgentRun 的 AI 助手,可以通过网络搜索帮助用户解决问题 你的工作流程如下 - 当用户向你提问概念性问题时,不要直接回答,而是先进行网络搜索 - 使用 Browser 工具打开百度搜索。如果要搜索 AgentRun,对应的搜索链接为: `https://www.baidu.com/s?ie=utf-8&wd=agentrun`。为了节省 token 使用,不要使用 `snapshot` 获取完整页面内容,而是通过 `evaluate` 获取你需要的部分 - 获取百度搜索的结果,根据相关性分别打开子页面获取内容 - 如果子页面的相关度较低,则可以直接忽略 - 如果子页面的相关度较高,则将其记录为可参考的资料,记录页面标题和实时的 url - 当你获得至少 3 条网络信息后,可以结束搜索,并根据搜索到的结果回答用户的问题。 - 如果某一部分回答引用了网络的信息,需要进行标注,并在回答的最后给出跳转链接 """, # 只需要一行代码,即可在您喜爱的框架中使用 AgentRun 的 Sandbox 及其他工具 tools=[*sandbox_toolset(SANDBOX_NAME, template_type=TemplateType.BROWSER)], ) async def invoke_agent(req: AgentRequest): try: converter = AgentRunConverter() result = agent.astream_events( { "messages": [ {"role": msg.role, "content": msg.content} for msg in req.messages ] }, config={"recursion_limit": 1000}, ) async for event in result: for agentrun_event in converter.convert(event): yield agentrun_event except Exception as e: print(e) raise Exception("Internal Error") ``` -------------------------------- ### 设置自定义请求超时时间 Source: https://docs.agent.run/docs/tutorial/advanced/best-practices 通过 Config 对象设置更长的请求超时和读取超时时间,适用于需要长时间运行的任务。在执行代码时传入配置。 ```python from agentrun.utils.config import Config # 为长时间运行的任务设置更长的超时 config = Config( timeout=1800, # 30 分钟 read_timeout=100000 # 读取超时 ) # 在调用时传入配置 result = sandbox.context.execute(code, config=config) ``` -------------------------------- ### Get Suggested Route Prefix for Protocol Source: https://docs.agent.run/docs/api/python/server/protocol This Python function returns the suggested route prefix for a protocol. The server uses this prefix if no specific prefix is provided by the user. Examples include '/v1' for OpenAI, '/anthropic' for Anthropic, or an empty string for no prefix. ```python def get_prefix(self) -> str: # Returns the suggested route prefix, e.g., "/v1" or "" pass ``` -------------------------------- ### Unified Deployment Startup Script Source: https://docs.agent.run/docs/tutorial/advanced/best-practices-a2a-by-me-a-coffee This command initiates the unified deployment mode by starting the gateway service. The gateway's lifespan hook is responsible for initializing databases and creating the root agent. ```bash python -m gateway.main ``` -------------------------------- ### Manual Deployment Commands Source: https://docs.agent.run/docs/tutorial/advanced/07 Provides examples of how to manually deploy the project to different environments using the `deploy.sh` script. It shows commands for deploying to development and production environments, as well as an option to skip tests for a faster deployment. ```shell # Deploy to development environment ./scripts/deploy.sh dev # Deploy to production environment ./scripts/deploy.sh prod # Skip test for quick deployment ./scripts/deploy.sh dev --skip-test ``` -------------------------------- ### Get AgentRun SDK Configuration Values (Python) Source: https://docs.agent.run/docs/api/python/utils/config Provides examples of retrieving specific configuration values from an AgentRun SDK Config object. This includes methods for accessing Access Key ID, Access Key Secret, security token, account ID, custom token, region ID, timeouts, and custom endpoints. ```python from agent_run_sdk.config import Config config = Config( account_id="your-account-id", access_key_id="your-key-id", access_key_secret="your-secret", region_id="cn-hangzhou", timeout=600 ) print(f"Access Key ID: {config.get_access_key_id()}") print(f"Account ID: {config.get_account_id()}") print(f"Region ID: {config.get_region_id()}") print(f"Timeout: {config.get_timeout()}") print(f"Data Endpoint: {config.get_data_endpoint()}") ``` -------------------------------- ### Initialize and Run Mastra Agent with AgentRun Server (TypeScript) Source: https://docs.agent.run/docs/tutorial/integration/mastra This code snippet sets up a Mastra agent within an AgentRun server. It defines the agent's instructions, model, and tools, and then creates a server to handle agent invocations. The server is configured to accept cross-origin requests and starts listening on a specified port. It also includes example curl commands for testing the agent. ```typescript import { Agent } from '@mastra/core/agent'; import { AgentRunServer, type AgentRequest } from '@agentrun/sdk/server'; import { MastraConverter, type AgentEventItem, model, toolset, sandbox, } from '@agentrun/sdk/integration/mastra'; const mastraAgent = new Agent({ id: 'run_agent', name: 'AgentRun', instructions: ` 你是一个智能助手,你会帮助用户完成各种任务。你的输出后,必须是返向输出的。 如,用户输入 “你好”,应该输出 “?么的您助帮以可么什有,好您” `.trim(), model: () => model({ name: 'ohyee-test' }), tools: async () => { const sandboxTools = await sandbox({ templateName: 'my-agentrun-browser' }); const toolsetTools = await toolset({ name: 'my-agentrun-time-mcp' }); const allTools = { ...sandboxTools, ...allTools }; return allTools; }, }); async function* invokeAgent( request: AgentRequest, ): AsyncGenerator { const converter = new MastraConverter(); const mastraStream = await mastraAgent.stream( request.messages.map( (msg) => ({ role: msg.role, content: msg.content || '', }) as any, ), ); for await (const chunk of mastraStream.fullStream) { const events = converter.convert(chunk); for (const event of events) { yield event; } } } const server = new AgentRunServer({ invokeAgent, config: { corsOrigins: ['*'] }, }); console.log(` curl http://127.0.0.1:9000/openai/v1/chat/completions -X POST \ -H "Content-Type: application/json" \ -d '{"messages": [{"role": "user", "content": "天空为什么是蓝的?"}], "stream": true}' curl http://127.0.0.1:9000/ag-ui/agent -X POST \ -H "Content-Type: application/json" \ -d '{"messages": [{"role": "user", "content": "天空为什么是蓝的?"}]}' `); server.start({ port: 9001 }); ``` -------------------------------- ### AgentRuntimeClient Initialization Source: https://docs.agent.run/docs/api/python/agent_runtime/client Initializes the AgentRuntimeClient. Configuration is optional. ```APIDOC ## AgentRuntimeClient Initialization ### Description Initializes the AgentRuntimeClient. Configuration is optional. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # No direct request example for constructor ``` ### Response #### Success Response None (initialization) #### Response Example ```json # No direct response example for constructor ``` ``` -------------------------------- ### Install AgentRun SDK (Python) Source: https://docs.agent.run/docs/tutorial/faq Installs the AgentRun SDK using pip. Requires Python 3.10 or higher. ```python pip install agentrun-sdk ``` -------------------------------- ### AgentRun Server Setup and Shutdown (Node.js) Source: https://docs.agent.run/docs/tutorial/quickstart/manual This code sets up the HTTP server for AgentRun using Node.js's 'http' module. It defines the port the server listens on and provides startup messages indicating available endpoints. It also includes graceful shutdown logic for the SIGINT signal, ensuring the browser is closed before the server terminates. ```javascript const server = createServer(handleRequest); process.on('SIGINT', async () => { console.log('\nShutting down...'); await closeBrowser(); server.close(() => process.exit(0)); }); server.listen(PORT, () => { console.log(` ======================================== AgentRun Server ======================================== AG-UI: http://127.0.0.1:${PORT}/ag-ui/agent OpenAI: http://127.0.0.1:${PORT}/openai/v1/chat/completions Health: http://127.0.0.1:${PORT}/health `); }); ``` -------------------------------- ### 正确使用异步上下文 Source: https://docs.agent.run/docs/tutorial/advanced/best-practices 在异步函数中避免直接调用同步方法,因为这可能导致事件循环阻塞。应使用异步兼容的方法或在单独的线程中执行同步操作。 ```python import asyncio # 错误:在异步函数中调用同步方法 # async def bad_example(): # result = model.completions(messages) # 阻塞事件循环 # return result ``` -------------------------------- ### Node.js HTTP Server with Browser Automation (Node.js) Source: https://docs.agent.run/docs/tutorial/quickstart/manual This Node.js example sets up an HTTP server that integrates with the AG-UI protocol using `@ag-ui/mastra`. It includes browser sandbox initialization using Playwright for web scraping and evaluation tasks. The agent is configured to perform web searches and answer questions based on the retrieved information. ```javascript /** * AgentRun Node.js -极简实现 * 使用 @ag-ui/mastra 简化 AG-UI 协议处理 */ import { createServer } from 'node:http'; import { Agent } from '@mastra/core/agent'; import { createTool } from '@mastra/core/tools'; import { z } from 'zod'; import { MastraAgent } from '@ag-ui/mastra'; import { EventEncoder } from '@ag-ui/encoder'; import { BrowserSandbox, ModelService } from '@agentrun/sdk'; import { chromium } from 'playwright'; // ============================================================================ // 配置 & 全局状态 // ============================================================================ const PORT = parseInt(process.env.PORT || '9000', 10); const MODEL_SERVICE = process.env.MODEL_SERVICE || ''; const MODEL_NAME = process.env.MODEL_NAME || 'qwen3-max'; const SANDBOX_NAME = process.env.SANDBOX_NAME || ''; let browser = null; let page = null; let sandbox = null; let template = null; let agent = null; // ============================================================================ // Browser Sandbox 初始化 // ============================================================================ async function initBrowser() { if (page) return page; console.log('Initializing Browser Sandbox...'); const sandbox = await BrowserSandbox.createFromTemplate(SANDBOX_NAME); await sandbox.waitUntilRunning(); const cdpUrl = await sandbox.getCdpUrl(); browser = await chromium.connectOverCDP(cdpUrl); const contexts = browser.contexts(); page = contexts[0]?.pages()[0] ?? (await browser.newContext()).newPage(); console.log('Browser Sandbox ready!'); return await page; } async function closeBrowser() { if (browser) await browser.close(); if (sandbox) await sandbox.delete(); // if (template) await template.delete(); browser = page = null; sandbox = template = null; } // ============================================================================ // 浏览器工具(精简版) // ============================================================================ const browserTools = { browser_navigate: createTool({ id: 'browser_navigate', description: 'Navigate to URL', inputSchema: z.object({ url: z.string().url() }), outputSchema: z.object({ url: z.string(), title: z.string() }), execute: async ({ context }) => { const p = await initBrowser(); await p.goto(context.url, { waitUntil: 'networkidle' }); return { url: p.url(), title: await p.title() }; }, }), browser_evaluate: createTool({ id: 'browser_evaluate', description: 'Execute JavaScript on page', inputSchema: z.object({ script: z.string() }), outputSchema: z.object({ result: z.unknown() }), execute: async ({ context }) => { const p = await initBrowser(); return { result: await p.evaluate(context.script) }; }, }), }; async function initAgent() { if (agent) return agent; const svc = await ModelService.get({ name: MODEL_SERVICE }); const info = await svc.modelInfo(); agent = new Agent({ id: 'search-agent', name: 'Search Agent', instructions: ` 你是 AgentRun 的 AI 助手,可以通过网络搜索帮助用户解决问题 你的工作流程如下 - 当用户向你提问概念性问题时,不要直接回答,而是先进行网络搜索 - 使用 browser_navigate 工具打开百度搜索。如果要搜索 AgentRun,对应的搜索链接为: https://www.baidu.com/s?ie=utf-8&wd=agentrun。为了节省 token 使用,通过 browser_evaluate 获取你需要的部分 - 获取百度搜索的结果,根据相关性分别打开子页面获取内容 - 如果子页面的相关度较低,则可以直接忽略 - 如果子页面的相关度较高,则将其记录为可参考的资料,记录页面标题和实时的 url - 当你获得至少 3 条网络信息后,可以结束搜索,并根据搜索到的结果回答用户的问题。 - 如果某一部分回答引用了网络的信息,需要进行标注,并在回答的最后给出跳转链接`, model: { id: `openai/${info.model || MODEL_NAME}`, url: info.baseUrl, apiKey: info.apiKey, }, tools: browserTools, }); return agent; } // ============================================================================ // HTTP 服务器 // ============================================================================ async function handleRequest(req, res) { const url = new URL(req.url || '/', `http://localhost:${PORT}`); // CORS res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); res.setHeader( 'Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization' ); if (req.method === 'OPTIONS') { res.writeHead(204); return res.end(); } // 路由 if (url.pathname === '/health') { res.writeHead(200, { 'Content-Type': 'application/json' }); ``` -------------------------------- ### Dynamic Toolset Creation with ApiSet from OpenAPI Source: https://docs.agent.run/docs/tutorial/core/toolset Illustrates advanced usage with the ApiSet class to dynamically create toolsets from an OpenAPI schema. It shows how to initialize ApiSet with schema URL, base URL, and authentication headers, list available tools, invoke tools directly, and convert tools into Python functions for use with frameworks like Google ADK. ```python from agentrun.toolset.api.openapi import ApiSet # 从 OpenAPI 规范创建工具集 apiset = ApiSet.from_openapi_schema( schema="https://api.example.com/openapi.json", base_url="https://api.example.com", headers={"Authorization": "Bearer your-token"} ) # 列出所有工具 tools = apiset.tools() for tool in tools: print(f"{tool.name}: {tool.description}") # 调用工具 result_invoke = apiset.invoke( name="get_weather", arguments={"location": "北京"} ) print(f"ApiSet invoke result: {result_invoke}") # 获取单个工具并转换为函数 get_weather_func = apiset.to_function_tool("get_weather") # 现在可以像调用普通函数一样使用 result_func = get_weather_func(location="上海", unit="celsius") print(f"ApiSet to_function_tool result: {result_func}") ``` -------------------------------- ### Install Serverless Devs CLI Source: https://docs.agent.run/docs/tutorial/discover/framework-langchain-deployment Installs the Serverless Devs CLI tool globally using npm. This tool is used for deploying applications to AgentRun. ```bash npm i -g @serverless-devs/s ``` -------------------------------- ### Initialize Credential Client (Python) Source: https://docs.agent.run/docs/api/python/credential/client Initializes the CredentialClient. It accepts an optional configuration object. This client provides methods for managing credentials. ```python def __init__(self, config: Optional[Config] = None) ``` -------------------------------- ### Initialize LangChain Project with AgentRun Template Source: https://docs.agent.run/docs/tutorial/discover/framework-langchain-deployment Initializes a new project for a LangChain agent using the agentrun-quick-start-langchain template. It requires Python 3.10 or higher. After initialization, it navigates into the code directory, sets up a virtual environment using uv, and installs project dependencies. ```bash # Initialize template s init agentrun-quick-start-langchain # Enter code directory cd agentrun-quick-start-langchain/code # Initialize virtual environment and install dependencies uv venv && uv pip install -r requirements.txt ``` -------------------------------- ### 沙箱复用以优化性能 Source: https://docs.agent.run/docs/tutorial/advanced/best-practices 推荐复用同一个沙箱实例来执行多个代码片段,以减少创建和销毁沙箱的开销。使用 try-finally 块确保沙箱最终被删除。 ```python # 不推荐:每次都创建新沙箱 # for code_snippet in code_list: # sandbox = Sandbox.create(...) # result = sandbox.context.execute(code_snippet) # sandbox.delete() # 推荐:复用沙箱 sandbox = Sandbox.create(...) try: for code_snippet in code_list: result = sandbox.context.execute(code_snippet) finally: sandbox.delete() ``` -------------------------------- ### Initialize ToolSetClient (Python) Source: https://docs.agent.run/docs/api/python/toolset/client Initializes the ToolSetClient with an optional configuration object. This client provides methods for interacting with toolsets. ```python class ToolSetClient: def __init__(self, config: Optional[Config] = None): pass ``` -------------------------------- ### Get Global Converter Instance Source: https://docs.agent.run/docs/api/python/integration/utils/converter Retrieves the global instance of the FrameworkConverter. ```APIDOC ## get_converter ### Description Gets the global converter instance. ### Method `get_converter` ### Endpoint N/A (Function Call) ### Parameters None ### Returns - FrameworkConverter - The global FrameworkConverter instance. ``` -------------------------------- ### model Function Source: https://docs.agent.run/docs/api/python/integration/crewai/builtin Gets an AgentRun model and converts it to a LangChain BaseChatModel. ```APIDOC ## model Function ### Description Gets an AgentRun model and converts it to a LangChain `BaseChatModel`. ### Method N/A (Function Definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python # Example usage (conceptual) from crewai_tools.tools import model # Assuming 'my_model' is a CrewAI-compatible model object langchain_model = model(name='my_model') ``` ### Response #### Success Response - **langchain_model** (BaseChatModel) - The converted LangChain model. #### Response Example ```json { "message": "Model converted successfully to LangChain BaseChatModel" } ``` ``` -------------------------------- ### Initialize AgentRun SDK Config from Parameters or Environment Variables (Python) Source: https://docs.agent.run/docs/api/python/utils/config Demonstrates how to create a configuration object for the AgentRun SDK. It shows initialization using explicit parameters like account ID and access keys, or by automatically reading credentials from environment variables. ```python from agent_run_sdk.config import Config # Create config from parameters config_from_params = Config( account_id="your-account-id", access_key_id="your-key-id", access_key_secret="your-secret" ) # Or read from environment variables config_from_env = Config() ``` -------------------------------- ### Set up AgentRun Server with OpenAI Chat Completions and AG-UI Protocols (TypeScript) Source: https://docs.agent.run/docs/tutorial/integration/mastra This snippet demonstrates how to initialize and start an AgentRunServer in TypeScript. It configures the server to handle agent invocations using a custom `invokeAgent` function, which can be integrated with different agent frameworks like Mastra. The server supports CORS requests and starts listening on port 9000. ```typescript async function* invokeAgent( request: AgentRequest, ): AsyncGenerator { // AgentRunServer 本身并非和 Mastra 绑定,您可以通过自己转换的方式,与任何 Agent 框架进行集成 // 通过 Mastra 集成提供的 MastraConverter,可以方便地将 Mastra 的流式输出转换为 AgentRun 事件流 const converter = new MastraConverter(); const mastraStream = await mastraAgent.stream( request.messages.map( (msg) => ({ role: msg.role, content: msg.content || '', }) as any, ), ); for await (const chunk of mastraStream.fullStream) { const events = converter.convert(chunk); for (const event of events) { // 这里返回的内容完全由您控制,您可以实现一个 “大模型” 做内容反转,但实现上可能只是一行 reverse 代码 yield event; } } } const server = new AgentRunServer({ invokeAgent, config: { corsOrigins: ['*'] }, }); server.start({ port: 9000 }); ``` -------------------------------- ### ModelProxy - Get Model Info Source: https://docs.agent.run/docs/api/python/model/model_proxy Retrieves model information for the current model service. ```APIDOC ## GET /websites/agent_run/model_proxy/model_info ### Description Retrieves model information for the current model service. ### Method GET ### Endpoint /websites/agent_run/model_proxy/model_info ### Parameters #### Query Parameters - **config** (Config) - Optional - Configuration ### Response #### Success Response (200) - **BaseInfo** (BaseInfo) - The model information object ``` -------------------------------- ### ControlAPI Constructor Source: https://docs.agent.run/docs/api/python/utils/control_api Initializes the Control API client. It accepts an optional global configuration object. ```APIDOC ## def __init__(self, config: Optional[Config] = None) ### Description Initialize Control API client. Accepts an optional global configuration object. ### Method __init__ (Constructor) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example of initializing ControlAPI with a config object from your_module import ControlAPI, Config # Assuming 'my_config' is a valid Config object my_config = Config(...) control_api_client = ControlAPI(config=my_config) ``` ### Response #### Success Response (200) N/A (This is a constructor, not an endpoint response) #### Response Example N/A ``` -------------------------------- ### GET /tools/{name} Source: https://docs.agent.run/docs/api/python/toolset/api/control Retrieves a specific toolset by its name. ```APIDOC ## GET /tools/{name} ### Description Retrieves a specific toolset by its name. This is the synchronous version of the call. ### Method GET ### Endpoint `/tools/{name}` ### Parameters #### Path Parameters - **name** (str) - Required - The name of the Tool to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming api_client is an instance of ToolControlAPI tool_name = "example_tool" toolset = api_client.get_toolset(name=tool_name) print(toolset) ``` ### Response #### Success Response (200) - **Toolset** (Toolset) - The ToolSet object containing details about the requested tool. #### Response Example ```json { "id": "example_tool_id", "name": "example_tool", "description": "An example toolset.", "version": "1.0.0" } ``` #### Error Responses - **AgentRuntimeError**: Called failed. - **ClientError**: Client-side error. - **ServerError**: Server-side error. - **APIError**: Runtime error. ``` -------------------------------- ### Get ToolSet Type Source: https://docs.agent.run/docs/api/python/toolset Returns the type of the ToolSet instance. This is an instance method. ```python def type(self) ``` -------------------------------- ### Get Agent Runtime (Async) Source: https://docs.agent.run/docs/api/python/agent_runtime/client Asynchronously retrieves an Agent Runtime by its ID. ```APIDOC ## GET /agent_runtime/{id} (Async) ### Description Asynchronously retrieves an Agent Runtime by its ID. ### Method GET ### Endpoint `/agent_runtime/{id}` ### Parameters #### Path Parameters - **id** (str) - Required - Agent Runtime ID #### Query Parameters None #### Request Body None ### Request Example ```json { "config": { ... } } ``` ### Response #### Success Response (200) - **AgentRuntime** (AgentRuntime) - The Agent Runtime object #### Response Example ```json { "id": "runtime-123", "status": "running", "..." } ``` ### Errors - `ResourceNotExistError`: Resource does not exist. - `HTTPError`: HTTP request error. ``` -------------------------------- ### 配置模型代理负载均衡 Source: https://docs.agent.run/docs/tutorial/advanced/best-practices 使用 ModelProxy 配置负载均衡模式,将请求分散到多个模型实例,提高可用性和性能。通过设置权重来控制流量分配。 ```python from agentrun.model import ModelProxy, ModelProxyCreateInput, ProxyConfig # 配置负载均衡 proxy = ModelProxy.create( ModelProxyCreateInput( name="balanced-proxy", proxy_config=ProxyConfig( mode="LOAD_BALANCE", endpoints=[ {"model_name": "model-1", "weight": 50}, {"model_name": "model-2", "weight": 50} ] ) ) ) ``` -------------------------------- ### ModelProxy - Get Model Service (Sync) Source: https://docs.agent.run/docs/api/python/model/model_proxy Synchronously refreshes the current model service information. ```APIDOC ## GET /websites/agent_run/model_proxy/get ### Description Synchronously refreshes the current model service information. ### Method GET ### Endpoint /websites/agent_run/model_proxy/get ### Parameters #### Query Parameters - **config** (Config) - Optional - Configuration ### Response #### Success Response (200) - **ModelProxy** (ModelProxy) - The refreshed model service object ``` -------------------------------- ### ModelProxy - Get Model Service (Async) Source: https://docs.agent.run/docs/api/python/model/model_proxy Asynchronously refreshes the current model service information. ```APIDOC ## GET /websites/agent_run/model_proxy/get_async ### Description Asynchronously refreshes the current model service information. ### Method GET ### Endpoint /websites/agent_run/model_proxy/get_async ### Parameters #### Query Parameters - **config** (Config) - Optional - Configuration ### Response #### Success Response (200) - **ModelProxy** (ModelProxy) - The refreshed model service object ``` -------------------------------- ### POST /toolsets/list (Async) Source: https://docs.agent.run/docs/api/python/toolset/api/control Asynchronously enumerates available toolsets based on the provided request configuration. ```APIDOC ## POST /toolsets/list (Async) ### Description Asynchronously enumerates available ToolSets. This is the asynchronous version of the call. ### Method POST ### Endpoint `/toolsets/list` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (ListToolsetsRequest) - Required - The configuration for listing toolsets. ### Request Example ```python import asyncio # Assuming api_client is an instance of ToolControlAPI from agent_run.api.control import ListToolsetsRequest async def list_tools(): list_request = ListToolsetsRequest(filter="some_filter") # Example filter toolset_list_response = await api_client.list_toolsets_async(input=list_request) print(toolset_list_response) asyncio.run(list_tools()) ``` ### Response #### Success Response (200) - **ListToolsetsResponseBody** (ListToolsetsResponseBody) - A response body containing a list of ToolSet objects. #### Response Example ```json { "toolsets": [ { "id": "toolset1_id", "name": "toolset1", "description": "First toolset.", "version": "1.0.0" }, { "id": "toolset2_id", "name": "toolset2", "description": "Second toolset.", "version": "1.1.0" } ] } ``` #### Error Responses - **AgentRuntimeError**: Called failed. - **ClientError**: Client-side error. - **ServerError**: Server-side error. - **APIError**: Runtime error. ```