### Install Serverless Devs with Bun Source: https://docs.agent.run/docs/tutorial/quickstart/manual Use this command to install the Serverless Devs CLI globally using Bun. ```bash bun add --global @serverless-devs/s ``` -------------------------------- ### Install Serverless Devs with npm Source: https://docs.agent.run/docs/tutorial/quickstart/manual Use this command to install the Serverless Devs CLI globally using npm. ```bash npm install -g @serverless-devs/s ``` -------------------------------- ### Install Serverless Devs with pnpm Source: https://docs.agent.run/docs/tutorial/quickstart/manual Use this command to install the Serverless Devs CLI globally using pnpm. ```bash pnpm add -g @serverless-devs/s ``` -------------------------------- ### Install Serverless Devs with Yarn Source: https://docs.agent.run/docs/tutorial/quickstart/manual Use this command to install the Serverless Devs CLI globally using Yarn. ```bash yarn global add @serverless-devs/s ``` -------------------------------- ### Install uv with pip Source: https://docs.agent.run/docs/tutorial/quickstart/manual Installs the uv package manager using pip. Ensure Python is installed and pip is available in your PATH. ```bash pip install uv ``` -------------------------------- ### Install AgentRun SDK Source: https://docs.agent.run/docs/tutorial/faq Install the AgentRun SDK using pip. Requires Python 3.10 or higher. ```bash pip install agentrun-sdk ``` -------------------------------- ### Install Python dependencies with uv Source: https://docs.agent.run/docs/tutorial/quickstart/manual Installs Python dependencies from requirements.txt using uv, with acceleration from the Aliyun PyPI mirror. This command ensures all necessary packages are installed for the project. ```bash uv pip install -r requirements.txt -i http://mirrors.aliyun.com/pypi/simple/ ``` -------------------------------- ### Install uv with PowerShell Source: https://docs.agent.run/docs/tutorial/quickstart/manual Installs the uv package manager on Windows using PowerShell. This command bypasses execution policy restrictions for installation. ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Deploying with Environment Variables Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv Examples of how to set environment variables for different deployment scenarios (development and production) when using the variable injection configuration method. ```bash # 开发环境 ENV=dev CPU=1.0 MEMORY=2048 s deploy # 生产环境 ENV=prod CPU=2.0 MEMORY=4096 s deploy ``` -------------------------------- ### Development Environment Configuration Template Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv Example template for development environment configuration. Define necessary configuration items without actual values. ```shell # 开发环境配置模板 # 阿里云配置 ACCOUNT_ID=123456789 # 模型和沙箱 DEV_MODEL_NAME=dev-qwen-model DEV_SANDBOX_NAME=dev-sandbox # API Keys DEV_API_KEY=dev-api-key-xxxxx # 数据库(开发环境使用本地或开发数据库) DEV_DB_HOST=dev-db.example.com DEV_DB_PORT=3306 ``` -------------------------------- ### Production Environment Configuration Template Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv Example template for production environment configuration. Includes more items and placeholders for secrets. ```shell # 生产环境配置模板(实际值通过 CI/CD Secrets 注入) # 阿里云配置 ACCOUNT_ID=123456789 # VPC 配置 PROD_VPC_ID=vpc-xxxxx PROD_VSWITCH_ID_1=vsw-xxxxx PROD_VSWITCH_ID_2=vsw-yyyyy PROD_SECURITY_GROUP_ID=sg-xxxxx # 模型和沙箱 PROD_MODEL_NAME=prod-qwen-max PROD_SANDBOX_NAME=prod-sandbox # API Keys(实际值留空,通过 Secrets 管理) PROD_API_KEY= # 数据库 PROD_DB_HOST=prod-db.example.com PROD_DB_PORT=3306 # 监控 METRICS_ENDPOINT=https://metrics.example.com ``` -------------------------------- ### Install AgentRun SDK and Mastra Core Source: https://docs.agent.run/docs/tutorial/integration/mastra Install the necessary SDKs for AgentRun and Mastra Core in your Node.js/TypeScript project. This command uses a specific npm mirror registry. ```bash npm install @agentrun/sdk @mastra/core --registry=https://registry.npmmirror.com ``` ```bash yarn add @agentrun/sdk @mastra/core --registry=https://registry.npmmirror.com ``` ```bash pnpm add @agentrun/sdk @mastra/core --registry=https://registry.npmmirror.com ``` ```bash bun add @agentrun/sdk @mastra/core --registry https://registry.npmmirror.com ``` -------------------------------- ### Install NodeJS dependencies Source: https://docs.agent.run/docs/tutorial/quickstart/manual Installs NodeJS project dependencies using npm, leveraging the NPM Mirror registry for faster downloads. This command reads the package.json file to install all required packages. ```bash npm i --registry=https://registry.npmmirror.com ``` -------------------------------- ### AgentRun Event Stream Example Source: https://docs.agent.run/docs/tutorial/integration/mastra This example demonstrates the event stream generated by AgentRun when an LLM interacts with tools. It shows the sequence of events from run initiation to tool calls, results, and message generation. Observe the 'TOOL_CALL_RESULT' for error handling and successful tool execution. ```json data: {"type":"RUN_STARTED","threadId":"2c7b5272-f2b5-401e-a6a4-f62c6b8f44bb","runId":"a7760759-49ba-41c5-9bd2-247902b7dfc3"} data: {"type":"TOOL_CALL_START","toolCallId":"call_df2498ad5d43415a8d3ad0e9","toolCallName":"start-mcp-time-ggda_get_current_time"} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_df2498ad5d43415a8d3ad0e9","delta":"{}"} data: {"type":"TOOL_CALL_END","toolCallId":"call_df2498ad5d43415a8d3ad0e9"} data: {"type":"TOOL_CALL_RESULT","messageId":"tool-result-call_df2498ad5d43415a8d3ad0e9","toolCallId":"call_df2498ad5d43415a8d3ad0e9","content":"{\"error\":true,\"message\":\"Tool input validation failed for start-mcp-time-ggda_get_current_time. Please fix the following errors and try again:\n- timezone: Invalid input: expected string, received undefined\n\nProvided arguments: {}\",\"validationErrors\":{\"_errors\":[],\"timezone\":{\"_errors\":[\"Invalid input: expected string, received undefined\"]}}}","role":"tool"} data: {"type":"TOOL_CALL_START","toolCallId":"call_5a1238ab6aff48658b28d7e4","toolCallName":"start-mcp-time-ggda_get_current_time"} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_5a1238ab6aff48658b28d7e4","delta":"{\"timezone\":\"UTC\"}"} data: {"type":"TOOL_CALL_END","toolCallId":"call_5a1238ab6aff48658b28d7e4"} data: {"type":"TOOL_CALL_RESULT","messageId":"tool-result-call_5a1238ab6aff48658b28d7e4","toolCallId":"call_5a1238ab6aff48658b28d7e4","content":"[{{\"type\":\"text\",\"text\":\"{\\\"timezone\\\": \\\"UTC\\\",\\\"datetime\\\": \\\"2026-01-30T10:13:25+00:00\\\",\\\"is_dst\\\": false\\\"}\"}}]","role":"tool"} data: {"type":"TEXT_MESSAGE_START","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","role":"assistant"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":"。"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":"时"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":"区"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":" UTC"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":" 在 20"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":"26 年 1"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":" 月 30 日"} data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091","delta":",现在是"} data: {"type":"TEXT_MESSAGE_END","messageId":"2f5a07f6-d65c-4a33-b62c-610053fd8091"} data: {"type":"RUN_FINISHED","threadId":"2c7b5272-f2b5-401e-a6a4-f62c6b8f44bb","runId":"a7760759-49ba-41c5-9bd2-247902b7dfc3"} ``` -------------------------------- ### Install uv with pipx Source: https://docs.agent.run/docs/tutorial/quickstart/manual Installs the uv package manager using pipx, which creates isolated environments for Python applications. ```bash pipx install uv ``` -------------------------------- ### Deploying to Production with GitHub Actions Secrets Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv Example of a GitHub Actions workflow step to deploy to production, referencing sensitive information from repository secrets. ```yaml - name: Deploy to production env: ACCOUNT_ID: ${{ secrets.ALIYUN_ACCOUNT_ID_PROD }} PROD_VPC_ID: ${{ secrets.PROD_VPC_ID }} PROD_MODEL_NAME: ${{ secrets.PROD_MODEL_NAME }} PROD_API_KEY: ${{ secrets.PROD_API_KEY }} run: | s deploy -t s.prod.yaml --assume-yes ``` -------------------------------- ### Configure Coffee Agent with Instructions and Tools Source: https://docs.agent.run/docs/tutorial/advanced/best-practices-a2a-by-me-a-coffee This configuration defines a coffee agent, specifying its name, model, description, and system instructions. The system instructions are crucial for guiding the agent's behavior, especially regarding tool usage and user interaction rules. ```python coffee_agent = Agent( name="coffee_agent", model=DEFAULT_LLM, description="希希咖啡店智能服务,可以帮助点咖啡和查询订单", instruction=""" 你是"希希咖啡"智能服务(Root Agent),管理两个子助手:下单助手(order_agent)与查询助手(query_agent)。请遵守下列规则并用中文与顾客交互,语气热情且简洁。 重要行为规则(必须遵守): - 每次用户询问"订单状态/我的咖啡做好了么/订单进度"等相关问题时,必须发起真实的后端查询调用: - 若用户提供了订单号,**必须**调用 `tool_query_order(order_id)` 并使用该工具的返回结果构建回复;不可仅凭上下文或记忆直接回答。 - 若用户未提供订单号,**必须**调用 `tool_get_recent_orders(limit=5)`,把最近订单列表返回给用户并在必要时提示用户选择或提供订单号;不可跳过该步骤。 - 禁止在未调用上述工具的情况下就断定或推测订单状态。每一次用户的"我的咖啡做好了么"都要触发后端查询(不使用缓存结果来回应用户)。 总体规则(补充): - 用户想点单、看菜单或需要推荐 → 转交给 `order_agent` 处理或直接调用下单相关工具。 - 对于门店基础信息(地址、营业时间、配送方式等)可直接回答:地址:人民路88号;营业时间:8:00-22:00;支持堂食/自取/外卖。 - 尽量减少轮次,不要无谓追问;但在缺少必要字段(例如订单号)时,应直接调用 `tool_get_recent_orders` 或询问最少的必要信息以完成工具调用。 """, tools=[ tool_get_menu, tool_search_product, tool_create_order, tool_query_order, tool_get_recent_orders, tool_update_order_status, ], ) ``` -------------------------------- ### Define Coffee Shop Menu Query Tool Source: https://docs.agent.run/docs/tutorial/advanced/best-practices-a2a-by-me-a-coffee This example defines a tool for querying the coffee shop's menu. The function's docstring details its purpose, the API endpoint it calls, its arguments, and its return format, which ADK uses to understand the tool's functionality. ```python def tool_get_menu(category: str = None) -> dict: """ 获取希希咖啡店的菜单 调用 API: GET /api/coffee/products Args: category: 商品分类,可选值:经典咖啡、特调饮品、甜点。不指定则返回全部菜单 Returns: 菜单信息,按分类整理 """ return tools.get_menu(category) ``` -------------------------------- ### Python requirements.txt Source: https://docs.agent.run/docs/tutorial/quickstart/manual Specifies the AgentRun SDK with server and langchain dependencies for Python projects. This file is used by pip or uv to install necessary packages. ```text agentrun-sdk[server,langchain]==0.0.9 ``` -------------------------------- ### Data Analysis Agent with Code Interpreter Source: https://docs.agent.run/docs/tutorial/core/sandbox This snippet shows the complete workflow for a data analysis Agent. It includes setting up the sandbox, uploading data, installing necessary libraries, executing analysis code, and downloading the generated visualization. This process is performed in an isolated environment. ```python from agentrun.sandbox import Sandbox, TemplateType from agentrun.integration.langchain import model, sandbox_toolset # Create sandbox sandbox = Sandbox.create( template_type=TemplateType.CODE_INTERPRETER, template_name="data-analysis-sandbox", sandbox_idle_timeout_seconds=1800 ) # Upload data file sandbox.file_system.upload( local_file_path="./sales_data.csv", target_file_path="/home/user/sales_data.csv" ) # Create execution context context = sandbox.context.create() # Install necessary libraries for analysis (if not pre-installed in the template) context.execute(""" import subprocess subprocess.run(['pip', 'install', 'pandas', 'matplotlib', 'seaborn']) """) # Execute data analysis analysis_code = """ import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Load data df = pd.read_csv('/home/user/sales_data.csv') # Basic statistics stats = { 'total_rows': len(df), 'columns': list(df.columns), 'summary': df.describe().to_dict() } # Generate visualization plt.figure(figsize=(10, 6)) sns.barplot(data=df, x='category', y='sales') plt.title('Sales by Category') plt.xticks(rotation=45) plt.tight_layout() plt.savefig('/home/user/sales_chart.png') print("Analysis complete") print(f"Dataset contains {len(df)} rows, {len(df.columns)} columns") """ result = context.execute(analysis_code) print(result.get("stdout")) # Download generated chart sandbox.file_system.download( path="/home/user/sales_chart.png", save_path="./sales_chart.png" ) print("Analysis report generated: sales_chart.png") ``` -------------------------------- ### Python Agent with Web Search Source: https://docs.agent.run/docs/tutorial/quickstart/manual This Python script sets up an AgentRun agent capable of performing web searches using a browser sandbox. It configures the agent with a system prompt that guides its search strategy, including using Baidu search and extracting information from web pages. Ensure you have the necessary environment variables set for MODEL_SERVICE, MODEL_NAME, and SANDBOX_NAME. ```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") # 只需要一行代码,即可将开放 OpenAI Chat Completions / AG-UI 协议的 HTTP 服务,快速与其他项目集成 AgentRunServer(invoke_agent=invoke_agent).start() ``` -------------------------------- ### Initialize Coffee Shop Database with aiosqlite Source: https://docs.agent.run/docs/tutorial/advanced/best-practices-a2a-by-me-a-coffee Initializes the SQLite database for the coffee shop, creating 'products' and 'orders' tables if they don't exist. It also populates initial product data if the products table is empty. This uses asynchronous operations with aiosqlite. ```python class CoffeeDatabase: async def init_db(self): """初始化数据库,创建表和初始数据""" async with aiosqlite.connect(self.db_path) as db: await db.execute(""" CREATE TABLE IF NOT EXISTS products ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, price REAL NOT NULL, description TEXT, category TEXT NOT NULL, image_url TEXT, available INTEGER DEFAULT 1 ) """) await db.execute(""" CREATE TABLE IF NOT EXISTS orders ( id INTEGER PRIMARY KEY AUTOINCREMENT, items TEXT NOT NULL, total REAL NOT NULL, status TEXT DEFAULT 'pending', customer_name TEXT, customer_phone TEXT, customer_address TEXT, notes TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ) """) await db.commit() cursor = await db.execute("SELECT COUNT(*) FROM products") count = await cursor.fetchone() if count[0] == 0: await self._insert_initial_products(db) ``` -------------------------------- ### Configure Global Parameters via Environment Variables Source: https://docs.agent.run/docs/tutorial/faq Recommended method for configuring global parameters. Set environment variables for access key ID, secret, account ID, and region. ```bash export AGENTRUN_ACCESS_KEY_ID="your-access-key-id" export AGENTRUN_ACCESS_KEY_SECRET="your-access-key-secret" export AGENTRUN_ACCOUNT_ID="your-account-id" export AGENTRUN_REGION="cn-hangzhou" ``` -------------------------------- ### Configure Alibaba Cloud Credentials Source: https://docs.agent.run/docs/tutorial/quickstart/manual Add Alibaba Cloud credentials by following the prompts to enter your Access Key ID and Secret. Remember to note the key pair name (e.g., agentrun-deploy). ```bash # 按照引导输入 Access Key ID 和 Secret,记住密钥对名称(如 agentrun-deploy) s config add ``` -------------------------------- ### Install uv with curl Source: https://docs.agent.run/docs/tutorial/quickstart/manual Installs or updates the uv package manager using a curl command. This is a prerequisite for managing Python environments and dependencies. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Create a Unified Environment Script Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv Create a unified environment script 'scripts/env.sh' to manage environment-specific actions like deployment, info, and logs. ```bash #!/bin/bash ENV=${1:-dev} case $2 in deploy) ./scripts/deploy.sh $ENV ;; info) s info -t s.$ENV.yaml ;; logs) s logs -t s.$ENV.yaml --tail ;; *) echo "Usage: $0 [deploy|info|logs]" echo "Example: $0 prod info" ;; esac ``` -------------------------------- ### Deploy to Different Environments Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv Use the deploy script to deploy to various environments like dev, test, staging, and prod. ```bash # Deploy to different environments ./scripts/deploy.sh dev ./scripts/deploy.sh test ./scripts/deploy.sh staging ./scripts/deploy.sh prod # View status of different environments ./scripts/status.sh dev ./scripts/status.sh prod ``` -------------------------------- ### Check NodeJS version Source: https://docs.agent.run/docs/tutorial/quickstart/manual Checks the installed NodeJS version. AgentRun requires NodeJS version 18.0.0 or higher. ```bash node -v ``` -------------------------------- ### Update uv Source: https://docs.agent.run/docs/tutorial/quickstart/manual Updates the uv package manager to the latest version. Run this command if you already have uv installed and want to upgrade. ```bash uv self update ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://docs.agent.run/docs/tutorial/advanced/best-practices It is recommended to load configuration, such as access keys, from environment variables instead of hardcoding them. This enhances security by keeping sensitive information out of your codebase. Ensure `.env` files are excluded from version control. ```python import os from agentrun.utils.config import Config # Recommended: Read from environment variables config = Config() # Automatically reads AGENTRUN_* environment variables # Avoid: Hardcoding sensitive information # config = Config( # access_key_id="LTAI...", # Do not do this # access_key_secret="..." # ) ``` -------------------------------- ### Execute Environment-Specific Commands Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv Use the 'scripts/env.sh' script for concise execution of environment-specific commands. For example, view production environment information or development environment logs. ```bash # View production environment information ./scripts/env.sh prod info # View development environment logs ./scripts/env.sh dev logs ``` -------------------------------- ### A2A JSON-RPC Request for Coffee Task Source: https://docs.agent.run/docs/tutorial/advanced/best-practices-a2a-by-me-a-coffee This is an example of a JSON-RPC request constructed by a remote agent to execute a task. It includes the method, parameters, and a unique ID for the request. ```json { "jsonrpc": "2.0", "method": "execute_task", "params": { "task_id": "task-12345", "message": "我要一杯拿铁", "context": {} }, "id": "req-67890" } ``` -------------------------------- ### Build and Run a LangChain Agent with AgentRun Components Source: https://docs.agent.run/docs/tutorial/integration/framework-integration This snippet demonstrates how to construct a LangChain Agent using AgentRun's model and toolset integrations. It combines a remote LLM with code execution capabilities via a sandboxed environment. ```python from langchain.agents import create_openai_functions_agent, AgentExecutor from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder from agentrun.integration.langchain import model, toolset, sandbox_toolset from agentrun.sandbox import TemplateType # 准备组件 llm = model("my-model") tools = toolset("my-toolset") + sandbox_toolset("my-sandbox", TemplateType.CODE_INTERPRETER) # 定义提示词 prompt = ChatPromptTemplate.from_messages([ ("system", "你是一个有帮助的助手。"), ("user", "{input}"), MessagesPlaceholder(variable_name="agent_scratchpad") ]) # 创建 Agent agent = create_openai_functions_agent(llm, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) # 运行 Agent result = agent_executor.invoke({"input": "帮我计算斐波那契数列的第20项"}) print(result["output"]) ``` -------------------------------- ### Automated Deployment to Development Environment Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv This workflow automatically deploys code to the development environment when changes are pushed to the 'develop' branch. It installs dependencies, configures credentials using GitHub Secrets, and executes a deployment script. ```yaml name: Deploy to Development on: push: branches: - develop env: NODE_VERSION: '18' PYTHON_VERSION: '3.12' jobs: deploy-dev: runs-on: ubuntu-latest environment: name: development steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} - name: Setup Python uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} - name: Install dependencies run: | npm install -g @serverless-devs/s cd code pip install -r requirements.txt - name: Configure credentials run: | s config add \ --AccountID ${{ secrets.ALIYUN_ACCOUNT_ID }} \ --AccessKeyID ${{ secrets.ALIYUN_ACCESS_KEY_ID }} \ --AccessKeySecret ${{ secrets.ALIYUN_ACCESS_KEY_SECRET }} \ --alias default - name: Deploy using script env: ACCOUNT_ID: ${{ secrets.ALIYUN_ACCOUNT_ID }} DEV_MODEL_NAME: ${{ secrets.DEV_MODEL_NAME }} DEV_SANDBOX_NAME: ${{ secrets.DEV_SANDBOX_NAME }} DEV_API_KEY: ${{ secrets.DEV_API_KEY }} run: | chmod +x scripts/deploy.sh ./scripts/deploy.sh dev ``` -------------------------------- ### AG-UI Protocol Event Stream Source: https://docs.agent.run/docs/tutorial/quickstart/manual This is an example of the Server-Sent Events (SSE) stream received when interacting with the agent via the AG-UI protocol. It shows the progression of the agent's execution, including tool calls and results. ```text data: {"type":"RUN_STARTED","threadId":"3fcd6aed-bbbb-4cbd-b14c-f43a25f02e27","runId":"9cc1bf23-8289-4df6-a257-dd271b4772de"} data: {"type":"TOOL_CALL_START","toolCallId":"call_eed285ab6bd64aea980c6a21","toolCallName":"health"} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_eed285ab6bd64aea980c6a21","delta":""} data: {"type":"TOOL_CALL_END","toolCallId":"call_eed285ab6bd64aea980c6a21"} data: {"type":"TOOL_CALL_RESULT","messageId":"tool-result-call_eed285ab6bd64aea980c6a21","toolCallId":"call_eed285ab6bd64aea980c6a21","content":"{\"status\": \"ok\", \"services\": {\"cdp_websocket\": {\"status\": \"ok\", \"message\": \"CDP WebSocket service ready, 0 active connections\"}, \"vnc_websocket\": {\"status\": \"ok\", \"message\": \"VNC server accessible\"}}}","role":"tool"} data: {"type":"TOOL_CALL_START","toolCallId":"call_51e1dc38f8544d0c83b6c803","toolCallName":"goto"} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_51e1dc38f8544d0c83b6c803","delta":"{\"url\": \"https://www.baidu.com/s?ie=utf-8&wd=a2a\"}"} data: {"type":"TOOL_CALL_END","toolCallId":"call_51e1dc38f8544d0c83b6c803"} data: {"type":"TOOL_CALL_RESULT","messageId":"tool-result-call_51e1dc38f8544d0c83b6c803","toolCallId":"call_51e1dc38f8544d0c83b6c803","content":"{\"url\": \"https://www.baidu.com/s?ie=utf-8&wd=a2a\", \"success\": true, \"status\": 200}","role":"tool"} data: {"type":"TOOL_CALL_START","toolCallId":"call_aea14c318731430485a10e82","toolCallName":"evaluate"} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_aea14c318731430485a10e82","delta":"{\"expression\": \"Array.from(document.querySelectorAll('.c-container')).slice(0, 5).map(item => { const titleEl = item.querySelector('h3') || item.querySelector('.content-title'); const linkEl = item.querySelector('a'); return { title: titleEl?.innerText.trim() || '', url: linkEl?.href || '' }; }).filter(item => item.title && item.url)"}"} data: {"type":"TOOL_CALL_END","toolCallId":"call_aea14c318731430485a10e82"} data: {"type":"TOOL_CALL_RESULT","messageId":"tool-result-call_aea14c318731430485a10e82","toolCallId":"call_aea14c318731430485a10e82","content":"{\"result\": [{\"title\": \"a2a\\n\\n - 百度图片\", \"url\": \"https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=utf8&sa=vs_ala_img&fr=ala&ala=1&alatpl=normal&pos=3&dyTabStr=MCwzLDEsMiwxMyw3LDYsNSwxMiw5&word=a2a&lid=a70b2bb30048809a&topic=a2a\"}, {\"title\": \"A2A超话—新浪微博超话社区\", \"url\": \"http://www.baidu.com/link?url=KceEJNAvs0xT2nDqwfaJlTC2szI4FTGxuKRCjUERJyAcp-ccEUNOa6upVrtMx9vM6q571tysS-pLHn8XArHYtHgngUFGPf6JpusP54k_fv3\"}, {\"title\": \"A2A - 百度百科\", \"url\": \"http://www.baidu.com/link?url=2byj0MG4tI7XgwYRIrqxIZkMTFQZhYL6GrJtfyli-5tjVLL7qtZTziZMA_PBi7Vx2-hb28hNDv_1Qmpk2kDGJ_\"}, {\"title\": \"a2a - 视频大全 - 高清在线观看\", \"url\": \"https://www.baidu.com/sf/vsearch?pd=video&wd=a2a&tn=vsearch&lid=a70b2bb30048809a&ie=utf-8&rsv_pq=a70b2bb30048809a&rsv_spt=5&rsv_bp=1&f=8&atn=index\"}]}","role":"tool"} data: {"type":"TOOL_CALL_START","toolCallId":"call_303cb2010c03435d8a2aca1a","toolCallName":"goto"} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_303cb2010c03435d8a2aca1a","delta":"{\"url\": \"http://www.baidu.com/link?url=2byj0MG4tI7XgwYRIrqxIZkMTFQZhYL6GrJtfyli-5tjVLL7qtZTziZMA_PBi7Vx2-hb28hNDv_1Qmpk2kDGJ_\"}"} data: {"type":"TOOL_CALL_END","toolCallId":"call_303cb2010c03435d8a2aca1a"} data: {"type":"TOOL_CALL_RESULT","messageId":"tool-result-call_303cb2010c03435d8a2aca1a","toolCallId":"call_303cb2010c03435d8a2aca1a","content":"{\"url\": \"http://www.baidu.com/link?url=2byj0MG4tI7XgwYRIrqxIZkMTFQZhYL6GrJtfyli-5tjVLL7qtZTziZMA_PBi7Vx2-hb28hNDv_1Qmpk2kDGJ_\", \"success\": true, \"status\": 200}","role":"tool"} data: {"type":"TOOL_CALL_START","toolCallId":"call_683ef02efe1a439893210e6c","toolCallName":"evaluate"} data: {"type":"TOOL_CALL_ARGS","toolCallId":"call_683ef02efe1a439893210e6c","delta":"{\"expression\": \"({ title: document.title, content: Array.from(document.querySelectorAll('meta[name=\"description\"], .lemma-summary, .content')).map(el => el.content || el.innerText).join(' ')}))\"}"} data: {"type":"TOOL_CALL_END","toolCallId":"call_683ef02efe1a439893210e6c"} ``` -------------------------------- ### Hybrid Configuration: Base and Environment-Specific Files Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv This hybrid approach uses a base configuration file (s.base.yaml) for common settings and environment-specific files (e.g., s.dev.yaml) that extend the base configuration. This balances centralized maintenance with clear, environment-specific overrides. ```yaml # s.base.yaml - 公共配置(不直接部署) edition: 3.0.0 vars: region: cn-hangzhou code_src: ./code code_language: python3.12 code_command: - python3 - app.py # s.dev.yaml - 开发环境(继承基础配置) edition: 3.0.0 name: dev-agentrun-app access: default extend: - s.base.yaml vars: env: dev resources: my-agent: component: agentrun props: region: ${vars.region} agent: name: agent-${vars.env} code: src: ${vars.code_src} language: ${vars.code_language} command: ${vars.code_command} # 开发环境特定配置 cpu: 1.0 memory: 2048 environmentVariables: ENVIRONMENT: ${vars.env} LOG_LEVEL: debug ``` -------------------------------- ### Configure s.yaml for NodeJS AgentRun Source: https://docs.agent.run/docs/tutorial/quickstart/manual This s.yaml configuration is for a NodeJS AgentRun project. It specifies environment variables, code source, language, and command for execution. Note that installing Linux x64 dependencies locally might conflict with your local environment. ```yaml edition: 3.0.0 name: my-agentrun # 您需要根据实际情况修改这里的内容 access: 'default' # 修改为您的密钥对名称 vars: region: 'cn-hangzhou' # 要部署的地域 agent_name: 'my-agentrun-nodejs' # 您的 Agent 名称 role: 'acs:ram::${config("AccountID")}:role/AliyunAgentRunDefaultRole' # 您的 Agent 需要拥有的权限(会用于注入 ACCESS_KEY) model_service: 'my-agentrun-model' # AgentRun 模型服务名称 model_name: 'qwen3-max' # 要使用的模型名称 sandbox_name: 'my-agentrun-browser' # 浏览器沙箱名称 resources: agent: component: agentrun props: region: ${vars.region} agent: # 基本信息 name: ${vars.agent_name} description: '我的 AgentRun Agent' role: ${vars.role} code: src: ./ language: nodejs20 command: - node - index.js # 资源配置 cpu: 1.0 memory: 2048 # 端口和并发 port: 9000 instanceConcurrency: 200 # 网络配置 - 仅公网访问 internetAccess: true # 环境变量 environmentVariables: MODEL_SERVICE: '${vars.model_service}' MODEL_NAME: '${vars.model_name}' SANDBOX_NAME: '${vars.sandbox_name}' # 日志配置 logConfig: auto # 端点配置 endpoints: - name: prod version: LATEST description: '生产环境端点' ``` -------------------------------- ### Batch View All Environment Statuses Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv This script iterates through all defined environments (dev, test, staging, prod) to display their deployment status and access endpoints. It provides a clear overview of the AgentRun environments. ```bash #!/bin/bash # scripts/status-all.sh echo "=========================================" echo "AgentRun Environments Status" echo "=========================================" echo "" for env in dev test staging prod; do echo "=== Environment: $env ===" if s info -t s.$env.yaml > /dev/null 2>&1; then STATUS=$(s info -t s.$env.yaml 2>/dev/null | grep "status:" | awk '{print $2}') ENDPOINT=$(s info -t s.$env.yaml 2>/dev/null | grep -oP 'https://[^\s]+' | head -1) echo "Status: $STATUS" echo "Endpoint: $ENDPOINT" else echo "Status: Not deployed" fi echo "" done ``` -------------------------------- ### Multi-File Configuration Structure Source: https://docs.agent.run/docs/tutorial/advanced/07.3-menv This structure uses separate YAML files for each environment (dev, test, staging, prod) alongside a base configuration file. This provides clear separation and independent version control for each environment's configuration. ```yaml project/ ├── s.yaml # 基础配置或默认配置 ├── s.dev.yaml # 开发环境完整配置 ├── s.test.yaml # 测试环境完整配置 ├── s.staging.yaml # 预发布环境完整配置 ├── s.prod.yaml # 生产环境完整配置 └── code/ └── ... ``` -------------------------------- ### Initialize Search Agent Source: https://docs.agent.run/docs/tutorial/quickstart/manual Initializes the search agent with specific instructions for web searching using Baidu. It configures the agent's model, API key, and available tools. ```javascript 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; } ``` -------------------------------- ### Configure AgentRun SDK using .env file Source: https://docs.agent.run/docs/tutorial/integration/mastra Configure AgentRun SDK by defining environment variables in a .env file. This is recommended to avoid hardcoding sensitive information. Ensure the .env file is added to .gitignore. ```dotenv AGENTRUN_ACCESS_KEY_ID="LT*************" AGENTRUN_ACCESS_KEY_SECRET="DU*************" AGENTRUN_ACCOUNT_ID="143*********149" AGENTRUN_REGION="cn-hangzhou" ```