.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "tutorial/task_model.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_tutorial_task_model.py: .. _model: 模型 ==================== 在本教程中,我们介绍 AgentScope 中集成的模型 API、如何使用它们,以及如何集成新的模型 API。 AgentScope 目前支持的模型 API 和模型提供商包括: .. list-table:: :header-rows: 1 * - API - 类 - 兼容 - 流式 - 工具 - 视觉 - 推理 * - OpenAI - ``OpenAIChatModel`` - vLLM, DeepSeek - ✅ - ✅ - ✅ - ✅ * - DashScope - ``DashScopeChatModel`` - - ✅ - ✅ - ✅ - ✅ * - Anthropic - ``AnthropicChatModel`` - - ✅ - ✅ - ✅ - ✅ * - Gemini - ``GeminiChatModel`` - - ✅ - ✅ - ✅ - ✅ * - Ollama - ``OllamaChatModel`` - - ✅ - ✅ - ✅ - ✅ 为了提供统一的模型接口,上述所有类均被统一为: - ``__call__`` 函数的前三个参数是 ``messages``,``tools`` 和 ``tool_choice``,分别是输入消息,工具函数的 JSON schema,以及工具选择的模式。 - 非流式返回时,返回类型是 ``ChatResponse`` 实例;流式返回时,返回的是 ``ChatResponse`` 的异步生成器。 .. note:: 不同的模型 API 在输入消息格式上有所不同,AgentScope 通过 formatter 模块处理消息的转换,请参考 :ref:`format`。 ``ChatResponse`` 包含大模型生成的推理/文本/工具使用内容、身份、创建时间和使用信息。 .. GENERATED FROM PYTHON SOURCE LINES 66-91 .. code-block:: Python import asyncio import json import os from agentscope.message import TextBlock, ToolUseBlock, ThinkingBlock, Msg from agentscope.model import ChatResponse, DashScopeChatModel response = ChatResponse( content=[ ThinkingBlock( type="thinking", thinking="我应该在 Google 上搜索 AgentScope。", ), TextBlock(type="text", text="我将在 Google 上搜索 AgentScope。"), ToolUseBlock( type="tool_use", id="642n298gjna", name="google_search", input={"query": "AgentScope"}, ), ], ) print(response) .. rst-class:: sphx-glr-script-out .. code-block:: none ChatResponse(content=[{'type': 'thinking', 'thinking': '我应该在 Google 上搜索 AgentScope。'}, {'type': 'text', 'text': '我将在 Google 上搜索 AgentScope。'}, {'type': 'tool_use', 'id': '642n298gjna', 'name': 'google_search', 'input': {'query': 'AgentScope'}}], id='2025-08-27 03:49:07.977_e71f18', created_at='2025-08-27 03:49:07.977', type='chat', usage=None, metadata=None) .. GENERATED FROM PYTHON SOURCE LINES 92-93 以 ``DashScopeChatModel`` 为例,调用和返回结果如下: .. GENERATED FROM PYTHON SOURCE LINES 93-118 .. code-block:: 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()) .. rst-class:: sphx-glr-script-out .. code-block:: none LLM 返回结果: ChatResponse(content=[{'type': 'text', 'text': '你好!有什么可以帮助你的吗?'}], id='2025-08-27 03:49:09.458_1548fc', created_at='2025-08-27 03:49:09.458', type='chat', usage=ChatUsage(input_tokens=10, output_tokens=7, time=1.480118, type='chat'), metadata=None) 作为 Msg 的响应: Msg(id='JshyFDG7XrbohTq6XkpVdZ', name='Friday', content=[{'type': 'text', 'text': '你好!有什么可以帮助你的吗?'}], role='assistant', metadata=None, timestamp='2025-08-27 03:49:09.458', invocation_id='None') .. GENERATED FROM PYTHON SOURCE LINES 119-126 流式返回 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 要启用流式返回,请在模型的构造函数中将 ``stream`` 参数设置为 ``True``。 流式返回中,``__call__`` 方法将返回一个 **异步生成器**,该生成器迭代返回 ``ChatResponse`` 实例。 .. note:: AgentScope 中的流式返回结果为 **累加式**,这意味着每个 chunk 中的内容包含所有之前的内容加上新生成的内容。 .. GENERATED FROM PYTHON SOURCE LINES 126-156 .. code-block:: Python async def example_streaming() -> None: """使用流式模型的示例。""" model = DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], stream=True, ) generator = await model( messages=[ { "role": "user", "content": "从 1 数到 20,只报告数字,不要任何其他信息。", }, ], ) print("响应的类型:", type(generator)) i = 0 async for chunk in generator: print(f"块 {i}") print(f"\t类型: {type(chunk.content)}") print(f"\t{chunk}\n") i += 1 asyncio.run(example_streaming()) .. rst-class:: sphx-glr-script-out .. code-block:: none 响应的类型: 块 0 类型: ChatResponse(content=[{'type': 'text', 'text': '1'}], id='2025-08-27 03:49:10.464_3cb484', created_at='2025-08-27 03:49:10.464', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=1, time=1.004839, type='chat'), metadata=None) 块 1 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n'}], id='2025-08-27 03:49:10.535_70c325', created_at='2025-08-27 03:49:10.535', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=2, time=1.075928, type='chat'), metadata=None) 块 2 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3'}], id='2025-08-27 03:49:10.606_d4aee3', created_at='2025-08-27 03:49:10.606', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=5, time=1.146239, type='chat'), metadata=None) 块 3 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n'}], id='2025-08-27 03:49:10.676_1bd383', created_at='2025-08-27 03:49:10.676', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=8, time=1.216916, type='chat'), metadata=None) 块 4 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n'}], id='2025-08-27 03:49:10.821_96ae91', created_at='2025-08-27 03:49:10.821', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=14, time=1.361825, type='chat'), metadata=None) 块 5 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10'}], id='2025-08-27 03:49:11.001_4cc291', created_at='2025-08-27 03:49:11.002', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=20, time=1.542057, type='chat'), metadata=None) 块 6 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12'}], id='2025-08-27 03:49:11.104_8a4280', created_at='2025-08-27 03:49:11.104', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=26, time=1.644659, type='chat'), metadata=None) 块 7 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14'}], id='2025-08-27 03:49:11.247_7ae938', created_at='2025-08-27 03:49:11.247', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=32, time=1.788018, type='chat'), metadata=None) 块 8 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16'}], id='2025-08-27 03:49:11.796_e3f908', created_at='2025-08-27 03:49:11.796', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=38, time=2.336475, type='chat'), metadata=None) 块 9 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18'}], id='2025-08-27 03:49:11.918_086675', created_at='2025-08-27 03:49:11.918', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=44, time=2.458807, type='chat'), metadata=None) 块 10 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20'}], id='2025-08-27 03:49:12.065_529bc7', created_at='2025-08-27 03:49:12.065', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=50, time=2.605269, type='chat'), metadata=None) 块 11 类型: ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20'}], id='2025-08-27 03:49:12.153_b4aa8a', created_at='2025-08-27 03:49:12.153', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=50, time=2.693546, type='chat'), metadata=None) .. GENERATED FROM PYTHON SOURCE LINES 157-161 推理模型 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AgentScope 通过提供 ``ThinkingBlock`` 来支持推理模型。 .. GENERATED FROM PYTHON SOURCE LINES 161-186 .. code-block:: 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()) .. rst-class:: sphx-glr-script-out .. code-block:: none 最终响应: ChatResponse(content=[{'type': 'thinking', 'thinking': '好的,用户问“我是谁?”,这是一个哲学性的问题,可能需要从多个角度来回答。首先,我需要考虑用户为什么会提出这个问题。可能是在思考自我身份,或者对存在感到困惑。接下来,我应该分析这个问题的不同层面,比如哲学、心理学、社会学等。\n\n从哲学角度来看,笛卡尔的“我思故我在”是一个经典的观点,强调思维作为存在的证明。而佛教中的“无我”则认为自我是虚幻的,由五蕴组成。这些都是不同的视角,需要简要介绍。\n\n心理学方面,自我认同理论,比如埃里克森的发展阶段,可能帮助用户理解自我是如何形成的。同时,自我概念和自我意识的区别也很重要,可以解释用户如何认识自己。\n\n社会学角度,自我是社会互动的产物,比如镜中自我理论,说明他人如何看待我们影响我们的自我认知。这可能帮助用户理解外部因素对自我身份的影响。\n\n另外,用户可能有更深层的需求,比如寻找人生意义或解决身份危机。这时候需要提供一些思考方向,而不是简单的答案。同时,要注意避免过于学术化的解释,保持口语化和易懂。\n\n还要考虑用户可能的背景,如果是学生,可能需要更简洁的解释;如果是成年人,可能需要更深入的分析。不过用户没有提供具体信息,所以保持通用性。\n\n最后,确保回答结构清晰,分点说明不同角度,并鼓励用户进一步思考或提问。避免绝对化的结论,因为这个问题没有标准答案,而是开放性的。'}, {'type': 'text', 'text': '“我是谁?”这个问题看似简单,却可能引发深刻的思考。它可以从多个角度来探讨:\n\n---\n\n### **1. 哲学视角:自我与存在的追问**\n- **笛卡尔的“我思故我在”**:法国哲学家笛卡尔认为,即使怀疑一切,只要“我”在思考,就证明“我”存在。这种观点强调思维作为自我存在的核心。\n- **佛教的“无我”**:佛教认为“我”是虚幻的,是五蕴(色、受、想、行、识)暂时聚合的结果,执着于“我”会导致痛苦。\n- **存在主义**:萨特认为“存在先于本质”,人通过选择和行动定义自己,而非被预设的身份所束缚。\n\n---\n\n### **2. 心理学视角:自我认同的形成**\n- **自我意识**:心理学家认为,自我是通过反思、记忆和对自身行为的觉察形成的。例如,婴儿通过“镜像测试”(看到镜子中的自己)逐渐发展出自我认知。\n- **社会角色**:我们的身份也与社会角色相关(如学生、父母、职业),这些角色塑造了我们对“自己”的理解。\n- **内在与外在的冲突**:有时我们会感到“真实的我”与社会期待的“我”之间存在矛盾,这种冲突可能引发身份困惑。\n\n---\n\n### **3. 生物学视角:身体与基因的限制**\n- **生物学身份**:从基因、DNA到生理特征,我们是特定生物序列的产物。但“我是谁”远不止于生物学定义。\n- **大脑与意识**:神经科学认为,自我是大脑复杂活动的产物,但意识的本质仍是未解之谜。\n\n---\n\n### **4. 人类学与文化视角:社会建构的“我”**\n- **文化塑造**:不同文化对“自我”的定义差异巨大。例如,西方文化更强调个体独立性,而东方文化可能更注重群体关系。\n- **语言与叙事**:我们通过语言和故事构建“我”的叙事,比如“我是谁”可能通过“我经历过什么”“我信仰什么”来回答。\n\n---\n\n### **5. 简单而深刻的回答**\n如果直接回答“你是谁”,可能是一个开放性的探索:\n- **你是你此刻的体验**:此刻的思考、感受、选择,构成了你独特的存在。\n- **你是未完成的可能**:你并非固定不变,而是不断变化、成长的个体。\n- **你是他人眼中的“你”**:但这也只是部分真相,真正的“你”可能远比他人想象的更复杂。\n\n---\n\n### **或许可以这样思考**:\n- **“我是谁”没有标准答案**,它可能是一个持续探索的过程。\n- **答案可能藏在你的选择中**:比如你关心什么、害怕什么、追求什么,这些都在定义你。\n- **“我是谁”也可以是提问本身**:通过不断追问,你可能更接近真实的自己。\n\n如果你愿意分享更多背景,我可以尝试更具体地探讨这个问题。 🌱'}], id='2025-08-27 03:49:25.039_c18842', created_at='2025-08-27 03:49:25.039', type='chat', usage=ChatUsage(input_tokens=11, output_tokens=969, time=12.882604, type='chat'), metadata=None) .. GENERATED FROM PYTHON SOURCE LINES 187-195 工具 API ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 不同的模型提供商在工具 API 方面有所不同,例如工具 JSON schema、工具调用/响应格式。 为了提供统一的接口,AgentScope 通过以下方式解决了这个问题: - 提供了统一的工具调用结构 block :ref:`ToolUseBlock ` 和工具响应结构 :ref:`ToolResultBlock `。 - 在模型类的 ``__call__`` 方法中提供统一的工具接口 ``tools``,接受工具 JSON schema 列表,如下所示: .. GENERATED FROM PYTHON SOURCE LINES 195-216 .. code-block:: Python json_schemas = [ { "type": "function", "function": { "name": "google_search", "description": "在 Google 上搜索查询。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "搜索查询。", }, }, "required": ["query"], }, }, }, ] .. GENERATED FROM PYTHON SOURCE LINES 217-222 进一步阅读 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :ref:`message` - :ref:`prompt` .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 17.066 seconds) .. _sphx_glr_download_tutorial_task_model.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: task_model.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: task_model.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: task_model.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_