Note
Go to the end to download the full example code.
Model¶
In this tutorial, we introduce the model APIs integrated in AgentScope, how to use them and how to integrate new model APIs. The supported model APIs and providers include:
API |
Class |
Compatible |
Streaming |
Tools |
Vision |
Reasoning |
---|---|---|---|---|---|---|
OpenAI |
|
vLLM, DeepSeek |
✅ |
✅ |
✅ |
✅ |
DashScope |
|
✅ |
✅ |
✅ |
✅ |
|
Anthropic |
|
✅ |
✅ |
✅ |
✅ |
|
Gemini |
|
✅ |
✅ |
✅ |
✅ |
|
Ollama |
|
✅ |
✅ |
✅ |
✅ |
To provide unified model interfaces, the above model classes has the following common methods:
The first three arguments of the
__call__
method aremessages
,tools
andtool_choice
, representing the input messages, JSON schema of tool functions, and tool selection mode, respectively.The return type are either a
ChatResponse
instance or an async generator ofChatResponse
in streaming mode.
Note
Different model APIs differ in the input message format, refer to Prompt Formatter for more details.
The ChatResponse
instance contains the generated thinking/text/tool use content, identity, created time and usage information.
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="I should search for AgentScope on Google.",
),
TextBlock(type="text", text="I'll search for AgentScope on Google."),
ToolUseBlock(
type="tool_use",
id="642n298gjna",
name="google_search",
input={"query": "AgentScope?"},
),
],
)
print(response)
ChatResponse(content=[{'type': 'thinking', 'thinking': 'I should search for AgentScope on Google.'}, {'type': 'text', 'text': "I'll search for AgentScope on Google."}, {'type': 'tool_use', 'id': '642n298gjna', 'name': 'google_search', 'input': {'query': 'AgentScope?'}}], id='2025-08-15 09:50:15.081_378aab', created_at='2025-08-15 09:50:15.081', type='chat', usage=None)
Taking DashScopeChatModel
as an example, we can use it to create a chat model instance and call it with messages and tools:
async def example_model_call() -> None:
"""An example of using the DashScopeChatModel."""
model = DashScopeChatModel(
model_name="qwen-max",
api_key=os.environ["DASHSCOPE_API_KEY"],
stream=False,
)
res = await model(
messages=[
{"role": "user", "content": "Hi!"},
],
)
# You can directly create a ``Msg`` object with the response content
msg_res = Msg("Friday", res.content, "assistant")
print("The response:", res)
print("The response as Msg:", msg_res)
asyncio.run(example_model_call())
The response: ChatResponse(content=[{'type': 'text', 'text': 'Hello! How can I assist you today?'}], id='2025-08-15 09:50:16.402_8fe09b', created_at='2025-08-15 09:50:16.402', type='chat', usage=ChatUsage(input_tokens=10, output_tokens=9, time=1.320003, type='chat'))
The response as Msg: Msg(id='nsQ5C4rsaqTNB3LN37ni6T', name='Friday', content=[{'type': 'text', 'text': 'Hello! How can I assist you today?'}], role='assistant', metadata=None, timestamp='2025-08-15 09:50:16.402', invocation_id='None')
Streaming¶
To enable streaming model, set the stream
parameter in the model constructor to True
.
When streaming is enabled, the __call__
method will return an async generator that yields ChatResponse
instances as they are generated by the model.
Note
The streaming mode in AgentScope is designed to be cumulative, meaning the content in each chunk contains all the previous content plus the newly generated content.
async def example_streaming() -> None:
"""An example of using the streaming model."""
model = DashScopeChatModel(
model_name="qwen-max",
api_key=os.environ["DASHSCOPE_API_KEY"],
stream=True,
)
generator = await model(
messages=[
{
"role": "user",
"content": "Count from 1 to 20, and just report the number without any other information.",
},
],
)
print("The type of the response:", type(generator))
i = 0
async for chunk in generator:
print(f"Chunk {i}")
print(f"\ttype: {type(chunk.content)}")
print(f"\t{chunk}\n")
i += 1
asyncio.run(example_streaming())
The type of the response: <class 'async_generator'>
Chunk 0
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1'}], id='2025-08-15 09:50:17.497_2ce567', created_at='2025-08-15 09:50:17.497', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=1, time=1.093135, type='chat'))
Chunk 1
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n'}], id='2025-08-15 09:50:17.702_91ad83', created_at='2025-08-15 09:50:17.703', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=4, time=1.299055, type='chat'))
Chunk 2
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4'}], id='2025-08-15 09:50:17.784_010803', created_at='2025-08-15 09:50:17.784', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=7, time=1.380938, type='chat'))
Chunk 3
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n'}], id='2025-08-15 09:50:17.861_ee03f0', created_at='2025-08-15 09:50:17.861', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=10, time=1.45767, type='chat'))
Chunk 4
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n'}], id='2025-08-15 09:50:18.028_f8f032', created_at='2025-08-15 09:50:18.028', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=16, time=1.624955, type='chat'))
Chunk 5
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n1'}], id='2025-08-15 09:50:18.161_8a8483', created_at='2025-08-15 09:50:18.161', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=22, time=1.757551, type='chat'))
Chunk 6
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n1'}], id='2025-08-15 09:50:18.649_d440fc', created_at='2025-08-15 09:50:18.649', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=28, time=2.245222, type='chat'))
Chunk 7
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n1'}], id='2025-08-15 09:50:18.851_33e3d9', created_at='2025-08-15 09:50:18.851', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=34, time=2.447298, type='chat'))
Chunk 8
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n1'}], id='2025-08-15 09:50:18.977_b64e8b', created_at='2025-08-15 09:50:18.977', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=40, time=2.573348, type='chat'))
Chunk 9
type: <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\n1'}], id='2025-08-15 09:50:19.132_194e42', created_at='2025-08-15 09:50:19.132', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=46, time=2.728453, type='chat'))
Chunk 10
type: <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-08-15 09:50:19.460_1b8bd3', created_at='2025-08-15 09:50:19.460', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=50, time=3.056993, type='chat'))
Chunk 11
type: <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-08-15 09:50:19.479_60ce7a', created_at='2025-08-15 09:50:19.479', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=50, time=3.07581, type='chat'))
Reasoning¶
AgentScope supports reasoning models by providing the ThinkingBlock
.
async def example_reasoning() -> None:
"""An example of using the reasoning model."""
model = DashScopeChatModel(
model_name="qwen-turbo",
api_key=os.environ["DASHSCOPE_API_KEY"],
enable_thinking=True,
)
res = await model(
messages=[
{"role": "user", "content": "Who am I?"},
],
)
last_chunk = None
async for chunk in res:
last_chunk = chunk
print("The final response:")
print(last_chunk)
asyncio.run(example_reasoning())
The final response:
ChatResponse(content=[{'type': 'thinking', 'thinking': 'Okay, the user asked "Who am I?" So I need to figure out how to respond. First, I should consider that the user might be asking about their identity in a general sense. But since I\'m an AI, I don\'t have personal information about them. I should make it clear that I can\'t know their personal details. However, maybe they\'re looking for a philosophical perspective or a way to reflect on their own identity. I should offer to help them explore that.\n\nI need to make sure the response is helpful and not just a simple "I don\'t know." Maybe ask them to provide more context or explain what they mean by "who am I." That way, I can give a more tailored response. Also, I should keep the tone friendly and open to encourage them to share more if they want. Let me structure the response to first acknowledge their question, explain my limitations, and then invite them to elaborate.'}, {'type': 'text', 'text': 'The question "Who am I?" is profound and deeply personal. As an AI, I don’t have access to your unique experiences, thoughts, or identity. However, I can help you explore this question together! \n\nIf you’re reflecting on your identity, values, goals, or purpose, feel free to share more about what’s on your mind. I can offer perspectives, ask guiding questions, or help you brainstorm. \n\nWhat does "who you are" mean to you? Are you seeking clarity, self-discovery, or something else? 😊'}], id='2025-08-15 09:50:24.329_cf20ce', created_at='2025-08-15 09:50:24.329', type='chat', usage=ChatUsage(input_tokens=12, output_tokens=305, time=4.846393, type='chat'))
Tools API¶
Different model providers differ in their tools APIs, e.g. the tools JSON schema, the tool call/response format. To provide a unified interface, AgentScope solves the problem by:
Providing unified tool call block ToolUseBlock and tool response block ToolResultBlock, respectively.
Providing a unified tools interface in the
__call__
method of the model classes, that accepts a list of tools JSON schemas as follows:
json_schemas = [
{
"type": "function",
"function": {
"name": "google_search",
"description": "Search for a query on Google.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query.",
},
},
"required": ["query"],
},
},
},
]
Further Reading¶
Total running time of the script: (0 minutes 9.251 seconds)