# PyAgent **Repository Path**: ulyan/py-agent ## Basic Information - **Project Name**: PyAgent - **Description**: 一个简单易用的Python库,可以轻松地对接LLM,并可以将Python函数对象直接对接LLM,成为LLM的臂膀,实现快速搭建有特定功能的Agent。 - **Primary Language**: Python - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-05-14 - **Last Updated**: 2026-05-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # PyAgent 一个渐进式披露的 Python LLM API 库。从一行代码开始,到完全控制 —— 全部使用地道的 Python 表达。 ```python from pyagent import PyAgent agent = PyAgent(api_type="openai") with agent.session() as s: print(s.chat("你好!")) ``` ## 安装 ```bash pip install pyagent ``` 需要 Python 3.10+。唯一外部依赖是 [httpx](https://www.pypi.org/project/httpx/)。 ## 快速开始 ### 第一层 —— 聊天 ```python from pyagent import PyAgent # 零配置:从环境变量读取 OPENAI_API_KEY / ANTHROPIC_API_KEY agent = PyAgent(api_type="anthropic") with agent.session(system="你是专业翻译。") as s: result = s.chat("翻译成英文:你好世界") print(result) ``` ### 第二层 —— 工具 ```python from pyagent import PyAgent, tool @tool def get_weather(city: str, unit: str = "celsius") -> str: """查询城市天气。""" # 实际代码中可调用天气 API return f"{city}: 22°{unit[0].upper()}" agent = PyAgent(api_type="openai") with agent.session(tools=[get_weather]) as s: reply = s.chat("北京天气怎么样?") print(reply) ``` `@tool` 装饰器自动从函数签名和 docstring 生成 JSON Schema —— 无需手写。 ### 第三层 —— 完全控制 ```python from pyagent import PyAgent, Message agent = PyAgent(api_type="anthropic") # 手动编排消息 resp = agent.raw( [Message.system("你是乐于助人的助手。"), Message.user("你好!")], max_tokens=200, temperature=0.7, ) print(resp.content) # str print(resp.usage) # Usage(prompt_tokens=..., completion_tokens=...) ``` ## Session 与 Role API ```python agent = PyAgent() with agent.session() as s: # 以用户身份聊天(默认) s.chat("你好") # 以助手身份聊天 s.chat("我很好!", role="assistant") # 流式输出 for token in s.chat("写一首诗", stream=True): print(token, end="") # 插入但不发送 —— 逐步构建上下文 s.user.insert("我想学 Python。") s.assistant.insert("好选择!你想从哪里开始?") reply = s.chat() # 不追加新消息,直接发送已有历史 # 角色对象 s.system.insert("你是一位 Python 专家。") s.role("tool").insert('{"result": 42}', tool_call_id="call_abc") # 历史管理 print(s.history) # 只读消息列表 s.clear() # 重置对话 ``` ## 支持的后端 | `api_type` | 后端 | 默认模型 | |------------|------|----------| | `"openai"` | OpenAI Chat Completions | `gpt-4o` | | `"anthropic"` | Anthropic Messages | `claude-sonnet-4-6` | 兼容 OpenAI 接口的服务(Azure、本地 LLM 等)可通过 `api_type="openai"` + 自定义 `base_url` 使用。 ## 配置 ```python agent = PyAgent( api_type="openai", api_key="sk-...", # 或 OPENAI_API_KEY 环境变量 base_url="https://api.openai.com/v1", # 或 OPENAI_BASE_URL 环境变量 model="gpt-4o", # 或 OPENAI_MODEL 环境变量 system="你是乐于助人的助手。", # 所有 session 的默认系统提示 timeout=30.0, max_retries=3, ) ``` 各后端环境变量: | 变量 | OpenAI | Anthropic | |------|--------|-----------| | API key | `OPENAI_API_KEY` | `ANTHROPIC_API_KEY` | | Base URL | `OPENAI_BASE_URL` | `ANTHROPIC_BASE_URL` | | Model | `OPENAI_MODEL` | `ANTHROPIC_MODEL` | ## 错误处理 ```python from pyagent import ( PyAgent, AuthenticationError, RateLimitError, APIError, ConnectionError, TimeoutError, ) agent = PyAgent() try: with agent.session() as s: s.chat("你好") except AuthenticationError: print("请检查 API key。") except RateLimitError: print("请求过于频繁,请稍后。") except (ConnectionError, TimeoutError): print("网络问题。") except APIError as e: print(f"API 返回了 {e.status_code}") ``` 所有异常均继承自 `LLMError`。 ## 流式输出 ```python with agent.session() as s: for token in s.chat("给我讲个故事", stream=True): print(token, end="", flush=True) # token 会被自动累积并追加到历史中 ``` ## 许可证 Apache 2.0 —— 详见 [LICENSE](LICENSE)。