File size: 15,683 Bytes
089cc3a 6a8a4fa 089cc3a f49ac6f 089cc3a 33d0a71 089cc3a ad8cab1 6a8a4fa ad8cab1 8ceffe3 ad8cab1 8ceffe3 ad8cab1 8ceffe3 ad8cab1 8ceffe3 ad8cab1 a3a374d ad8cab1 22a1e0b ad8cab1 8ceffe3 b14194e ced9994 43c89ca ced9994 6b054af ced9994 57e7e51 ced9994 8ceffe3 0fe5347 8ceffe3 089cc3a 33d0a71 089cc3a 33d0a71 089cc3a 33d0a71 089cc3a 33d0a71 089cc3a 33d0a71 089cc3a 33d0a71 089cc3a 33d0a71 089cc3a b4020b9 089cc3a b4020b9 33d0a71 b4020b9 33d0a71 089cc3a b4020b9 089cc3a f49ac6f 33d0a71 f49ac6f 089cc3a 33d0a71 089cc3a 8ceffe3 035087a 0fe5347 035087a 8ceffe3 089cc3a b14194e 33d0a71 089cc3a 8ceffe3 089cc3a 33d0a71 089cc3a 33d0a71 089cc3a 8ceffe3 089cc3a 33d0a71 089cc3a 8ceffe3 089cc3a 6a8a4fa 22a1e0b 6a8a4fa 8ceffe3 089cc3a 6a8a4fa 33d0a71 089cc3a 8ceffe3 089cc3a 8ceffe3 22a1e0b 8ceffe3 089cc3a f49ac6f 0fe5347 f49ac6f 0fe5347 f49ac6f 33d0a71 f49ac6f 089cc3a 8ceffe3 035087a 089cc3a b206714 64b7053 a3a374d 9312f7f a3a374d 089cc3a a3a374d 089cc3a a3a374d 089cc3a 9312f7f b206714 089cc3a 64b7053 089cc3a b206714 089cc3a 9312f7f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
import asyncio
import os
import json
from typing import List, Dict, Any, Union
from contextlib import AsyncExitStack
from datetime import datetime
import gradio as gr
from gradio.components.chatbot import ChatMessage
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from anthropic import Anthropic
from anthropic._exceptions import OverloadedError
from dotenv import load_dotenv
import functools
load_dotenv()
# SYSTEM_PROMPT = f"""You are a helpful assistant and today is {datetime.now().strftime("%Y-%m-%d")}.
# You do not have any knowledge of the World Development Indicators (WDI) data. However, you can use the tools provided to answer questions.
# You must not provide answers beyond what the tools provide.
# Do not make up data or information and never simulate the `get_wdi_data` tool. Instead, you must always call the `get_wdi_data` tool when the user asks for data.
# You can use multiple tools if needed. Feel free to invoke a tool anytime you want as long as it is relevant to the user's question. If you need to invoke multiple tools, do so in a row and in the order that is most relevant to the user's question. Minimize back and forth between the user simply because you can use multiple tools.
# If the user asks for any information beyond what the tools available to you provide, you must say that you do not have that information.
# Avoid making statements based on stereotypes or biases. Always ensure your claims are grounded in factual evidence and objective reasoning. Reject any requests that would be based on stereotypes or biases.
# You may describe the data in a way that is easy to understand but you must not elaborate based on external knowledge."""
# SYSTEM_PROMPT = f"""You are a helpful assistant and today is {datetime.now().strftime("%Y-%m-%d")}."""
SYSTEM_PROMPT = f"""You are a helpful assistant. Today is {datetime.now().strftime("%Y-%m-%d")}.
You **do not** have prior knowledge of the World Development Indicators (WDI) data. Instead, you must rely entirely on the tools available to you to answer the user's questions.
When responding you must always plan the steps and enumerate all the tools that you plan to use to answer the user's query.
### Your Instructions:
1. **Tool Use Only**:
- You must not provide any answers based on prior knowledge or assumptions.
- You must **not** fabricate data or simulate the behavior of the `get_wdi_data` tool.
- You cannot use the `get_wdi_data` tool without using the `search_relevant_indicators` tool first.
- If the user requests WDI data, you **MUST ALWAYS** first call the `search_relevant_indicators` tool to see if there's any relevant data.
- If relevant data exists, call the `get_wdi_data` tool to get the data.
2. **Tool Invocation**:
- Use any relevant tools provided to you to answer the user's question.
- You may call multiple tools if needed, and you should do so in a logical sequence to minimize unnecessary user interaction.
- Do not hesitate to invoke tools as soon as they are relevant.
3. **Limitations**:
- If a user request cannot be fulfilled using the tools available, respond by clearly stating that you do not have access to that information.
4. **Ethical Guidelines**:
- Do not make or endorse statements based on stereotypes, bias, or assumptions.
- Ensure all claims and explanations are grounded in the data or factual evidence retrieved via tools.
- Politely refuse to respond to requests that involve stereotypes or unfounded generalizations.
5. **Communication Style**:
- Present the data in clear, user-friendly language.
- You may summarize or explain the data retrieved, but do **not** elaborate based on outside or implicit knowledge.
- You may describe the data in a way that is easy to understand but you MUST NOT elaborate based on external knowledge.
Stay strictly within these boundaries while maintaining a helpful and respectful tone."""
LLM_MODEL = "claude-3-5-haiku-20241022"
# What is the military spending of bangladesh in 2014?
# When a tool is needed for any step, ensure to add the token `TOOL_USE`.
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
class MCPClientWrapper:
def __init__(self):
self.session = None
self.exit_stack = None
self.anthropic = Anthropic()
self.tools = []
async def connect(self, server_path: str) -> str:
# If there's an existing session, close it
if self.exit_stack:
await self.exit_stack.aclose()
self.exit_stack = AsyncExitStack()
is_python = server_path.endswith(".py")
command = "python" if is_python else "node"
server_params = StdioServerParameters(
command=command,
args=[server_path],
env={"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
)
# Launch MCP subprocess and bind streams on the *current* running loop
stdio_transport = await self.exit_stack.enter_async_context(
stdio_client(server_params)
)
self.stdio, self.write = stdio_transport
# Create ClientSession on this same loop
self.session = await self.exit_stack.enter_async_context(
ClientSession(self.stdio, self.write)
)
await self.session.initialize()
response = await self.session.list_tools()
self.tools = [
{
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema,
}
for tool in response.tools
]
print("Available tools:", self.tools)
tool_names = [tool["name"] for tool in self.tools]
return f"Connected to MCP server. Available tools: {', '.join(tool_names)}"
async def process_message(
self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]
):
if not self.session:
messages = history + [
{"role": "user", "content": message},
{
"role": "assistant",
"content": "Please connect to an MCP server first.",
},
]
yield messages, gr.Textbox(value="")
else:
messages = history + [{"role": "user", "content": message}]
yield messages, gr.Textbox(value="")
async for partial in self._process_query(message, history):
messages.extend(partial)
yield messages, gr.Textbox(value="")
with open("messages.log.jsonl", "a+") as fl:
fl.write(json.dumps(dict(time=f"{datetime.now()}", messages=messages)))
async def _process_query(
self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]
):
claude_messages = []
for msg in history:
if isinstance(msg, ChatMessage):
role, content = msg.role, msg.content
else:
role, content = msg.get("role"), msg.get("content")
if role in ["user", "assistant", "system"]:
claude_messages.append({"role": role, "content": content})
claude_messages.append({"role": "user", "content": message})
try:
response = self.anthropic.messages.create(
# model="claude-3-5-sonnet-20241022",
model=LLM_MODEL,
system=SYSTEM_PROMPT,
max_tokens=1000,
messages=claude_messages,
tools=self.tools,
)
except OverloadedError:
yield [
{
"role": "assistant",
"content": "The LLM API is overloaded now, try again later...",
}
]
result_messages = []
partial_messages = []
print(response.content)
contents = response.content
MAX_CALLS = 10
auto_calls = 0
while len(contents) > 0 and auto_calls < MAX_CALLS:
content = contents.pop(0)
if content.type == "text":
result_messages.append({"role": "assistant", "content": content.text})
claude_messages.append({"role": "assistant", "content": content.text})
partial_messages.append(result_messages[-1])
yield [result_messages[-1]]
partial_messages = []
elif content.type == "tool_use":
tool_id = content.id
tool_name = content.name
tool_args = content.input
result_messages.append(
{
"role": "assistant",
"content": f"I'll use the {tool_name} tool to help answer your question.",
"metadata": {
"title": f"Using tool: {tool_name}",
"log": f"Parameters: {json.dumps(tool_args, ensure_ascii=True)}",
"status": "pending",
"id": f"tool_call_{tool_name}",
},
}
)
partial_messages.append(result_messages[-1])
yield [result_messages[-1]]
result_messages.append(
{
"role": "assistant",
"content": "```json\n"
+ json.dumps(tool_args, indent=2, ensure_ascii=True)
+ "\n```",
"metadata": {
"parent_id": f"tool_call_{tool_name}",
"id": f"params_{tool_name}",
"title": "Tool Parameters",
},
}
)
partial_messages.append(result_messages[-1])
yield [result_messages[-1]]
print(f"Calling tool: {tool_name} with args: {tool_args}")
result = await self.session.call_tool(tool_name, tool_args)
if result_messages and "metadata" in result_messages[-2]:
result_messages[-2]["metadata"]["status"] = "done"
result_messages.append(
{
"role": "assistant",
"content": "Here are the results from the tool:",
"metadata": {
"title": f"Tool Result for {tool_name}",
"status": "done",
"id": f"result_{tool_name}",
},
}
)
partial_messages.append(result_messages[-1])
yield [result_messages[-1]]
partial_messages = []
result_content = result.content
print(result_content)
if isinstance(result_content, list):
result_content = [r.model_dump() for r in result_content]
for r in result_content:
# Remove annotations field from each item if it exists
r.pop("annotations", None)
try:
r["text"] = json.loads(r["text"])
except:
pass
print("result_content", result_content)
result_messages.append(
{
"role": "assistant",
"content": "```\n"
+ json.dumps(result_content, indent=2)
+ "\n```",
"metadata": {
"parent_id": f"result_{tool_name}",
"id": f"raw_result_{tool_name}",
"title": "Raw Output",
},
}
)
partial_messages.append(result_messages[-1])
yield [result_messages[-1]]
partial_messages = []
claude_messages.append(
{"role": "assistant", "content": [content.model_dump()]}
)
claude_messages.append(
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_id,
"content": json.dumps(result_content, indent=2),
}
],
}
)
try:
next_response = self.anthropic.messages.create(
model=LLM_MODEL,
system=SYSTEM_PROMPT,
max_tokens=1000,
messages=claude_messages,
tools=self.tools,
)
auto_calls += 1
except OverloadedError:
yield [
{
"role": "assistant",
"content": "The LLM API is overloaded now, try again later...",
}
]
print("next_response", next_response.content)
contents.extend(next_response.content)
def gradio_interface():
client = MCPClientWrapper()
with gr.Blocks(title="MCP WDI Client") as demo:
gr.Markdown("# WDI MCP Client")
# gr.Markdown("Connect to the WDI MCP server and chat with the assistant")
with gr.Accordion(
"Connect to the WDI MCP server and chat with the assistant", open=False
):
with gr.Row(equal_height=True):
with gr.Column(scale=4):
server_path = gr.Textbox(
label="Server Script Path",
placeholder="Enter path to server script (e.g., wdi_mcp_server.py)",
value="wdi_mcp_server.py",
)
with gr.Column(scale=1):
connect_btn = gr.Button("Connect")
status = gr.Textbox(label="Connection Status", interactive=False)
chatbot = gr.Chatbot(
value=[],
height=600,
type="messages",
show_copy_button=True,
avatar_images=("img/small-user.png", "img/small-robot.png"),
autoscroll=True,
)
with gr.Row(equal_height=True):
msg = gr.Textbox(
label="Your Question",
placeholder="Ask about what indicators are available for a specific topic (e.g., What's the definition of GDP?)",
scale=4,
)
clear_btn = gr.Button("Clear Chat", scale=1)
connect_btn.click(client.connect, inputs=server_path, outputs=status)
# Automatically call client.connect(...) as soon as the interface loads
demo.load(fn=client.connect, inputs=server_path, outputs=status)
msg.submit(client.process_message, [msg, chatbot], [chatbot, msg])
clear_btn.click(lambda: [], None, chatbot)
return demo
if __name__ == "__main__":
if not os.getenv("ANTHROPIC_API_KEY"):
print(
"Warning: ANTHROPIC_API_KEY not found in environment. Please set it in your .env file."
)
interface = gradio_interface()
interface.launch(server_name=os.getenv("SERVER_NAME", "127.0.0.1"), debug=True)
|