### Install AgentScope and OpenJudge Source: https://doc.agentscope.io/zh_CN/tutorial/task_eval_openjudge.html Before running the tutorial, install the necessary dependencies for AgentScope and OpenJudge. ```bash pip install agentscope py-openjudge ``` -------------------------------- ### Run Task Tuning Script with Ray Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_tuner.rst.txt This command sequence demonstrates how to start a Ray cluster head node and then execute the Python tuning script. Ensure Ray is installed and configured before running. ```bash ray start --head python main.py ``` -------------------------------- ### Real-time TTS Streaming Example Setup Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_tts.rst.txt Initializes a real-time TTS model (DashScopeRealtimeTTSModel) for scenarios where text is generated incrementally. This setup is designed for low-latency applications, such as streaming LLM responses. ```Python async def example_realtime_tts_streaming(): tts_model = DashScopeRealtimeTTSModel( api_key=os.environ.get("DASHSCOPE_API_KEY", ""), model_name="qwen3-tts-flash-realtime", voice="Cherry", stream=False, ) # 实时 tts 模型接收累积的文本块 ``` -------------------------------- ### Install AgentScope from Source Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/quickstart_installation.rst.txt Clone the AgentScope repository from GitHub and install it in editable mode for development. ```bash git clone -b main https://github.com/agentscope-ai/agentscope cd agentscope pip install -e . ``` -------------------------------- ### Example of Structured Output Source: https://doc.agentscope.io/zh_CN/tutorial/task_agent.html Demonstrates how to use an agent to generate output conforming to a specified structured model and prints the metadata. ```python import asyncio import json from agentscope.agents import agent from agentscope.message import Msg async def example_structured_output() -> None: """结构化输出示例""" res = await agent( Msg( "user", "介绍爱因斯坦", "user", ), structured_model=Model, ) print("\n结构化输出:") print(json.dumps(res.metadata, indent=4, ensure_ascii=False)) asyncio.run(example_structured_output()) ``` -------------------------------- ### Configure and Run Tuning Process Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_tuner.rst.txt Illustrates the configuration and initiation of the tuning process using the 'tuner' module. Requires installation of Trinity-RFT. ```Python from agentscope.tuner import tune, AlgorithmConfig, DatasetConfig, TunerModelConfig # 你的工作流 / 评判函数 ... ``` -------------------------------- ### Install Tablestore Dependencies Source: https://doc.agentscope.io/zh_CN/tutorial/task_memory.html Install the necessary packages for Tablestore integration and AgentScope memory. ```shell pip install tablestore tablestore-for-agent-memory ``` -------------------------------- ### Install and Run AgentScope Studio Source: https://doc.agentscope.io/zh_CN/_downloads/a29fb4d5a2f8a541ea7628de96d494f5/task_studio.ipynb Commands to install the AgentScope Studio CLI globally via npm and launch the local server. ```bash npm install -g @agentscope/studio as_studio ``` -------------------------------- ### Multiple Middleware Execution Example Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_middleware.rst.txt This example demonstrates the registration and execution of multiple middleware functions (middleware_1 and middleware_2) in a specific order. It shows how the 'onion model' applies, where preprocessing occurs sequentially before the tool call and postprocessing occurs in reverse order after the tool call. ```python async def example_multiple_middleware() -> None: """多个中间件的示例。""" toolkit = Toolkit() toolkit.register_tool_function(search_tool) # 按顺序注册中间件 toolkit.register_middleware(middleware_1) toolkit.register_middleware(middleware_2) result = await toolkit.call_tool_function( ToolUseBlock( type="tool_use", id="5", name="search_tool", input={"query": "测试"}, ), ) async for response in result: print(f"\n最终结果:{response.content[0]['text']}") ``` -------------------------------- ### Start AgentScope Studio Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_studio.rst.txt This command starts the AgentScope Studio application. Once running, it can be accessed via a web browser. ```bash as_studio ``` -------------------------------- ### Install OpenJudge and AgentScope Source: https://doc.agentscope.io/zh_CN/_downloads/111fb4ecba0dae3d1df2a707ee3f76d6/task_eval_openjudge.ipynb Before running the tutorial, install the necessary dependencies: 'agentscope' and 'py-openjudge'. This command ensures you have the required libraries for integration. ```bash pip install agentscope py-openjudge ``` -------------------------------- ### Running the Tuning Script Source: https://doc.agentscope.io/zh_CN/tutorial/task_tuner.html Commands to start the Ray head node and run the main Python script for tuning. This initiates the training process. ```bash ray start --head python main.py ``` -------------------------------- ### Generic RAG Integration with ReActAgent Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_rag.rst.txt This example demonstrates a more general way to integrate RAG by passing the knowledge base directly to the ReActAgent. The agent automatically retrieves knowledge at the start of each reply. ```Python async def example_generic_manner() -> None: """以通用方式将 RAG 模块与 ReActAgent 集成的示例。""" # 创建一个 ReAct 智能体 agent = ReActAgent( name="Friday", sys_prompt="You're a helpful assistant named Friday.", model=DashScopeChatModel( api_key=os.environ["DASHSCOPE_API_KEY"], model_name="qwen-max", ), formatter=DashScopeChatFormatter(), # 将知识库传递给智能体 knowledge=knowledge, ) await agent( Msg( "user", "你知道李明的父亲是谁吗?", "user", ), ) print("\n查看智能体记忆中检索信息如何插入:") content = (await agent.memory.get_memory())[1].content print(json.dumps(content, indent=2, ensure_ascii=False)) asyncio.run(example_generic_manner()) ``` -------------------------------- ### Example: Using the logging middleware with a search tool Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_middleware.rst.txt Demonstrates how to register a custom logging middleware and a search tool with a Toolkit, then execute the tool to see the middleware in action. The output shows the logged information before and after the tool's response. ```Python async def search_tool(query: str) -> ToolResponse: """一个简单的搜索工具。 Args: query (`str`): 搜索查询。 Returns: `ToolResponse`: 搜索结果。 """ return ToolResponse( content=[ TextBlock( type="text", text=f"'{query}' 的搜索结果", ), ], ) async def example_logging_middleware() -> None: """使用日志中间件的示例。""" # 创建工具包并注册工具 toolkit = Toolkit() toolkit.register_tool_function(search_tool) # 注册中间件 toolkit.register_middleware(logging_middleware) # 调用工具 result = await toolkit.call_tool_function( ToolUseBlock( type="tool_use", id="1", name="search_tool", input={"query": "AgentScope"}, ), ) async for response in result: print(f"\n[最终] {response.content[0]['text']}\n") print("=" * 60) print("示例 1:日志中间件") print("=" * 60) asyncio.run(example_logging_middleware()) ``` -------------------------------- ### Build and Query Knowledge Base with Qdrant Source: https://doc.agentscope.io/zh_CN/tutorial/task_rag.html This example demonstrates how to build a knowledge base using AgentScope. It involves reading documents, initializing a SimpleKnowledge base with an embedding model (DashScopeTextEmbedding) and a vector store (QdrantStore in memory mode), adding documents, and then retrieving information based on a query. ```python import asyncio import os from agentscope.rag import SimpleKnowledge, TextReader, Document from agentscope.agents import Agent from agentscope.message import Msg from agentscope.models import DashScopeTextEmbedding from agentscope.vector_store import QdrantStore async def example_text_reader(print_docs: bool) -> list[Document]: """使用 TextReader 读取文本字符串,并将文本分块为 Document 对象。""" # 创建 TextReader 对象 reader = TextReader(chunk_size=512, split_by="paragraph") # 读取文本字符串 documents = await reader( text=( # 我们准备一些文本数据用于演示 RAG 功能。 "我的名字是李明,今年28岁。\n" "我居住在中国杭州,是一名算法工程师。我喜欢打篮球和玩游戏。\n" "我父亲的名字是李强,是一名医生,我的母亲是陈芳芳,是一名教师,她总是指导我学习。\n" "我现在在北京大学攻读博士学位,研究方向是人工智能。\n" "我最好的朋友是王伟,我们从小一起长大,现在他是一名律师。" ), ) if print_docs: print(f"文本被分块为 {len(documents)} 个 Document 对象:") for idx, doc in enumerate(documents): print(f"Document {idx}:") print("\tScore: ", doc.score) print( "\tMetadata: ", json.dumps(doc.metadata, indent=2, ensure_ascii=False), "\n", ) return documents async def build_knowledge_base() -> SimpleKnowledge: """构建知识库。""" # 读取 documents 数据 documents = await example_text_reader(print_docs=False) # 创建一个内存中的 Qdrant 向量存储,以及使用 DashScopeTextEmbedding 作为嵌入模型,初始化知识库 knowledge = SimpleKnowledge( # 提供一个 embedding 模型用于将文本转换为向量 embedding_model=DashScopeTextEmbedding( api_key=os.environ["DASHSCOPE_API_KEY"], model_name="text-embedding-v4", dimensions=1024, ), # 选择 Qdrant 作为向量存储 embedding_store=QdrantStore( location=":memory:", # 使用内存模式 collection_name="test_collection", dimensions=1024, # 嵌入向量的维度必须与嵌入模型输出的维度一致 ), ) # 将 documents 添加到知识库中 await knowledge.add_documents(documents) # 从知识库中检索数据 docs = await knowledge.retrieve( query="李明的父亲是谁?", limit=3, score_threshold=0.5, ) print("检索到的 Document 对象:") for doc in docs: print(doc, "\n") return knowledge knowledge = asyncio.run(build_knowledge_base()) ``` -------------------------------- ### OpenAI Token Counting Example Source: https://doc.agentscope.io/zh_CN/tutorial/task_token.html Demonstrates how to use the `OpenAITokenCounter` to calculate the token count for a list of messages. Ensure you have the necessary libraries installed and potentially API keys configured if required by the underlying model. ```python import asyncio from agentscope.token import OpenAITokenCounter async def example_token_counting(): # 示例消息 messages = [ {"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Hi, how can I help you?"}, ] # OpenAI token 计数 openai_counter = OpenAITokenCounter(model_name="gpt-4.1") n_tokens = await openai_counter.count(messages) print(f"Token 数量: {n_tokens}") asyncio.run(example_token_counting()) ``` -------------------------------- ### Manual Plan Creation using create_plan Tool Source: https://doc.agentscope.io/zh_CN/_downloads/a776edd4ceeb1e1c060eeaa2e2a79b11/task_plan.ipynb Demonstrates how to manually create a plan using the 'create_plan' tool function. This is useful for initializing ReActAgent with a specific plan for comprehensive research on LLM capabilities. ```python # Example of manual plan creation to conduct comprehensive research on LLM capabilities # This would typically involve calling the create_plan tool function. # For instance: # plan_notebook.create_plan("Research LLM capabilities") # The exact implementation details would depend on the context and available parameters. ``` -------------------------------- ### Example Agent with TTS Integration Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_tts.rst.txt Demonstrates how to create a ReActAgent with a TTS model enabled. The agent automatically synthesizes its text responses into speech. This setup is suitable for interactive chat applications where voice output is desired. ```Python async def example_agent_with_tts() -> None: """使用带 TTS 的 ReActAgent 的示例。""" # 创建启用了 TTS 的智能体 agent = ReActAgent( name="Assistant", sys_prompt="你是一个有用的助手。", model=DashScopeChatModel( api_key=os.environ["DASHSCOPE_API_KEY"], model_name="qwen-max", stream=True, ), formatter=DashScopeChatFormatter(), # 启用 TTS tts_model=DashScopeRealtimeTTSModel( api_key=os.getenv("DASHSCOPE_API_KEY"), model_name="qwen3-tts-flash-realtime", voice="Cherry", ), ) user = UserAgent("User") # 像正常情况一样构建对话 msg = None while True: msg = await agent(msg) msg = await user(msg) if msg.get_text_content() == "exit": break ``` -------------------------------- ### Using SequentialPipeline Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_pipeline.rst.txt Demonstrates how to create and use a SequentialPipeline with a list of agents. The pipeline executes agents in a sequential manner. It can be reused with different inputs. ```python from agentscope.pipeline import SequentialPipeline # 创建管道对象 pipeline = SequentialPipeline(agents=[alice, bob, charlie, david]) # 调用管道 msg = await pipeline(msg=None) # 使用不同输入复用管道 msg = await pipeline(msg=Msg("user", "你好!", "user")) ``` -------------------------------- ### Run Workflow Function with Sample Task Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_tuner.rst.txt Demonstrates how to execute a workflow function with a sample task and a DashScopeChatModel before formal training. Ensures the workflow logic is correct. ```Python import asyncio import os from agentscope.model import DashScopeChatModel task = {"question": "123 加 456 等于多少?", "answer": "579"} model = DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ) workflow_output = asyncio.run(example_workflow_function(task, model)) assert isinstance( workflow_output.response, Msg, ), "在此示例中,响应应为 Msg 实例。" print("\n工作流响应:", workflow_output.response.get_text_content()) ``` -------------------------------- ### Realtime Agent Initialization and Usage Example (Python) Source: https://doc.agentscope.io/zh_CN/_downloads/b9ea2d5f1a0b19c3900464ff9de7596e/task_realtime.ipynb This Python code demonstrates how to initialize and use a realtime agent named 'Friday' with a system prompt and a DashScope model. It sets up an asynchronous queue to handle messages from the agent and starts the agent's communication loop. The example also includes tasks for handling agent messages and starting/stopping the agent. ```python async def example_realtime_agent() -> None: """Creates and uses a realtime agent example.""" agent = RealtimeAgent( name="Friday", sys_prompt="You are an assistant named Friday.", model=DashScopeRealtimeModel( model_name="qwen3-omni-flash-realtime", api_key=os.getenv("DASHSCOPE_API_KEY"), ), ) # Create a queue to receive messages from the agent outgoing_queue = asyncio.Queue() # The agent is ready to process input # Process outgoing messages in a separate task async def handle_agent_messages(): while True: event = await outgoing_queue.get() # Process the event (e.g., send to frontend via WebSocket) print(f"Agent event: {event.type}") # Start the message handling task asyncio.create_task(handle_agent_messages()) # Start the agent (establish connection) await agent.start(outgoing_queue) # Stop the agent after completion await agent.stop() ``` -------------------------------- ### Calculate Token Count with OpenAI Token Counter Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_token.rst.txt This example demonstrates how to use the OpenAITokenCounter to calculate the token count for a list of messages. Ensure you have the necessary libraries installed and understand that the calculation might differ slightly from official OpenAI results due to the local computation method. ```Python import asyncio from agentscope.token import OpenAITokenCounter async def example_token_counting(): # 示例消息 messages = [ {"role": "user", "content": "Hello!"}, {"role": "assistant", "content": "Hi, how can I help you?"}, ] # OpenAI token 计数 openai_counter = OpenAITokenCounter(model_name="gpt-4.1") n_tokens = await openai_counter.count(messages) print(f"Token 数量: {n_tokens}") asyncio.run(example_token_counting()) ``` -------------------------------- ### Install AgentScope Studio via npm Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_studio.rst.txt This command installs the AgentScope Studio globally using npm. Ensure you have Node.js and npm installed on your system. ```bash npm install -g @agentscope/studio ``` -------------------------------- ### Manual Plan Specification Example Source: https://doc.agentscope.io/zh_CN/tutorial/task_plan.html Illustrates how to manually create a plan with multiple subtasks using the `create_plan` tool. This is useful when developers want to define the task structure explicitly. ```python async def manual_plan_specification() -> None: """手动计划规范示例。""" await plan_notebook.create_plan( name="智能体研究", description="对基于LLM的智能体进行全面研究", expected_outcome="一份Markdown格式的报告,回答三个问题:1. 什么是智能体?2. 智能体的当前技术水平是什么?3. 智能体的未来趋势是什么?", subtasks=[ SubTask( name="搜索智能体相关调研论文", description=( "在多个来源搜索调研论文,包括" "Google Scholar、arXiv和Semantic Scholar。必须" "在2021年后发表且引用数超过50。" ), expected_outcome="Markdown格式的论文列表", ), SubTask( name="阅读和总结论文", description="阅读前一步找到的论文,并总结关键点,包括定义、分类、挑战和关键方向。", expected_outcome="Markdown格式的关键点总结", ), SubTask( name="研究大公司的最新进展", description=( "研究大公司的最新进展,包括但不限于Google、Microsoft、OpenAI、" "Anthropic、阿里巴巴和Meta。查找官方博客或新闻文章。" ), expected_outcome="大公司的最新进展", ), SubTask( name="撰写报告", description="基于前面的步骤撰写报告,并回答预期结果中的三个问题。", expected_outcome=( "一份Markdown格式的报告,回答三个问题:1. " "什么是智能体?2. 智能体的当前技术水平" "是什么?3. 智能体的未来趋势是什么?" ), ), ], ) print("当前提示消息:\n") msg = await plan_notebook.get_current_hint() print(f"{msg.name}: {msg.content}") asyncio.run(manual_plan_specification()) ``` -------------------------------- ### Initialize and Use TablestoreMemory Source: https://doc.agentscope.io/zh_CN/tutorial/task_memory.html Demonstrates how to initialize TablestoreMemory with credentials and session information, add messages, and retrieve messages by mark. ```python import asyncio from agentscope.memory import TablestoreMemory from agentscope.message import Msg async def tablestore_memory_example(): # 创建 Tablestore 记忆 memory = TablestoreMemory( end_point="https://your-instance.cn-hangzhou.ots.aliyuncs.com", instance_name="your-instance-name", access_key_id="your-access-key-id", access_key_secret="your-access-key-secret", # 可选地指定 user_id 和 session_id user_id="user_1", session_id="session_1", ) # 向记忆中添加消息 await memory.add( Msg("Alice", "生成一份关于AgentScope的报告", "user"), ) # 添加一条带有标记"hint"的提示消息 await memory.add( Msg( "system", "首先创建一个计划来收集信息,\n然后逐步生成报告。", "system", ), marks="hint", ) # 检索带有标记"hint"的消息 msgs = await memory.get_memory(mark="hint") for msg in msgs: print(f"- {msg}") # 完成后关闭 Tablestore 客户端连接 await memory.close() asyncio.run(tablestore_memory_example()) ``` -------------------------------- ### RedisMemory Output Example Source: https://doc.agentscope.io/zh_CN/tutorial/task_memory.html Example output showing a retrieved message with its associated metadata from RedisMemory. ```text 带有标记'hint'的消息: - Msg(id='hhyaaKo3ePm6YW5idmK5Q5', name='system', content='首先创建一个计划来收集信息,然后逐步生成报告。', role='system', metadata={}, timestamp='2026-05-25 08:56:10.468', invocation_id='None') ``` -------------------------------- ### Python Example of Reasoning Model Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_model.rst.txt Demonstrates how to use a reasoning model with AgentScope. It initializes a DashScopeChatModel with reasoning enabled and processes a user query, printing the final response. ```Python async def example_reasoning() -> None: """使用推理模型的示例。""" model = DashScopeChatModel( model_name="qwen-turbo", api_key=os.environ["DASHSCOPE_API_KEY"], enable_thinking=True, ) res = await model( messages=[ {"role": "user", "content": "我是谁?"}, ], ) last_chunk = None async for chunk in res: last_chunk = chunk print("最终响应:") print(last_chunk) asyncio.run(example_reasoning()) ``` -------------------------------- ### Setup and Agent Initialization for Multi-Agent Debate Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/workflow_multiagent_debate.rst.txt Initializes agents (Alice, Bob, Moderator) and defines the debate topic. Requires setting the DASHSCOPE_API_KEY environment variable. ```Python import asyncio import os from pydantic import Field, BaseModel from agentscope.agent import ReActAgent from agentscope.formatter import ( DashScopeMultiAgentFormatter, ) from agentscope.message import Msg from agentscope.model import DashScopeChatModel from agentscope.pipeline import MsgHub # 准备一个话题 topic = "两个圆外切且没有相对滑动。圆A的半径是圆B半径的1/3。圆A绕圆B滚动一圈回到起点。圆A总共会旋转多少次?" # 创建两个辩论者智能体,Alice 和 Bob,他们将讨论这个话题。 def create_solver_agent(name: str) -> ReActAgent: """获取一个解决者智能体。""" return ReActAgent( name=name, sys_prompt=f"你是一个名为 {name} 的辩论者。你好,欢迎来到" "辩论比赛。我们的目标是找到正确答案,因此你没有必要完全同意对方" f"的观点。辩论话题如下所述:{topic}", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=False, ), formatter=DashScopeMultiAgentFormatter(), ) alice, bob = [create_solver_agent(name) for name in ["Alice", "Bob"]] # 创建主持人智能体 moderator = ReActAgent( name="Aggregator", sys_prompt=f"""你是一个主持人。将有两个辩论者参与辩论比赛。他们将就以下话题提出观点并进行讨论: `````` {topic} `````` 在每轮讨论结束时,你将评估辩论是否结束,以及话题正确的答案。""", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=False, ), # 使用多智能体格式化器,因为主持人将接收来自多于用户和助手的消息 formatter=DashScopeMultiAgentFormatter(), ) # 主持人的结构化输出模型 class JudgeModel(BaseModel): """主持人的结构化输出模型。""" finished: bool = Field(description="辩论是否结束。") correct_answer: str | None = Field( description="辩论话题的正确答案,仅当辩论结束时提供该字段。否则保留为 None。", default=None, ) ``` -------------------------------- ### Verify AgentScope Installation Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/quickstart_installation.rst.txt Run this Python code to verify that AgentScope is installed correctly and to check its version. ```Python import agentscope print(agentscope.__version__) ``` -------------------------------- ### Install AgentScope from PyPI Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/quickstart_installation.rst.txt Use this command to install the latest stable version of AgentScope from the Python Package Index. ```bash pip install agentscope ``` -------------------------------- ### Broadcast Message using MsgHub Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_pipeline.rst.txt Demonstrates using MsgHub as an asynchronous context manager to broadcast an initial message to a list of participants (Alice, Bob, Charlie). Each participant then introduces themselves. ```Python async def example_broadcast_message(): """使用 MsgHub 广播消息的示例。""" # 创建消息中心 async with MsgHub( participants=[alice, bob, charlie], announcement=Msg( "user", "现在请简要介绍一下自己,包括你的姓名、年龄和职业。", "user", ), ) as hub: # 无需手动消息传递的群聊 await alice() await bob() await charlie() asyncio.run(example_broadcast_message()) ``` -------------------------------- ### Example Token Count Output Source: https://doc.agentscope.io/zh_CN/tutorial/task_token.html This snippet shows the expected output when running the OpenAI token counting example. ```text Token 数量: 21 ``` -------------------------------- ### Agent Response Example Source: https://doc.agentscope.io/zh_CN/tutorial/quickstart_agent.html This is an example of the output generated by the custom agent 'Friday' in response to a user's query. ```text Friday: 我是Friday,一个设计来帮助回答问题、提供信息和协助各种任务的虚拟助手。如果你有任何问题或需要帮助的地方,请尽管告诉我! ``` -------------------------------- ### Initialize ReActAgent with PlanNotebook Source: https://doc.agentscope.io/zh_CN/_downloads/a776edd4ceeb1e1c060eeaa2e2a79b11/task_plan.ipynb Shows how to configure a ReActAgent instance with a PlanNotebook, enabling the agent to utilize structured planning for its tasks. This setup supports both manual and autonomous plan management scenarios. ```python agent = ReActAgent( name="Friday", sys_prompt="你是一个有用的助手。", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ), formatter=DashScopeChatFormatter(), plan_notebook=plan_notebook, ) ``` ```python agent = ReActAgent( name="Friday", sys_prompt="你是一个有用的助手。", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ), formatter=DashScopeChatFormatter(), plan_notebook=PlanNotebook(), ) ``` -------------------------------- ### Example Usage of DashScopeChatModel Source: https://doc.agentscope.io/zh_CN/tutorial/task_model.html This example demonstrates how to instantiate and use `DashScopeChatModel` for chat interactions. It shows how to process the response and convert it into a `Msg` object. ```python async def example_model_call() -> None: """使用 DashScopeChatModel 的示例。""" model = DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=False, ) res = await model( messages=[ {"role": "user", "content": "你好!"}, ], ) # 您可以直接使用响应内容创建 ``Msg`` 对象 msg_res = Msg("Friday", res.content, "assistant") print("LLM 返回结果:", res) print("作为 Msg 的响应:", msg_res) asyncio.run(example_model_call()) ``` ```text LLM 返回结果: ChatResponse(content=[{'type': 'text', 'text': '你好!有什么我可以帮助你的吗?'}], id='855abb35-10e3-985e-ade4-30b0252fd1aa', created_at='2026-05-25 08:53:27.624', type='chat', usage=ChatUsage(input_tokens=10, output_tokens=8, time=2.354106, type='chat', metadata=GenerationUsage(input_tokens=10, output_tokens=8)), metadata=None) 作为 Msg 的响应: Msg(id='P4eDMoVAVQscyEQQpwLAn3', name='Friday', content=[{'type': 'text', 'text': '你好!有什么我可以帮助你的吗?'}], role='assistant', metadata={}, timestamp='2026-05-25 08:53:27.624', invocation_id='None') ``` -------------------------------- ### QA Benchmark Setup with OpenJudge Graders Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_eval_openjudge.rst.txt This snippet demonstrates setting up a QA Benchmark using AgentScope and OpenJudge's RelevanceGrader and CorrectnessGrader. It includes loading data, configuring LLM parameters, and defining data mappers for the graders. ```Python import os from typing import Generator from openjudge.graders.common.relevance import RelevanceGrader from openjudge.graders.common.correctness import CorrectnessGrader from agentscope.evaluate import ( Task, BenchmarkBase, ) class QABenchmark(BenchmarkBase): def __init__(self): super().__init__( name="QA Quality Benchmark", description="Benchmark to evaluate QA systems using OpenJudge grader classes", ) self.dataset = self._load_data() def _load_data(self): tasks = [] # 配置 LLM Grader 的模型参数 # 注意:如果不使用环境变量,请在此处设置 "api_key" model_config = { "model": "qwen3-32b", "api_key": os.environ.get("DASHSCOPE_API_KEY"), "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1", } for data in QA_BENCHMARK_DATASET: # 定义映射关系:左侧是 OpenJudge 的键,右侧是 AgentScope 的数据路径 mapper = { "query": "data.input", "response": "solution.output", "context": "data.ground_truth", "reference_response": "data.reference_output", } # 通过 Adapter 实例化 Metrics metrics = [ OpenJudgeMetric( grader_cls=RelevanceGrader, data=data, mapper=mapper, name="Relevance", model=model_config, ), OpenJudgeMetric( grader_cls=CorrectnessGrader, data=data, ``` -------------------------------- ### Create and run a ReAct Agent with a simple task Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/quickstart_agent.rst.txt This snippet demonstrates how to initialize a ReActAgent with a name, system prompt, model, formatter, and toolkit. It then sends a message to the agent and awaits its response, executing a Python code task. ```Python async def creating_react_agent() -> None: """创建一个 ReAct 智能体并运行一个简单任务。""" # 准备工具 toolkit = Toolkit() toolkit.register_tool_function(execute_python_code) jarvis = ReActAgent( name="Jarvis", sys_prompt="你是一个名为 Jarvis 的助手", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=True, enable_thinking=False, ), formatter=DashScopeChatFormatter(), toolkit=toolkit, memory=InMemoryMemory(), ) msg = Msg( name="user", content="你好!Jarvis,用 Python 运行 Hello World。", role="user", ) await jarvis(msg) asyncio.run(creating_react_agent()) ``` -------------------------------- ### Manually create a plan Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_plan.rst.txt Demonstrates how to manually create a plan using the create_plan tool function. This involves specifying the plan's name, description, expected outcome, and a list of subtasks. ```Python async def manual_plan_specification() -> None: """手动计划规范示例。""" await plan_notebook.create_plan( name="智能体研究", description="对基于LLM的智能体进行全面研究", expected_outcome="一份Markdown格式的报告,回答三个问题:1. 什么是智能体?2. 智能体的当前技术水平是什么?3. 智能体的未来趋势是什么?", subtasks=[ SubTask( name="搜索智能体相关调研论文", description=( "在多个来源搜索调研论文,包括" "Google Scholar、arXiv和Semantic Scholar。必须" "在2021年后发表且引用数超过50。" ), expected_outcome="Markdown格式的论文列表", ``` -------------------------------- ### Install AgentScope with Full Dependencies (Windows) Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/quickstart_installation.rst.txt For Windows users, install AgentScope with the 'full' extra dependencies, which include model APIs and tool functions. ```bash pip install agentscope[full] ``` -------------------------------- ### Example Output from Toy Benchmark Evaluation Source: https://doc.agentscope.io/zh_CN/_sources/tutorial/task_eval.rst.txt This output shows the execution logs and evaluation metrics from running the toy benchmark with the GeneralEvaluator. It includes agent interactions, tool usage, and a summary of the math check metric. ```none /home/runner/work/agentscope/agentscope/src/agentscope/model/_dashscope_model.py:232: DeprecationWarning: 'required' is not supported by DashScope API. It will be converted to 'auto'. warnings.warn( Friday: { "type": "tool_use", "name": "generate_response", "input": { "answer_as_number": 4 }, "id": "call_8a4301bda9ae4938bada91" } system: { "type": "tool_result", "id": "call_8a4301bda9ae4938bada91", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } Friday: The answer to 2 + 2 is 4. /home/runner/work/agentscope/agentscope/src/agentscope/model/_dashscope_model.py:232: DeprecationWarning: 'required' is not supported by DashScope API. It will be converted to 'auto'. warnings.warn( Friday: { "type": "tool_use", "name": "generate_response", "input": { "answer_as_number": 73021 }, "id": "call_e04759eef3954e3cba0d52" } system: { "type": "tool_result", "id": "call_e04759eef3954e3cba0d52", "name": "generate_response", "output": [ { "type": "text", "text": "Successfully generated response." } ] } Friday: The sum of 12345, 54321, 6789, and 9876 is 73021. Repeat ID: 0 Metric: math check number equal Type: MetricType.NUMERICAL Involved tasks: 2 Completed tasks: 2 Incomplete tasks: 0 Aggregation: { "mean": 0.5, "max": 1.0, "min": 0.0 } ```