jdewitte commited on
Commit
d7afe5d
·
1 Parent(s): ab09c53

connect mcp

Browse files
Files changed (1) hide show
  1. app_api.py +43 -5
app_api.py CHANGED
@@ -13,24 +13,62 @@ MODEL_NAME = "Qwen/Qwen3-4B-Thinking-2507" # Smallest Qwen3 model
13
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
14
  model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)
15
 
16
- def chat(prompt):
17
- # Send JSON-RPC request to MCP server
 
 
 
 
 
 
 
 
 
18
  mcp_url = "http://localhost:8080/standalone-mcp.php"
19
  jsonrpc_id = str(uuid.uuid4())
20
  payload = {
21
  "jsonrpc": "2.0",
22
- "method": "tools/list", # Example: list tools, you can change to tools/call for real queries
 
 
 
 
23
  "id": jsonrpc_id
24
  }
25
  try:
26
  response = requests.post(mcp_url, json=payload, timeout=10)
27
  response.raise_for_status()
28
  data = response.json()
29
- # Return the full JSON for now, or extract what you want
30
- return str(data)
 
31
  except Exception as e:
32
  return f"Error contacting MCP server: {e}"
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  # Gradio interface
35
  iface = gr.Interface(fn=chat, inputs="text", outputs="text", title="Qwen3 Chatbot")
36
 
 
13
  tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
14
  model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)
15
 
16
+ import json
17
+
18
+ def call_llm(prompt, context=None):
19
+ # Optionally add context for a second LLM pass
20
+ if context:
21
+ prompt = f"User: {prompt}\n\nMCP Data: {context}\n\nPlease answer the user using the above information."
22
+ inputs = tokenizer(prompt, return_tensors="pt")
23
+ outputs = model.generate(**inputs, max_new_tokens=512)
24
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
25
+
26
+ def call_mcp(tool, arguments):
27
  mcp_url = "http://localhost:8080/standalone-mcp.php"
28
  jsonrpc_id = str(uuid.uuid4())
29
  payload = {
30
  "jsonrpc": "2.0",
31
+ "method": "tools/call",
32
+ "params": {
33
+ "name": tool,
34
+ "arguments": arguments
35
+ },
36
  "id": jsonrpc_id
37
  }
38
  try:
39
  response = requests.post(mcp_url, json=payload, timeout=10)
40
  response.raise_for_status()
41
  data = response.json()
42
+ # Extract text content from MCP response
43
+ content = data.get("result", {}).get("content", [{}])[0].get("text", str(data))
44
+ return content
45
  except Exception as e:
46
  return f"Error contacting MCP server: {e}"
47
 
48
+ def chat(prompt):
49
+ # Step 1: Ask LLM what to do (tool call or answer directly)
50
+ tool_prompt = (
51
+ "You are a helpful assistant with access to PrestaShop product tools. "
52
+ "If the user asks for product details, features, or images, output a JSON like "
53
+ "{\"tool\": \"get_product_details\", \"product_id\": 123}. "
54
+ "Otherwise, answer normally. Only output the JSON if a tool call is needed.\n\n"
55
+ f"User: {prompt}"
56
+ )
57
+ llm_output = call_llm(tool_prompt)
58
+ # Try to parse tool call
59
+ try:
60
+ tool_call = json.loads(llm_output)
61
+ if isinstance(tool_call, dict) and "tool" in tool_call:
62
+ tool = tool_call["tool"]
63
+ arguments = {k: v for k, v in tool_call.items() if k != "tool"}
64
+ mcp_result = call_mcp(tool, arguments)
65
+ # Step 2: Ask LLM to answer using MCP data
66
+ final_answer = call_llm(prompt, context=mcp_result)
67
+ return final_answer
68
+ except Exception:
69
+ pass # Not a tool call, just return LLM output
70
+ return llm_output
71
+
72
  # Gradio interface
73
  iface = gr.Interface(fn=chat, inputs="text", outputs="text", title="Qwen3 Chatbot")
74