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

OpenAIChatModel

vLLM, DeepSeek

✅

✅

✅

✅

DashScope

DashScopeChatModel

✅

✅

✅

✅

Anthropic

AnthropicChatModel

✅

✅

✅

✅

Gemini

GeminiChatModel

✅

✅

✅

✅

Ollama

OllamaChatModel

✅

✅

✅

✅

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 are messages , tools and tool_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 of ChatResponse 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.

  1. import asyncio
  2. import json
  3. import os
  4. from agentscope.message import TextBlock, ToolUseBlock, ThinkingBlock, Msg
  5. from agentscope.model import ChatResponse, DashScopeChatModel
  6. response = ChatResponse(
  7. content=[
  8. ThinkingBlock(
  9. type="thinking",
  10. thinking="I should search for AgentScope on Google.",
  11. ),
  12. TextBlock(type="text", text="I'll search for AgentScope on Google."),
  13. ToolUseBlock(
  14. type="tool_use",
  15. id="642n298gjna",
  16. name="google_search",
  17. input={"query": "AgentScope?"},
  18. ),
  19. ],
  20. )
  21. print(response)
  1. 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:

  1. async def example_model_call() -> None:
  2. """An example of using the DashScopeChatModel."""
  3. model = DashScopeChatModel(
  4. model_name="qwen-max",
  5. api_key=os.environ["DASHSCOPE_API_KEY"],
  6. stream=False,
  7. )
  8. res = await model(
  9. messages=[
  10. {"role": "user", "content": "Hi!"},
  11. ],
  12. )
  13. # You can directly create a ``Msg`` object with the response content
  14. msg_res = Msg("Friday", res.content, "assistant")
  15. print("The response:", res)
  16. print("The response as Msg:", msg_res)
  17. asyncio.run(example_model_call())
  1. 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)
  2. 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.

  1. async def example_streaming() -> None:
  2. """An example of using the streaming model."""
  3. model = DashScopeChatModel(
  4. model_name="qwen-max",
  5. api_key=os.environ["DASHSCOPE_API_KEY"],
  6. stream=True,
  7. )
  8. generator = await model(
  9. messages=[
  10. {
  11. "role": "user",
  12. "content": "Count from 1 to 20, and just report the number without any other information.",
  13. },
  14. ],
  15. )
  16. print("The type of the response:", type(generator))
  17. i = 0
  18. async for chunk in generator:
  19. print(f"Chunk {i}")
  20. print(f"\ttype: {type(chunk.content)}")
  21. print(f"\t{chunk}\n")
  22. i += 1
  23. asyncio.run(example_streaming())
  1. The type of the response: <class 'async_generator'>
  2. Chunk 0
  3. type: <class 'list'>
  4. 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)
  5. Chunk 1
  6. type: <class 'list'>
  7. 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)
  8. Chunk 2
  9. type: <class 'list'>
  10. 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)
  11. Chunk 3
  12. type: <class 'list'>
  13. 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)
  14. Chunk 4
  15. type: <class 'list'>
  16. 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)
  17. Chunk 5
  18. type: <class 'list'>
  19. 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)
  20. Chunk 6
  21. type: <class 'list'>
  22. 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)
  23. Chunk 7
  24. type: <class 'list'>
  25. 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)
  26. Chunk 8
  27. type: <class 'list'>
  28. 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)
  29. Chunk 9
  30. type: <class 'list'>
  31. 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)
  32. Chunk 10
  33. type: <class 'list'>
  34. 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)
  35. Chunk 11
  36. type: <class 'list'>
  37. 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)
  38. Chunk 12
  39. type: <class 'list'>
  40. 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)
  41. Chunk 13
  42. type: <class 'list'>
  43. 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)
  44. Chunk 14
  45. type: <class 'list'>
  46. 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)
  47. Chunk 15
  48. type: <class 'list'>
  49. 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)
  50. Chunk 16
  51. type: <class 'list'>
  52. 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.

  1. async def example_reasoning() -> None:
  2. """An example of using the reasoning model."""
  3. model = DashScopeChatModel(
  4. model_name="qwen-turbo",
  5. api_key=os.environ["DASHSCOPE_API_KEY"],
  6. enable_thinking=True,
  7. )
  8. res = await model(
  9. messages=[
  10. {"role": "user", "content": "Who am I?"},
  11. ],
  12. )
  13. last_chunk = None
  14. async for chunk in res:
  15. last_chunk = chunk
  16. print("The final response:")
  17. print(last_chunk)
  18. asyncio.run(example_reasoning())
  1. The final response:
  2. 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:

  1. json_schemas = [
  2. {
  3. "type": "function",
  4. "function": {
  5. "name": "google_search",
  6. "description": "Search for a query on Google.",
  7. "parameters": {
  8. "type": "object",
  9. "properties": {
  10. "query": {
  11. "type": "string",
  12. "description": "The search query.",
  13. },
  14. },
  15. "required": ["query"],
  16. },
  17. },
  18. },
  19. ]

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

Download zipped: task_model.zip

Gallery generated by Sphinx-Gallery