🧠 会话策略代理
一个推理驱动的人工智能代理系统,使用 感知→ 决定→ 行动 循环来解决复杂的任务。该代理利用多个MCP(模型上下文协议)服务器,通过语义搜索维护基于会话的内存,并使用基于LLM的规划来生成可执行的Python代码。
✨ 主要特点
- 🧠 智能存储系统:通过自动索引在历史对话中进行语义搜索
- 🔍 智能上下文感知:利用之前的对话提供上下文感知的答案
- 🌐 Web内容处理:使用自动内存索引抓取、提取和汇总网页
- 🛠️ 多工具集成:无缝集成数学、文档处理、网络搜索和内存工具
- 🔄 适应性规划:具有自动重试机制的保守和探索性规划模式
🚀 快速开始
# Install dependencies
pip install -r requirements.txt
# Set up environment variables
export OPENAI_API_KEY=your_api_key_here
# Run the agent
python agent.py📚 用法示例
示例1:来自历史记忆的直接回答
当你再次问同样的问题时,Cortex-R会直接从历史对话中检索答案,而无需任何工具调用。
查询:
🧑 What do you want to solve today? → Find the ASCII values of characters in INDIA and then return sum of exponentials of those values.终端输出:
[23:19:01] [historical_check] 🔍 Checking historical conversations for direct answer...
[23:19:01] [historical_check] 📚 Found 5 relevant historical conversations
══════════════════════════════════════════════════════════════════════
║ ║
║ PATH: DIRECT_ANSWER ║
║ ║
║ Answer found completely in historical conversations ║
║ ║
══════════════════════════════════════════════════════════════════════
[23:19:02] [historical_check] ✅ Answer found in historical conversations - returning directly
[23:19:02] [agent] ✅ Direct answer from historical conversations - skipping tool loop
💡 Final Answer: {"ascii_values": [73, 78, 68, 73, 65], "exponential_sum": 7.59982224609308e+33}发生了什么:
- 代理使用语义搜索搜索历史对话
- 从之前的对话中找到了完全匹配的内容
- 立即返回答案,没有任何工具调用
- 对话已自动编入索引,以备将来搜索
______________________________________________________________________
示例2:部分上下文+工具调用
当历史上下文提供部分信息时,Cortex-R会使用该上下文并调用适当的工具来完成任务。
查询:
🧑 What do you want to solve today? → can you add 5 to ASCII values of INDIA终端输出:
[23:19:22] [historical_check] 🔍 Checking historical conversations for direct answer...
[23:19:23] [historical_check] 📚 Found 5 relevant historical conversations
══════════════════════════════════════════════════════════════════════
║ ║
║ PATH: CONTEXT_AWARE ║
║ ║
║ Relevant context found - will send to perception layer ║
║ ║
║────────────────────────────────────────────────────────────────────║
║ CONTEXT TAKEN FORWARD: ║
║────────────────────────────────────────────────────────────────────║
║ Previous conversations provide the ASCII values for the characters ║
║ in "INDIA" as [73, 78, 68, 73, 65]. However, the specific request ║
║ to add 5 to these ASCII values has not been directly answered. ║
║ ║
══════════════════════════════════════════════════════════════════════
[23:19:24] [historical_check] 📚 Relevant context found in history - will send to perception layer
[23:19:24] [agent] 📚 Proceeding to tool loop with historical context (will be sent to perception)
🔁 Step 1/5 starting...
[23:19:26] [perception] intent='Perform arithmetic operation on ASCII values'
entities=['5', 'ASCII', 'INDIA']
tool_hint='You can compute the new ASCII values by adding 5 to each of the previous ASCII values.'
selected_servers=['math']
[plan] async def solve():
# USE the provided values from context - DO NOT call strings_to_chars_to_int!
ascii_values = [73, 78, 68, 73, 65] # From context
# Now add 5 to each
result = []
for val in ascii_values:
add_result = await mcp.call_tool('add', {"input": {"a": val, "b": 5}})
result.append(json.loads(add_result.content[0].text)["result"])
return "FINAL_ANSWER: " + str(result)
[23:19:31] [sandbox] 🔧 Calling tool: add (call #1)
[23:19:31] [sandbox] ✅ Tool add completed
...
💡 Final Answer: [78, 83, 73, 78, 70]发生了什么:
- 找到相关历史上下文(印度的ASCII值)
- 认识到上下文提供了部分信息
- 直接使用提供的ASCII值(未重新获取)
- 被称为
add工具5次,每个值加5 - 结合历史背景和工具调用来完成任务
______________________________________________________________________
示例3:网页抓取和自动索引
Cortex-R可以抓取网页、提取内容、对其进行总结,并自动将其索引到内存中以供将来搜索。
查询:
🧑 What do you want to solve today? → can you summarize this https://www.seldon.io/managing-realtime-ai-cost-in-production-a-practical-guide/终端输出:
[23:37:14] [historical_check] 🔍 Checking historical conversations for direct answer...
[23:37:15] [historical_check] 🆕 No relevant context in history - proceeding with traditional route
[23:37:15] [agent] 🆕 Proceeding to tool loop with fresh approach (no relevant history)
🔁 Step 1/5 starting...
[23:37:18] [perception] intent='summarize an article'
entities=['Seldon', 'AI', 'cost', 'production', 'guide']
selected_servers=['documents', 'websearch']
[plan] async def solve():
result = await mcp.call_tool('convert_webpage_url_into_markdown',
{"input": {"url": "https://www.seldon.io/..."}})
markdown = json.loads(result.content[0].text)["markdown"]
return "FURTHER_PROCESSING_REQUIRED: " + markdown
[23:37:20] [sandbox] 🔧 Calling tool: convert_webpage_url_into_markdown (call #1)
CAPTION: 🖼️ Attempting to caption image: https://www.seldon.io/wp-content/uploads/...
CAPTION: ✅ Caption generated: [Image descriptions]
[23:37:22] [sandbox] ✅ Tool convert_webpage_url_into_markdown completed
##### FURTHER_PROCESSING_REQUIRED: In the last three years adoption of AI across industries has increased by 56% [1]. This growth has translated into a surge of AI use-cases reaching production...
[23:37:22] [loop] 🔍 Content already provided - using LLM directly to analyze (bypassing tool selection)
[23:37:22] [loop] ✅ LLM direct analysis completed
💡 Final Answer: [Comprehensive summary of the article about managing real-time AI costs in production, including key strategies, cost breakdowns, and best practices...]
[conversation_indexer] Saved index with 35 conversations
[conversation_indexer] ✅ Indexed conversation: 2025/11/14/session-1...
[23:37:38] [agent] ✅ Conversation indexed for semantic search发生了什么:
- 在查询中检测到URL并选择了适当的工具
- 称为
convert_webpage_url_into_markdown提取干净的标记 - 网页中自动添加字幕的图像
- 使用LLM分析和总结内容
- 自动为整个对话建立索引 (查询+回答)记忆
- 以后对本文的查询将从内存中检索它
______________________________________________________________________
🏗️ 建筑
📄 架构图:参见 architecture_diagram.pdf 用于系统架构的全面流程图可视化。三路径历史语境体系
Cortex-R使用智能预检查层,为每个查询确定最佳路径:
┌─────────────────────────────────────────┐
│ Historical Conversation Check │
└─────────────────────────────────────────┘
│
┌───────────┴───────────┐
│ │
▼ ▼
┌───────────────┐ ┌───────────────┐
│ PATH 1: │ │ PATH 2: │
│ DIRECT_ANSWER │ │ CONTEXT_AWARE │
│ │ │ │
│ Answer found │ │ Partial info │
│ completely in │ │ found - use │
│ history │ │ with tools │
└───────────────┘ └───────────────┘
│
▼
┌───────────────┐
│ PATH 3: │
│ FRESH_APPROACH │
│ │
│ No relevant │
│ context │
└───────────────┘关键组件
- 历史检查层 (
modules/historical_check.py)
- 使用语义搜索搜索历史对话 - 使用LLM确定答案是否可用 - 返回三个路径之一:DIRECT_ANSWER、CONTEXT_AWARE或FRESH_APPROACH
- 感知层 (
modules/perception.py)
- 分析用户意图和实体 - 选择相关的MCP服务器 - 可以接收历史上下文以通知工具选择
- 决策层 (
modules/decision.py)
- 生成可执行Python solve() 函数 - 直接使用提供的上下文值(无需重新获取) - 处理工具选择和规划
- 动作层 (
modules/action.py)
- 在沙盒环境中执行生成的计划 - 使用速率限制管理工具调用 - 返回结果或 FURTHER_PROCESSING_REQUIRED
- 存储器系统 (
modules/conversation_indexer.py)
- 自动为所有对话建立索引 - 使用FAISS进行语义搜索 - 存储对话元数据和嵌入
🔧 配置
编辑 config/profiles.yaml 自定义:
- LLM提供者:OpenAI、Gemini或Olama
- 计划模式:保守型(每一步一个工具)或探索型(多个工具)
- 内存设置:存储位置、摘要、标记
- MCP服务器:添加或修改工具服务器
📝 详细功能
智能上下文重用
- 无重新提取:当历史上下文提供值时,代理直接使用它们
- 上下文感知工具选择:感知层接收历史背景,以做出更好的工具选择
- 无关上下文过滤:自动检测并忽略不相关的历史上下文
Web内容处理
- 清除Markdown提取:将网页转换为干净、可读的markdown
- 图像描述:使用视觉模型自动为图像生成字幕
- 自动索引:所有抓取的内容都已编入索引,以便将来进行语义搜索
环路预防
- 严格的规则:当内容通过以下方式提供时
FURTHER_PROCESSING_REQUIRED,代理直接对其进行分析 - LLM回退:如果检测到循环,系统会自动使用LLM来分析内容
- 内容检测:自动检测内容何时已提供,并绕过工具选择
🛡️ 护栏
- 查询验证:检查SQL注入、命令注入和其他安全威胁
- 结果消毒:对最终输出中的个人身份信息和敏感信息进行消毒
- 内容过滤:删除禁用词和脏话
- 安全执行:带工具调用限制的沙盒Python执行
📊 存储器系统
所有对话都会自动编入索引:
- 语义搜索:基于FAISS的矢量搜索,用于查找相关对话
- 元数据存储:存储用户查询、最终答案和工具调用
- 会话管理:按日期和会话ID组织对话
🎯 用例
- 研究与总结:抓取和总结网络文章
- 数据分析:根据前几次会议的上下文进行计算
- 信息检索:从历史对话中寻找答案
- 多步骤问题解决:将复杂任务分解为步骤
📸 截图
备注:在此处添加屏幕截图,显示: - 每个示例的终端输出 - PATH选择框 - 内存索引确认消息 - 工具调用日志
🤝 贡献
这是一个学习项目。请随时探索代码库并提出改进建议!
📄 许可证
\[在此处添加您的许可证\]
______________________________________________________________________
内置于❤️ 使用MCP(模型上下文协议)、FAISS和现代LLM API
