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 |
|
✅ |
✅ |
✅ |
✅ |
Note
When using vLLM, you need to configure the appropriate tool calling parameters for different models during deployment, such as --enable-auto-tool-choice, --tool-call-parser, etc. For more details, refer to the official vLLM documentation.
Note
For OpenAI-compatible models (e.g. vLLM, Deepseek), developers can use the OpenAIChatModel class, and specify the API endpoint by the client_kwargs parameter: client_kwargs={"base_url": "http://your-api-endpoint"}. For example:
OpenAIChatModel(client_kwargs={"base_url": "http://localhost:8000/v1"})
Note
Model behavior parameters (such as temperature, maximum length, etc.) can be preset in the constructor function via the generate_kwargs parameter. For example:
OpenAIChatModel(generate_kwargs={"temperature": 0.3, "max_tokens": 1000})
To provide unified model interfaces, the above model classes has the following common methods:
The first three arguments of the
__call__method aremessages,toolsandtool_choice, representing the input messages, JSON schema of tool functions, and tool selection mode, respectively.The return type are either a
ChatResponseinstance or an async generator ofChatResponsein 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='2026-01-30 10:59:57.531_628848', created_at='2026-01-30 10:59:57.531', type='chat', usage=None, metadata=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='2026-01-30 10:59:59.179_2c5962', created_at='2026-01-30 10:59:59.179', type='chat', usage=ChatUsage(input_tokens=10, output_tokens=9, time=1.647339, type='chat'), metadata=None)
The response as Msg: Msg(id='RjkanY7vCRFhqaPoSVtKTQ', name='Friday', content=[{'type': 'text', 'text': 'Hello! How can I assist you today?'}], role='assistant', metadata=None, timestamp='2026-01-30 10:59:59.179', 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='2026-01-30 11:00:00.269_56c491', created_at='2026-01-30 11:00:00.269', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=1, time=1.088358, type='chat'), metadata=None)
Chunk 1
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n'}], id='2026-01-30 11:00:00.319_ec7e91', created_at='2026-01-30 11:00:00.319', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=4, time=1.138217, type='chat'), metadata=None)
Chunk 2
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4'}], id='2026-01-30 11:00:00.366_0921e3', created_at='2026-01-30 11:00:00.366', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=7, time=1.18582, type='chat'), metadata=None)
Chunk 3
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n'}], id='2026-01-30 11:00:00.416_c87fc6', created_at='2026-01-30 11:00:00.416', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=10, time=1.235582, type='chat'), metadata=None)
Chunk 4
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n'}], id='2026-01-30 11:00:00.534_c4ca13', created_at='2026-01-30 11:00:00.534', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=16, time=1.353275, type='chat'), metadata=None)
Chunk 5
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n1'}], id='2026-01-30 11:00:00.616_48ec2b', created_at='2026-01-30 11:00:00.616', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=22, time=1.435712, type='chat'), metadata=None)
Chunk 6
type: <class 'list'>
ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n1'}], id='2026-01-30 11:00:00.717_a6f8a7', created_at='2026-01-30 11:00:00.717', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=28, time=1.536114, type='chat'), metadata=None)
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='2026-01-30 11:00:01.013_d80b3f', created_at='2026-01-30 11:00:01.013', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=34, time=1.83237, type='chat'), metadata=None)
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='2026-01-30 11:00:01.098_c1ec7e', created_at='2026-01-30 11:00:01.098', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=40, time=1.917113, type='chat'), metadata=None)
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='2026-01-30 11:00:01.285_8a0596', created_at='2026-01-30 11:00:01.286', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=46, time=2.105035, type='chat'), metadata=None)
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='2026-01-30 11:00:01.415_4b3f49', created_at='2026-01-30 11:00:01.415', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=50, time=2.234177, type='chat'), metadata=None)
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='2026-01-30 11:00:01.433_24becb', created_at='2026-01-30 11:00:01.433', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=50, time=2.252509, type='chat'), metadata=None)
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?" I need to figure out how to respond. First, I should consider the context. The user might be curious about their identity, but since I don\'t have personal information about them, I can\'t provide a direct answer. Maybe they\'re looking for a philosophical perspective or a way to explore self-discovery.\n\nI should start by acknowledging their question and explaining that I can\'t know their specific identity. Then, offer different angles. For example, from a philosophical standpoint, identity can be about consciousness and experiences. From a psychological view, it\'s shaped by thoughts, memories, and interactions. Also, maybe mention that it\'s a personal journey, and they might need to reflect on their own experiences.\n\nI should keep the tone friendly and open-ended, encouraging them to think about what defines them. Avoid making assumptions and stay supportive. Make sure the response is clear and not too technical. Check if there\'s anything else they might need, but since the question is straightforward, focus on providing a thoughtful, empathetic answer.\n'}, {'type': 'text', 'text': 'The question "Who am I?" is one of the deepest and most profound inquiries humans can make. While I can’t know your specific identity (as I don’t have access to personal information about you), I can offer some reflections on what "self" might mean:\n\n1. **Consciousness and Awareness**: You are the awareness that perceives thoughts, emotions, and the world around you. It’s the sense of "I" that experiences life, even if the nature of that "I" remains mysterious.\n\n2. **A Collection of Experiences**: Your identity is shaped by your memories, relationships, choices, and the stories you tell yourself about who you are. It’s dynamic, evolving over time.\n\n3. **A Question, Not a Fixed Answer**: The search for "who you are" might be more important than any single answer. Philosophers, scientists, and spiritual traditions have long debated this, suggesting that identity is complex, layered, and perhaps even fluid.\n\n4. **Connection to Others**: You are also defined by your relationships, your impact on the world, and the ways you contribute to the lives of others. Identity isn’t just internal—it’s shaped by interaction.\n\nIf you’re exploring this question deeply, it might help to reflect on what matters most to you, what gives your life meaning, or how you see yourself in the world. Let me know if you’d like to explore this further! 🌱'}], id='2026-01-30 11:00:08.982_50d2bb', created_at='2026-01-30 11:00:08.982', type='chat', usage=ChatUsage(input_tokens=12, output_tokens=510, time=7.544296, type='chat'), metadata=None)
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 11.455 seconds)