内容
# 个人助理代理与 LangGraph
一个强大的对话式代理,具备检索增强生成、MCP 服务器、长期和短期记忆以及工具集成——由 LangGraph、LangChain、Redis、PostgreSQL 和 Pinecone 提供支持。
---
## 功能特点
- **对话聊天**
- 交互式命令行界面 (`app/run.py`)
- 通过 Python SDK 进行编程访问 (`langgraph_sdk`)
- **检索增强生成**
- 将 PDF、Markdown、HTML、CSV 和 DOCX 摄入 Pinecone
- `index_docs(name, path_or_url)` 和 `query_index(name, question, k)` 工具
- **MCP 服务器**
- 暴露 25+ 个 CoinMarketCap 端点
- **长期记忆**
- 用户命名的配置文件、项目和指令存储在 PostgreSQL 中
- **短期记忆**
- 最近对话的滚动摘要(10+ 次对话后修剪)
- **工具集成**
- **网络与知识**:`web_fetch`、`wiki_search`、`tavily_search`
- **文件处理**:`inspect_file`、`summarise_file`、`extract_tables`、`ocr_image`、`save_uploaded_file`
- **金融**:`get_stock_quote`、`get_stock_news`
- **健壮性**
- 暂时的 OpenAI 错误自动重试
- Docker Compose 中的 Redis 和 Postgres 健康检查
## 项目结构
```
personal_assistant/
├── app/
│ ├── config.py
│ ├── run.py # 命令行入口
│ ├── graph/
│ │ ├── assistant.py # StateGraph 定义
│ │ ├── state.py # ChatState 模式
│ │ └── memory/ # 总结,模式
│ ├── tools/ # 外部工具函数
│ ├── rag/ # RAG 加载器和索引器
│ ├── mcp/ # MCP 服务器逻辑
│ └── schemas/
├── requirements.txt
├── docker-compose.yml
├── langgraph.json
└── README.md
```
## 先决条件
- Python 3.11+
- Docker 和 Docker Compose(用于容器化部署)
- Redis 和 PostgreSQL(本地或通过 Docker)
- OpenAI、Pinecone、Tavily 和 CoinMarketCap API 密钥
## 入门指南
### 本地设置
1. 克隆仓库:
```bash
git clone https://github.com/amanzoni1/pa_agent && cd personal_assistant
```
2. 创建并激活虚拟环境:
```bash
python -m venv .venv
source .venv/bin/activate
```
3. 安装依赖项:
```bash
pip install -r requirements.txt
```
4. 在项目根目录创建 `.env` 文件:
```ini
OPENAI_API_KEY=your_openai_key
LANGSMITH_API_KEY=your_langsmith_key
REDIS_URI=redis://localhost:6379
POSTGRES_URI=postgresql://postgres:postgres@localhost:5432/personal_assistant?sslmode=disable
PINECONE_API_KEY=your_pinecone_key
TAVILY_API_KEY=your_tavily_key
COINMARKETCAP_API_KEY=your_cmc_key
```
5. 确保 Redis 和 Postgres 在本地运行。
## 命令行界面(CLI)
在终端中通过聊天交互:
```bash
python -m app.run --thread-id <optional-uuid> --user-id <optional-your_id>
```
命令:
- `/memory`:显示存储的长期记忆(配置文件、项目、指令)。
- `/mcp`:获取 MCP 服务器上可用的所有工具。
- `/exit` 或 Ctrl-D:退出。
## Docker Compose 部署
1. 构建 LangGraph 镜像:
```bash
langgraph build -t my-assistant
```
2. 通过 Docker Compose 启动:
```bash
docker compose up -d
```
3. 访问:
- API:`http://localhost:8123`
- Swagger 文档:`http://localhost:8123/docs`
### Python SDK 用法
安装 SDK:
```bash
pip install langgraph_sdk
```
示例:
```python
import asyncio
from langgraph_sdk import get_client
from langchain_core.messages import HumanMessage
async def main():
client = get_client(url="http://localhost:8123")
thread = await client.threads.create()
run = await client.runs.create(
thread["thread_id"],
"my-assistant",
input={"messages": [HumanMessage(content="你好!")]},
config={"configurable": {"user_id": "you", "thread_id": thread["thread_id"]}},
)
final = await client.runs.join(thread["thread_id"], run["run_id"])
msgs = final.get("messages", [])
ai = msgs[1]["content"] if len(msgs) > 1 else None
print("AI:", ai)
asyncio.run(main())
```