备注
Go to the end to download the full example code.
模型¶
在本教程中,我们介绍 AgentScope 中集成的模型 API、如何使用它们,以及如何集成新的模型 API。 AgentScope 目前支持的模型 API 和模型提供商包括:
API |
类 |
兼容 |
流式 |
工具 |
视觉 |
推理 |
|---|---|---|---|---|---|---|
OpenAI |
|
vLLM, DeepSeek |
✅ |
✅ |
✅ |
✅ |
DashScope |
|
✅ |
✅ |
✅ |
✅ |
|
Anthropic |
|
✅ |
✅ |
✅ |
✅ |
|
Gemini |
|
✅ |
✅ |
✅ |
✅ |
|
Ollama |
|
✅ |
✅ |
✅ |
✅ |
备注
当使用 vLLM 时,需要在部署时为不同模型配置相应的工具调用参数,例如 --enable-auto-tool-choice、--tool-call-parser 等参数。更多详情请参考 vLLM 官方文档。
备注
兼容 OpenAI API 的模型(例如 vLLM 部署的模型),推荐使用 OpenAIChatModel,并通过 client_args={"base_url": "http://your-api-endpoint"} 参数指定 API 端点。例如:
OpenAIChatModel(client_args={"base_url": "http://localhost:8000/v1"})
备注
模型的行为参数(如温度、最大长度等)可以通过 generate_kwargs 参数在构造函数中提前设定。例如:
OpenAIChatModel(generate_kwargs={"temperature": 0.3, "max_tokens": 1000})
为了提供统一的模型接口,上述所有类均被统一为:
__call__函数的前三个参数是messages,tools和tool_choice,分别是输入消息,工具函数的 JSON schema,以及工具选择的模式。非流式返回时,返回类型是
ChatResponse实例;流式返回时,返回的是ChatResponse的异步生成器。
备注
不同的模型 API 在输入消息格式上有所不同,AgentScope 通过 formatter 模块处理消息的转换,请参考 format。
ChatResponse 包含大模型生成的推理/文本/工具使用内容、身份、创建时间和使用信息。
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)
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-11-02 00:54:12.778_64d1cf', created_at='2025-11-02 00:54:12.778', type='chat', usage=None, metadata=None)
以 DashScopeChatModel 为例,调用和返回结果如下:
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())
LLM 返回结果: ChatResponse(content=[{'type': 'text', 'text': '你好!有什么可以帮助你的吗?'}], id='2025-11-02 00:54:14.442_bc1ad2', created_at='2025-11-02 00:54:14.442', type='chat', usage=ChatUsage(input_tokens=10, output_tokens=7, time=1.663194, type='chat'), metadata=None)
作为 Msg 的响应: Msg(id='7sg6333vschFabrzAnfjTD', name='Friday', content=[{'type': 'text', 'text': '你好!有什么可以帮助你的吗?'}], role='assistant', metadata=None, timestamp='2025-11-02 00:54:14.442', invocation_id='None')
流式返回¶
要启用流式返回,请在模型的构造函数中将 stream 参数设置为 True。
流式返回中,__call__ 方法将返回一个 异步生成器,该生成器迭代返回 ChatResponse 实例。
备注
AgentScope 中的流式返回结果为 累加式,这意味着每个 chunk 中的内容包含所有之前的内容加上新生成的内容。
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())
响应的类型: <class 'async_generator'>
块 0
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1'}], id='2025-11-02 00:54:15.701_b99ecb', created_at='2025-11-02 00:54:15.701', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=1, time=1.257301, type='chat'), metadata=None)
块 1
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n'}], id='2025-11-02 00:54:16.024_46cf8a', created_at='2025-11-02 00:54:16.024', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=2, time=1.580281, type='chat'), metadata=None)
块 2
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3'}], id='2025-11-02 00:54:16.070_3a7fc5', created_at='2025-11-02 00:54:16.070', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=5, time=1.626744, type='chat'), metadata=None)
块 3
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n'}], id='2025-11-02 00:54:16.114_8f0b52', created_at='2025-11-02 00:54:16.114', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=8, time=1.670768, type='chat'), metadata=None)
块 4
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n'}], id='2025-11-02 00:54:16.204_7dd114', created_at='2025-11-02 00:54:16.204', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=14, time=1.760615, type='chat'), metadata=None)
块 5
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10'}], id='2025-11-02 00:54:16.314_d92f0d', created_at='2025-11-02 00:54:16.314', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=20, time=1.8708, type='chat'), metadata=None)
块 6
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12'}], id='2025-11-02 00:54:16.377_abba21', created_at='2025-11-02 00:54:16.377', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=26, time=1.933087, type='chat'), metadata=None)
块 7
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14'}], id='2025-11-02 00:54:16.468_6d2ca8', created_at='2025-11-02 00:54:16.468', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=32, time=2.024874, type='chat'), metadata=None)
块 8
类型: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16'}], id='2025-11-02 00:54:16.788_9d4fc9', created_at='2025-11-02 00:54:16.788', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=38, time=2.344886, type='chat'), metadata=None)
块 9
类型: <class 'list'>
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-11-02 00:54:16.859_a82d01', created_at='2025-11-02 00:54:16.859', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=44, time=2.415011, type='chat'), metadata=None)
块 10
类型: <class 'list'>
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-11-02 00:54:16.946_d5c60c', created_at='2025-11-02 00:54:16.946', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=50, time=2.50241, type='chat'), metadata=None)
块 11
类型: <class 'list'>
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-11-02 00:54:17.031_11f4fa', created_at='2025-11-02 00:54:17.031', type='chat', usage=ChatUsage(input_tokens=26, output_tokens=50, time=2.587002, type='chat'), metadata=None)
推理模型¶
AgentScope 通过提供 ThinkingBlock 来支持推理模型。
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())
最终响应:
ChatResponse(content=[{'type': 'thinking', 'thinking': '好的,用户问“我是谁?”,这是一个哲学性的问题,可能需要从多个角度来回答。首先,我需要确定用户的具体需求是什么。他们可能是在寻找自我认知,或者对存在本质的思考,也可能是有心理上的困惑。接下来,我应该考虑如何组织回答,既要涵盖哲学观点,也要涉及心理学和科学的角度。\n\n用户可能没有明确说明他们的背景,所以需要保持回答的通用性。同时,要避免过于学术化的语言,让回答更易懂。可能需要提到不同的哲学流派,比如笛卡尔的“我思故我在”,存在主义的观点,以及现代心理学中的自我概念。\n\n另外,还要考虑到用户可能的深层需求,比如寻找自我认同或解决内心的困惑。这时候,可以建议他们进行自我反思,或者寻求专业的帮助。需要确保回答既全面又不显得冗长,同时保持同理心。\n\n还要检查是否有遗漏的重要观点,比如东方哲学中的“无我”概念,或者神经科学对自我意识的研究。确保信息准确,并且引用权威来源。最后,保持语气友好和鼓励,让用户感到被理解和支持。'}, {'type': 'text', 'text': '“我是谁?”是一个跨越哲学、心理学、宗教和科学的永恒命题。不同视角下,这个问题可能有不同的答案:\n\n---\n\n### **1. 哲学视角**\n- **笛卡尔**(René Descartes): \n “我思故我在”(*Cogito, ergo sum*)。他认为“我”的本质是思考的主体,即使怀疑一切,怀疑本身证明了“我”的存在。\n- **存在主义**(如萨特): \n 人没有预设的本质,而是通过选择和行动定义自己。“存在先于本质”,“我”是不断生成的。\n- **东方哲学**(如佛教、道家): \n - **佛教**:认为“我”是五蕴(色、受、想、行、识)的暂时聚合,本质是“无我”(Anatta)。 \n - **道家**:强调“道”是万物本源,“我”是道的显现,与自然合一。\n\n---\n\n### **2. 心理学视角**\n- **自我认同**: \n 个体通过经历、关系、价值观和目标逐渐构建“自我”。心理学家埃里克森(Erikson)提出,人的一生中不断探索“我是谁”的问题。\n- **认知与情感**: \n “我”是大脑对自身意识的感知,包括记忆、情绪、身体感受和对世界的认知。\n\n---\n\n### **3. 科学视角**\n- **神经科学**: \n “我”可能源于大脑的默认模式网络(DMN),它负责自我反思、回忆和想象。但科学家尚未完全解释意识的起源。\n- **量子物理与意识研究**: \n 一些理论尝试将意识与量子现象关联,但目前仍无定论。\n\n---\n\n### **4. 宗教与灵性视角**\n- **一神教**(如基督教、伊斯兰教): \n “我”是上帝创造的个体,灵魂与肉体的结合,最终归于神圣。\n- **泛神论**: \n “我”是宇宙的一部分,与万物一体。\n\n---\n\n### **5. 个人层面的探索**\n- **你可能在问**: \n - 我的价值是什么? \n - 我的使命是什么? \n - 我与他人的关系如何定义我? \n 这些问题没有标准答案,但可以通过**自我反思**(如写日记、冥想)或**与他人对话**逐渐接近。\n\n---\n\n### **6. 简单的回答**\n如果需要一个直接的答案: \n**“你是此刻正在思考这个问题的‘你’。”** \n你的存在本身,就是答案的一部分。\n\n---\n\n如果你愿意分享更多背景,我可以尝试更具体地探讨。这个问题或许没有终点,但探索的过程本身,可能就是意义所在。 🌱'}], id='2025-11-02 00:54:31.030_7b6bdd', created_at='2025-11-02 00:54:31.030', type='chat', usage=ChatUsage(input_tokens=11, output_tokens=841, time=13.994821, type='chat'), metadata=None)
工具 API¶
不同的模型提供商在工具 API 方面有所不同,例如工具 JSON schema、工具调用/响应格式。 为了提供统一的接口,AgentScope 通过以下方式解决了这个问题:
提供了统一的工具调用结构 block ToolUseBlock 和工具响应结构 ToolResultBlock。
在模型类的
__call__方法中提供统一的工具接口tools,接受工具 JSON schema 列表,如下所示:
json_schemas = [
{
"type": "function",
"function": {
"name": "google_search",
"description": "在 Google 上搜索查询。",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索查询。",
},
},
"required": ["query"],
},
},
},
]
进一步阅读¶
Total running time of the script: (0 minutes 18.257 seconds)