当前位置: 首页 > news >正文

AIAgent

AIAgent 是一个 AI 代理类,用于处理企业微信消息。

from deepagents import create_deep_agent from langchain_mcp_adapters.tools import load_mcp_tools from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage from mcp.client.session import ClientSession from mcp.client.streamable_http import streamable_http_client from pkg.config import cfg from pkg.log import get_logger class AIAgent: logger = get_logger("ai_agent") def __init__(self): self.model: ChatOpenAI = None # type: ignore self._mcp_session: ClientSession = None # type: ignore self._mcp_server_url = f"http://127.0.0.1:{cfg.service_port}/mcp/" async def start(self): if not self.model: self.model = ChatOpenAI( base_url=cfg.agent_base_url, api_key=cfg.agent_api_key, # type: ignore model=cfg.agent_model, ) async def shutdown(self): self.model = None # type: ignore async def _create_root_agent(self, session: ClientSession): tools = await load_mcp_tools(session) root_agent = create_deep_agent( model=self.model, tools=tools, system_prompt=f"你是一个智能助手,名字叫{cfg.qywx_bot_name}, 可以协助用户处理各种问题,并用温和积极的语气回答问题。回答的格式应该符合markdown规范。", ) return root_agent async def astream(self, input: str, thread_id: str = ""): self.logger.debug(f"Connecting to mcp server: {self._mcp_server_url}") async with streamable_http_client(self._mcp_server_url) as (read, write, get_session_id): async with ClientSession(read, write) as session: await session.initialize() root_agent = await self._create_root_agent(session) async for chunk in root_agent.astream( input={"messages": [HumanMessage(content=input)]} ): # 从 chunk 字典中提取 AIMessage 的 content if isinstance(chunk, dict): messages = chunk.get("model", {}).get("messages", []) if not messages: continue for msg in messages: if hasattr(msg, "content") and msg.content: yield str(msg.content) elif hasattr(chunk, "content"): yield str(chunk.content) # type: ignore else: yield str(chunk) async def ainvoke(self, input: str, thread_id: str = ""): self.logger.debug(f"Connecting to mcp server: {self._mcp_server_url}") async with streamable_http_client(self._mcp_server_url) as (read, write, get_session_id): async with ClientSession(read, write) as session: await session.initialize() root_agent = await self._create_root_agent(session) resp = await root_agent.ainvoke( input={"messages": [HumanMessage(content=input)]} ) return resp["messages"][-1].content

main

# main.py from fastapi import FastAPI, Request from fastapi.responses import JSONResponse import uvicorn from contextlib import asynccontextmanager from pkg.qywx import qywx_client from pkg.config import cfg from ai_agent.mcp_servers.datetime_server import mcp as datetime_mcp from ai_agent import aiops @asynccontextmanager async def lifespan(app: FastAPI): await aiops.start() await qywx_client.start() # 先获取 MCP app(这会创建 session_manager) mcp_app = datetime_mcp.streamable_http_app() # 在 FastAPI lifespan 中启动 MCP session manager async with datetime_mcp.session_manager.run(): # 挂载 MCP app app.mount("/mcp", mcp_app) yield await aiops.shutdown() await qywx_client.shutdown() app = FastAPI( lifespan=lifespan ) if __name__ == "__main__": uvicorn.run("main:app", host=cfg.service_host, port=cfg.service_port)
http://www.gsyq.cn/news/1605776.html

相关文章:

  • 扬州清宸康养180道菜不重样?真相究竟是怎样,快来一探究竟!
  • ModelEngine QA对生成技术:如何实现60%留用率的高质量训练数据
  • 好用的检测机DD马达哪家靠谱
  • GaussDB(DWS)数据仓库性能压测与调优实战:从0到1全记录
  • 【从0到1构建一个ClaudeAg _
  • 为什么建议中小企业优先考虑开源ERP
  • AI编码代理实战:从网站克隆到Next.js项目生成的工程化指南
  • AI 赋能接口自动化测试系列(一):接口文档智能解析Agent Skill推荐
  • OpenMontage:本地化AI视频全链路制作工具部署与实战指南
  • 计算机毕业设计之基于深度学习的花卉分类检测系统的设计与实现
  • 基于PANDAS的QAbstractTableModel实现高级TableView详细解析(九、在TableView实现多重表头)
  • 2026算力避坑实测!主流GPU租赁平台稳定性深度评测,告别宕机与算力虚标
  • Paxos算法:如何解决分布式系统中的共识问题
  • 民意调查真伪辨别!四招看懂靠谱民调标准
  • 快消品新零售商城小程序开发
  • 全球AI可见性基础建设:从“信息发布”到“AI记忆持续性”的重构
  • gt-checksum v4.0.0 新功能解读系列文章(4):SSL 加密连接——数据校验传输安全再升级
  • 基于MCP协议构建AI编程助手持久化代码记忆的实战指南
  • OpenMontage:从文本到视频的AI自动化生成框架实践指南
  • D1117 低压差线性稳压电路
  • 5分钟快速上手OWASP Dependency-Check:命令行实战与CI/CD集成指南
  • LoRA训练实战61:Krea2人物角色LoRA保姆级训练教程,几分钟捏出专属IP!
  • 一款H5播放器,搞定所有流媒体协议?EasyPlayer.js流媒体播放器到底有多强
  • AI Agent沙箱是什么?跟Docker容器和虚拟机有什么区别
  • Skills开源项目:为AI Agent提供标准化技能库,实现代码仓库自动化操作
  • 【车载】轮速-AK协议:从电流信号到车辆控制的解码之旅
  • AI 赋能接口自动化测试系列(二):全场景测试数据智能构造Agent Skill
  • 后端架构演进:微服务与单体应用如何选择
  • 2026 年小程序开发公司推荐,靠谱服务商汇总
  • AI Agent多智能体系统在金融投资分析中的实战应用