1+ import textwrap
2+ from pathlib import Path
3+
4+ from langchain .agents import create_agent
5+ from langchain .agents .middleware import ModelRequest , ModelResponse , dynamic_prompt , wrap_model_call
6+
7+ from src .agents .common .base import BaseAgent
8+ from src .agents .common .models import load_chat_model
9+ from src .agents .common .mcp import get_mcp_tools
10+ from src .agents .common .toolkits .mysql import get_mysql_tools
11+ from src .utils import logger
12+
13+ _mcp_servers = {
14+ "mcp-server-chart" : {
15+ "url" : "https://mcp.api-inference.modelscope.net/9993ae42524c4c/mcp" ,
16+ "transport" : "streamable_http" ,
17+ },
18+ }
19+
20+ @dynamic_prompt
21+ def context_aware_prompt (request : ModelRequest ) -> str :
22+ user_prompt = request .runtime .context .system_prompt
23+ agent_prompt = user_prompt + textwrap .dedent ("""
24+ You are an SQL reporting assistant. Your task is to generate SQL queries based on user requests
25+ and provide insights from the database. Use the tools provided to you to answer the questions.
26+ """ )
27+
28+ return agent_prompt
29+
30+
31+ @wrap_model_call
32+ async def context_based_model (request : ModelRequest , handler ) -> ModelResponse :
33+ # 从 runtime context 读取配置
34+ model_spec = request .runtime .context .model
35+ model = load_chat_model (model_spec )
36+
37+ request = request .override (model = model )
38+ return await handler (request )
39+
40+
41+ class SqlReporterAgent (BaseAgent ):
42+ name = "SQL 报告助手"
43+ description = "一个能够生成 SQL 查询报告的智能体助手。同时调用 Charts MCP 生成图表。"
44+
45+ def __init__ (self , ** kwargs ):
46+ super ().__init__ (** kwargs )
47+
48+ async def get_tools (self ):
49+ chart_tools = await get_mcp_tools ("mcp-server-chart" , additional_servers = _mcp_servers )
50+ mysql_tools = get_mysql_tools ()
51+ return chart_tools + mysql_tools
52+
53+ async def get_graph (self , ** kwargs ):
54+ if self .graph :
55+ return self .graph
56+
57+ # 创建 SqlReporterAgent
58+ graph = create_agent (
59+ model = load_chat_model ("siliconflow/Qwen/Qwen3-235B-A22B-Instruct-2507" ),
60+ tools = await self .get_tools (),
61+ middleware = [context_aware_prompt , context_based_model ],
62+ checkpointer = await self ._get_checkpointer (),
63+ )
64+
65+ self .graph = graph
66+ logger .info ("SqlReporterAgent 构建成功" )
67+ return graph
0 commit comments