ZipAgent is a modern Python AI Agent framework focused on providing a clean, efficient, and easily extensible development experience. Designed with "lightweight" in mind, the framework implements a full-featured system of intelligences, including an agent engine, tooling system, and dialog management, in about 700 lines of core code. This allows developers to get started and start building their own AI assistants in as little as 5 minutes. ZipAgent is based on Python version 3.10+, supports asynchronous programming, and offers modern features including streaming output, automatic context management, and native support for the Model Context Protocol (MCP). The project has over 120 test cases to ensure high quality and stability of the code, making it suitable for building chatbots, intelligent assistants, workflow automation, and many other application scenarios.
Function List
- Simple API: With a minimalist design philosophy, developers can build a basic AI Agent with just a few lines of code.
- tooling system: Provides powerful
@function_tool
Decorators that make it easy to extend the capabilities of ordinary Python functions by converting them into tools that can be called by an AI Agent. - streaming output: Full support for streaming response processing enables a real-time interactive experience similar to the effect of a typewriter, enhancing the user experience.
- context management (computing): The ability to automatically manage and maintain the history and status of multiple rounds of conversations, eliminating the need for developers to manually handle complex conversation logic.
- MCP Integration: Native support for Model Context Protocol allows for easy integration with external tools (e.g., Goldmap, etc.).
- modernized structure: The project is based on Python 3.10+, which fully embraces asynchronous programming and guarantees high performance and concurrent processing.
- High quality code: The project contains over 120 test cases with code coverage of 78%, ensuring the stability and reliability of the framework.
Using Help
ZipAgent is designed to get developers up and running quickly, and the installation and usage process is described in detail below.
1. Environment preparation and installation
Before you begin, make sure you have Python 3.10 or later installed in your development environment.
Then, by pip
command will complete the installation of ZipAgent:
pip install zipagent
2. 5 minutes to get started
Once installed, you can create a conversational AI assistant in just three steps.
Step 1: Define the tool
Tools are capabilities that can be used by the Agent. zipAgent uses a simple decorator @function_tool
You can turn any Python function into a tool.
For example, let's define a tool to compute a mathematical expression:
from zipagent import function_tool
@function_tool
def calculate(expression: str) -> str:
"""这个工具用于计算一个数学表达式的值。"""
# 注意:eval函数有安全风险,这里仅为演示目的
return str(eval(expression))
The documentation string (docstring) in the function is very important, and Agent will use this description to determine when the tool should be used.
Step 2: Create Agent
Next, create an Agent instance and tell it who it is, its task instructions, and the tools it can use.
from zipagent import Agent
agent = Agent(
name="MathAssistant",
instructions="你是一个非常厉害的数学助手,你需要使用工具来回答用户的数学问题。",
tools=[calculate] # 将刚才定义的工具列表传给Agent
)
Step 3: Run the Agent and start the dialog
Finally, use the Runner
to execute the Agent and get the results.
from zipagent import Runner
# 向Agent提问
result = Runner.run(agent, "请帮我计算一下 (100 + 200) * 3 等于多少?")
# 打印Agent的回答
print(result.content)
After running it, you will see the output:
(100 + 200) * 3 的计算结果是900
At this point, a simple AI Agent is built.
3. Operation of core functions
A. Realization of streaming output (typewriter effect)
To enhance the interactive experience, you can use the run_stream
method to get a real-time streaming response.
from zipagent import Runner, StreamEventType
# 使用run_stream方法
stream = Runner.run_stream(agent, "简单解释一下什么是人工智能?")
# 遍历事件流
for event in stream:
if event.type == StreamEventType.ANSWER_DELTA:
# ANSWER_DELTA事件表示模型正在生成回答内容
print(event.content, end="", flush=True)
elif event.type == StreamEventType.TOOL_CALL:
# TOOL_CALL事件表示Agent正在调用工具
print(f"\n🔧 正在调用工具: {event.tool_name}...")
This code prints out the model's responses verbatim and prompts the Agent when it calls the tool.
B. Managing the context of multiple rounds of dialogues
In practice, users usually have multiple rounds of conversations with an Agent, and the ZipAgent is designed to do this through the Context
The object automatically manages the dialog history.
from zipagent import Context, Runner
# 创建一个上下文对象
context = Context()
# 第一轮对话
Runner.run(agent, "记住,我的名字叫小明。", context=context)
# 第二轮对话
result = Runner.run(agent, "现在,请问我叫什么名字?", context=context)
print(result.content) # 输出: "你叫小明"
# 你还可以查看对话的统计信息
print(f"当前对话轮数: {context.turn_count}")
print(f"累计使用的Token数量: {context.usage}")
You just need to add the same context
object passed in run
method, the Agent will be able to remember the content of the previous conversation.
C. Integration of external tools (MCP)
ZipAgent supports the use of the MCP protocol to connect to and use externally published tool services, which makes tool extensions very flexible.
import asyncio
from zipagent import MCPTool, Agent, Runner
async def main():
# 假设有一个高德地图的MCP服务在运行
# 这里使用npx启动一个示例服务
amap_tools = await MCPTool.connect(
command="npx",
args=["-y", "@amap/amap-maps-mcp-server"],
env={"AMAP_MAPS_API_KEY": "填写你的高德API密钥"}
)
# 将MCP工具和本地工具混合使用
map_agent = Agent(
name="MapAssistant",
instructions="你是一个地图和天气查询助手。",
tools=[amap_tools] # MCP工具的接口与本地工具完全一样
)
result = Runner.run(map_agent, "查询一下中国北京市今天的天气怎么样?")
print(result.content)
# 运行异步函数
asyncio.run(main())```
### **4. 高级功能**
**A. 自定义模型配置**
默认情况下,ZipAgent 使用 OpenAI 的模型。你也可以轻松更换成其他模型或自定义配置。
```python
from zipagent import OpenAIModel
# 自定义模型,例如使用gpt-4,并指定API地址
custom_model = OpenAIModel(
model="gpt-4",
api_key="你的API Key",
base_url="你的代理API地址或官方地址"
)
# 在创建Agent时传入自定义模型
custom_agent = Agent(
name="CustomAgent",
instructions="...",
tools=[],
model=custom_model
)
B. Exception handling
When interacting with an Agent, there may be problems such as the tool failing to execute or the dialog getting stuck in a dead loop, etc. ZipAgent provides explicit exception types to handle these situations.
from zipagent import ToolExecutionError, MaxTurnsError
try:
# 设定最大对话轮数为3,防止无限循环
result = Runner.run(agent, "计算 10 / 0", max_turns=3)
except ToolExecutionError as e:
# 捕获工具执行失败的异常
print(f"工具 '{e.details['tool_name']}' 执行失败: {e}")
except MaxTurnsError as e:
# 捕获超出最大轮次的异常
print(f"对话已达到最大轮次 {e.details['max_turns']},已自动终止。")
application scenario
- Intelligent Customer Service
It is possible to build an intelligent customer service robot that can automatically answer users' frequently asked questions, check the status of orders, and handle after-sale applications. By integrating the company's internal API as a tool, the Agent can accomplish more complex business operations. - Code Development Assistant
Provide developers with a coding partner that can help generate code snippets, review code quality, fix common bugs, or automatically generate test cases based on requirements documentation. - Automated data analysis
Scripts for data querying, processing and visualization are encapsulated into tools that allow the Agent to automate data analysis tasks and generate analysis reports based on the user's natural language commands. - Workflow automation
Design an Agent capable of scheduling multiple tools and services to automate complex multi-step tasks, such as extracting attachments from an email, reading the content, analyzing it, and finally summarizing the results in a specified online document. - Enterprise Knowledge Base Q&A
Connect to your organization's internal knowledge base or database to create an intelligent Q&A system. Employees can ask questions in natural language, and the Agent is responsible for retrieving relevant information and providing accurate answers.
QA
- What is ZipAgent?
ZipAgent is a lightweight AI Agent framework written in Python. It is characterized by simple code, easy to extend, can help developers in a few minutes to quickly build a dedicated AI assistant with tool invocation, conversation management and other functions. - Do I have to pay to use ZipAgent?
The ZipAgent framework itself is open source and free under the MIT license, so you are free to use, modify, and distribute it. Note, however, that the Agent internally requires calls to large language models (such as OpenAI's GPT family), and using these modeling services usually requires a corresponding API call fee. - What kind of technical background do I need to use it?
You need to have a basic knowledge of Python programming. Understanding the concepts of functions, classes and decorators will be very helpful. If you want to do more advanced development, such as integrating external tools, then an understanding of asynchronous programming (async/await) would be better. - What big language models does it support?
ZipAgent has built-in support for OpenAI models. At the same time, its model layer is abstract, and you can access any other large language model by customizing the model class, such as Google Gemini, Anthropic Claude etc.