Overview
Qwen-Agent provides a flexible Agent base class that you can extend to create custom agents with specialized behaviors. All agents inherit from theAgent class and implement their own _run method to define their workflow.
Understanding the Agent Base Class
TheAgent class (qwen_agent/agent.py:31) provides the foundation for all agents:
Key Components
- function_list: List of tools the agent can use
- llm: Language model configuration or instance
- system_message: System prompt for the agent
- name: Agent identifier (required for multi-agent systems)
- description: Agent description (used by routers and orchestrators)
Creating a Basic Agent
from qwen_agent import Agent
from qwen_agent.llm.schema import Message
from typing import Iterator, List
class MyCustomAgent(Agent):
def _run(self, messages: List[Message], lang: str = 'en', **kwargs) -> Iterator[List[Message]]:
"""
The core workflow of your agent.
Args:
messages: Conversation history
lang: Language ('en' or 'zh')
**kwargs: Additional parameters
Yields:
List[Message]: Agent responses
"""
# Your custom logic here
return self._call_llm(messages)
Example: Creating a Specialized Agent
Here’s a complete example of a custom agent that adds domain-specific behavior:Using Built-in Agents
Qwen-Agent provides several pre-built agents you can use directly:Agent Methods Reference
Core Methods
run(messages, **kwargs)
Main method to run the agent (returns streaming response):
run_nonstream(messages, **kwargs)
Get complete response without streaming:
_call_llm(messages, functions=None, stream=True)
Call the LLM from within your agent (qwen_agent/agent.py:150):
_call_tool(tool_name, tool_args, **kwargs)
Execute a tool from within your agent (qwen_agent/agent.py:178):
Best Practices
Agent Design Tips
- Keep the
_runmethod focused on workflow logic - Use
system_messagefor agent personality and instructions - Set meaningful
nameanddescriptionfor multi-agent scenarios - Leverage
_call_llmand_call_toolfor common operations
Advanced: Agent with Custom Tool Handling
Next Steps
- Learn about Custom Tools to extend agent capabilities
- Explore Multi-Agent Systems for agent orchestration
- See RAG for knowledge-enhanced agents