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.
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 asyncioimport jsonimport osfrom agentscope.message import TextBlock, ToolUseBlock, ThinkingBlock, Msgfrom agentscope.model import ChatResponse, DashScopeChatModelresponse = 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-09-15 07:46:09.704_79716b', created_at='2025-09-15 07:46:09.704', 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 contentmsg_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-09-15 07:46:11.300_d26f86', created_at='2025-09-15 07:46:11.300', type='chat', usage=ChatUsage(input_tokens=10, output_tokens=9, time=1.595077, type='chat'), metadata=None)The response as Msg: Msg(id='YHAkBDMtSViPxqAjDSGanv', name='Friday', content=[{'type': 'text', 'text': 'Hello! How can I assist you today?'}], role='assistant', metadata=None, timestamp='2025-09-15 07:46:11.300', 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 = 0async for chunk in generator:print(f"Chunk {i}")print(f"\ttype: {type(chunk.content)}")print(f"\t{chunk}\n")i += 1asyncio.run(example_streaming())
The type of the response: <class 'async_generator'>Chunk 0type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1'}], id='2025-09-15 07:46:12.412_fc731c', created_at='2025-09-15 07:46:12.412', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=1, time=1.110746, type='chat'), metadata=None)Chunk 1type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n'}], id='2025-09-15 07:46:12.585_6771ae', created_at='2025-09-15 07:46:12.585', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=2, time=1.283635, type='chat'), metadata=None)Chunk 2type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2'}], id='2025-09-15 07:46:12.593_16f3c7', created_at='2025-09-15 07:46:12.593', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=3, time=1.291467, type='chat'), metadata=None)Chunk 3type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n'}], id='2025-09-15 07:46:12.639_74388e', created_at='2025-09-15 07:46:12.639', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=4, time=1.337463, type='chat'), metadata=None)Chunk 4type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n'}], id='2025-09-15 07:46:12.939_7c87b1', created_at='2025-09-15 07:46:12.939', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=8, time=1.637562, type='chat'), metadata=None)Chunk 5type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n'}], id='2025-09-15 07:46:13.123_a4c69d', created_at='2025-09-15 07:46:13.123', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=12, time=1.821939, type='chat'), metadata=None)Chunk 6type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n'}], id='2025-09-15 07:46:13.309_00cd8d', created_at='2025-09-15 07:46:13.309', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=16, time=2.007843, type='chat'), metadata=None)Chunk 7type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10'}], id='2025-09-15 07:46:14.016_3d0ed8', created_at='2025-09-15 07:46:14.016', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=20, time=2.714669, type='chat'), metadata=None)Chunk 8type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n'}], id='2025-09-15 07:46:14.166_9932d5', created_at='2025-09-15 07:46:14.166', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=24, time=2.864712, type='chat'), metadata=None)Chunk 9type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n1'}], id='2025-09-15 07:46:14.384_c36588', created_at='2025-09-15 07:46:14.384', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=28, time=3.082521, type='chat'), metadata=None)Chunk 10type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14'}], id='2025-09-15 07:46:14.609_4f2344', created_at='2025-09-15 07:46:14.609', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=32, time=3.307743, type='chat'), metadata=None)Chunk 11type: <class 'list'>ChatResponse(content=[{'type': 'text', 'text': '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n'}], id='2025-09-15 07:46:14.912_a54a1b', created_at='2025-09-15 07:46:14.912', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=36, time=3.611261, type='chat'), metadata=None)Chunk 12type: <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-09-15 07:46:15.089_1add34', created_at='2025-09-15 07:46:15.089', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=40, time=3.787598, type='chat'), metadata=None)Chunk 13type: <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-09-15 07:46:15.287_f5588b', created_at='2025-09-15 07:46:15.287', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=44, time=3.986105, type='chat'), metadata=None)Chunk 14type: <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\n'}], id='2025-09-15 07:46:15.487_395be5', created_at='2025-09-15 07:46:15.487', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=48, time=4.185755, type='chat'), metadata=None)Chunk 15type: <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-09-15 07:46:15.639_4dfa1f', created_at='2025-09-15 07:46:15.639', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=50, time=4.338068, type='chat'), metadata=None)Chunk 16type: <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-09-15 07:46:15.659_36049b', created_at='2025-09-15 07:46:15.659', type='chat', usage=ChatUsage(input_tokens=27, output_tokens=50, time=4.35748, 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 = Noneasync for chunk in res:last_chunk = chunkprint("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?" which is a deep philosophical question. I need to approach this carefully. First, I should acknowledge that it\'s a complex question with no single answer. Different perspectives like philosophy, psychology, and spirituality might offer various insights.\n\nI should mention that from a philosophical standpoint, it\'s about self-awareness and consciousness. Maybe reference thinkers like Descartes or Buddhist concepts. Then, from a psychological angle, it\'s about identity shaped by experiences and relationships. Also, consider the spiritual aspect where some believe in an eternal soul or higher self.\n\nI need to make sure the response is balanced and doesn\'t favor one perspective over others. Encourage the user to reflect on their own experiences and values. Avoid making assumptions about their beliefs. Keep the tone open and supportive, inviting them to explore their own answers.'}, {'type': 'text', 'text': 'The question "Who am I?" is one of the most profound and enduring inquiries in human history, touching on philosophy, psychology, spirituality, and identity. Here are some perspectives to consider:\n\n### 1. **Philosophical Perspective** \n - **Self as Consciousness**: Thinkers like Descartes ("I think, therefore I am") suggest that the essence of "you" lies in your capacity for self-awareness and thought. \n - **Existentialism**: Philosophers like Sartre argue that you are defined by your choices and actions, creating your own meaning in an otherwise indifferent universe. \n - **Eastern Thought**: In Buddhism, the idea of "no-self" (anatta) challenges the notion of a fixed identity, suggesting that the "self" is a fluid collection of impermanent experiences and attachments.\n\n### 2. **Psychological Perspective** \n - **Identity Formation**: Your sense of self is shaped by experiences, relationships, culture, and personal growth. Psychologists like Erik Erikson emphasized stages of development where identity is continually redefined. \n - **The "I" vs. the "Me"**: William James distinguished between the "I" (the conscious observer) and the "Me" (the collection of memories, roles, and traits you identify with). \n\n### 3. **Spiritual/Existential Perspective** \n - **Soul or Higher Self**: Many traditions (e.g., Christianity, Hinduism, New Age spirituality) posit that you have an eternal essence or soul beyond the physical body. \n - **Interconnectedness**: Some philosophies (e.g., Advaita Vedanta, quantum consciousness theories) suggest that the "self" is not isolated but part of a larger, unified reality. \n\n### 4. **Scientific Perspective** \n - **Neuroscience**: The brain\'s neural activity and patterns of thought may underpin the sense of self, but the exact mechanisms remain mysterious. \n - **Consciousness Studies**: Researchers explore whether consciousness arises from physical processes or if it’s a fundamental aspect of reality. \n\n### 5. **Personal Reflection** \n - **You are a story**: Your identity is shaped by your memories, values, goals, and relationships. It’s dynamic, evolving with time and experience. \n - **The question itself**: Sometimes, the act of asking "Who am I?" is more important than the answer. It invites introspection and growth. \n\n### Final Thought: \nThere is no single answer, and the journey to understand yourself is ongoing. You might find clarity by exploring what matters most to you, how you relate to others, and what gives your life meaning. The search itself is part of the answer. 🌱 \n\nWhat resonates with you? I’d be curious to hear your thoughts!'}], id='2025-09-15 07:46:27.593_9961b2', created_at='2025-09-15 07:46:27.593', type='chat', usage=ChatUsage(input_tokens=12, output_tokens=756, time=11.930203, 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 17.894 seconds)
Download Jupyter notebook: task_model.ipynb
Download Python source code: task_model.py