Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,11 @@
|
|
| 1 |
import os
|
| 2 |
-
import json
|
| 3 |
import asyncio
|
|
|
|
| 4 |
import gradio as gr
|
|
|
|
| 5 |
from google import genai
|
| 6 |
from google.genai import types
|
|
|
|
| 7 |
from mcp import ClientSession
|
| 8 |
from mcp.client.sse import sse_client
|
| 9 |
|
|
@@ -11,27 +13,43 @@ from mcp.client.sse import sse_client
|
|
| 11 |
MCP_SERVER_URL = "https://mgokg-db-timetable-api.hf.space/gradio_api/mcp/"
|
| 12 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
| 16 |
async with sse_client(MCP_SERVER_URL) as (read_stream, write_stream):
|
| 17 |
async with ClientSession(read_stream, write_stream) as session:
|
| 18 |
await session.initialize()
|
| 19 |
-
result = await session.call_tool(
|
| 20 |
-
"
|
| 21 |
-
"dest_loc": dest_loc
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
|
|
|
| 26 |
"""Async generator handling the tool loop with the corrected aio client."""
|
| 27 |
if not GEMINI_API_KEY:
|
| 28 |
-
yield "### Error\
|
| 29 |
return
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
model_id = "gemini-2.5-flash" # Ensure this is a valid model ID for your tier
|
| 34 |
|
|
|
|
| 35 |
train_tool = types.Tool(
|
| 36 |
function_declarations=[
|
| 37 |
types.FunctionDeclaration(
|
|
@@ -41,88 +59,94 @@ async def generate(input_text):
|
|
| 41 |
"type": "OBJECT",
|
| 42 |
"properties": {
|
| 43 |
"start_loc": {"type": "STRING", "description": "Departure city"},
|
| 44 |
-
"dest_loc": {"type": "STRING", "description": "Destination city"}
|
| 45 |
},
|
| 46 |
-
"required": ["start_loc", "dest_loc"]
|
| 47 |
-
}
|
| 48 |
)
|
| 49 |
]
|
| 50 |
)
|
| 51 |
|
| 52 |
try:
|
| 53 |
yield "π Thinking...", ""
|
| 54 |
-
|
| 55 |
config = types.GenerateContentConfig(
|
| 56 |
tools=[train_tool],
|
| 57 |
-
temperature=0.3
|
| 58 |
)
|
| 59 |
|
| 60 |
-
#
|
| 61 |
-
chat = client.aio.chats.create(model=model_id, config=config)
|
| 62 |
-
|
| 63 |
-
#
|
| 64 |
response = await chat.send_message(input_text)
|
| 65 |
|
| 66 |
# --- Manual Tool Loop ---
|
| 67 |
max_turns = 5
|
| 68 |
for _ in range(max_turns):
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
break
|
| 71 |
-
|
| 72 |
-
#tool_calls = [p.tool_call for p in response.candidates[0].content.parts if p.tool_call]
|
| 73 |
-
#if not tool_calls:
|
| 74 |
-
#break
|
| 75 |
-
|
| 76 |
-
part = response.candidates[0].content.parts[0]
|
| 77 |
-
if part.function_call:
|
| 78 |
-
function_name = part.function_call.name
|
| 79 |
-
arguments = part.function_call.args
|
| 80 |
-
print(f"Rufe Funktion {function_name} mit {arguments} auf")
|
| 81 |
-
|
| 82 |
tool_responses = []
|
|
|
|
| 83 |
for call in tool_calls:
|
| 84 |
if call.name == "get_train_connections":
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
tool_responses.append(
|
| 90 |
types.Part.from_function_response(
|
| 91 |
name=call.name,
|
| 92 |
-
response={
|
|
|
|
|
|
|
| 93 |
)
|
| 94 |
)
|
| 95 |
-
|
| 96 |
if tool_responses:
|
| 97 |
yield "π Finalizing response...", ""
|
| 98 |
-
#
|
| 99 |
response = await chat.send_message(tool_responses)
|
| 100 |
else:
|
| 101 |
break
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
# --- GRADIO UI ---
|
| 109 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 110 |
-
gr.Markdown("# π Gemini MCP Train Assistant")
|
| 111 |
-
|
| 112 |
-
output_textbox = gr.Markdown(label="Response")
|
| 113 |
-
input_textbox = gr.Textbox(label="Ask about German train connections", placeholder="Berlin to Munich?")
|
| 114 |
-
submit_button = gr.Button("Send", variant="primary")
|
| 115 |
-
|
| 116 |
-
submit_button.click(
|
| 117 |
-
fn=generate,
|
| 118 |
-
inputs=input_textbox,
|
| 119 |
-
outputs=[output_textbox, input_textbox]
|
| 120 |
-
)
|
| 121 |
-
|
| 122 |
-
if __name__ == '__main__':
|
| 123 |
-
demo.launch()
|
| 124 |
-
|
| 125 |
-
|
| 126 |
|
| 127 |
|
| 128 |
"""
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import asyncio
|
| 3 |
+
import json
|
| 4 |
import gradio as gr
|
| 5 |
+
|
| 6 |
from google import genai
|
| 7 |
from google.genai import types
|
| 8 |
+
|
| 9 |
from mcp import ClientSession
|
| 10 |
from mcp.client.sse import sse_client
|
| 11 |
|
|
|
|
| 13 |
MCP_SERVER_URL = "https://mgokg-db-timetable-api.hf.space/gradio_api/mcp/"
|
| 14 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 15 |
|
| 16 |
+
|
| 17 |
+
async def call_mcp_tool(start_loc: str, dest_loc: str) -> str:
|
| 18 |
+
"""Connect to the MCP server to fetch train data."""
|
| 19 |
async with sse_client(MCP_SERVER_URL) as (read_stream, write_stream):
|
| 20 |
async with ClientSession(read_stream, write_stream) as session:
|
| 21 |
await session.initialize()
|
| 22 |
+
result = await session.call_tool(
|
| 23 |
+
"get_train_connections",
|
| 24 |
+
arguments={"start_loc": start_loc, "dest_loc": dest_loc}
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Defensive handling: MCP returns a structured content array
|
| 28 |
+
# e.g., result.content[0].text or result.content[0].type == 'text'
|
| 29 |
+
try:
|
| 30 |
+
if hasattr(result, "content") and result.content:
|
| 31 |
+
first = result.content[0]
|
| 32 |
+
if hasattr(first, "text") and first.text:
|
| 33 |
+
return first.text
|
| 34 |
+
# Fallback: if the structure differs, try to serialize
|
| 35 |
+
return json.dumps([c.__dict__ for c in result.content], ensure_ascii=False)
|
| 36 |
+
except Exception:
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
# Final fallback
|
| 40 |
+
return "No train data returned from MCP."
|
| 41 |
|
| 42 |
+
|
| 43 |
+
async def generate(input_text: str):
|
| 44 |
"""Async generator handling the tool loop with the corrected aio client."""
|
| 45 |
if not GEMINI_API_KEY:
|
| 46 |
+
yield "### Error\n`GEMINI_API_KEY` is not set.", ""
|
| 47 |
return
|
| 48 |
|
| 49 |
+
client = genai.Client(api_key=GEMINI_API_KEY)
|
| 50 |
+
model_id = "gemini-2.5-flash" # Ensure this is enabled for your API key
|
|
|
|
| 51 |
|
| 52 |
+
# Declare the function/tool to the model
|
| 53 |
train_tool = types.Tool(
|
| 54 |
function_declarations=[
|
| 55 |
types.FunctionDeclaration(
|
|
|
|
| 59 |
"type": "OBJECT",
|
| 60 |
"properties": {
|
| 61 |
"start_loc": {"type": "STRING", "description": "Departure city"},
|
| 62 |
+
"dest_loc": {"type": "STRING", "description": "Destination city"},
|
| 63 |
},
|
| 64 |
+
"required": ["start_loc", "dest_loc"],
|
| 65 |
+
},
|
| 66 |
)
|
| 67 |
]
|
| 68 |
)
|
| 69 |
|
| 70 |
try:
|
| 71 |
yield "π Thinking...", ""
|
| 72 |
+
|
| 73 |
config = types.GenerateContentConfig(
|
| 74 |
tools=[train_tool],
|
| 75 |
+
temperature=0.3,
|
| 76 |
)
|
| 77 |
|
| 78 |
+
# IMPORTANT: create async chat session with await
|
| 79 |
+
chat = await client.aio.chats.create(model=model_id, config=config)
|
| 80 |
+
|
| 81 |
+
# Send the user input to the model
|
| 82 |
response = await chat.send_message(input_text)
|
| 83 |
|
| 84 |
# --- Manual Tool Loop ---
|
| 85 |
max_turns = 5
|
| 86 |
for _ in range(max_turns):
|
| 87 |
+
# Basic guards
|
| 88 |
+
if not response.candidates:
|
| 89 |
+
break
|
| 90 |
+
|
| 91 |
+
candidate = response.candidates[0]
|
| 92 |
+
parts = getattr(candidate.content, "parts", []) or []
|
| 93 |
+
if not parts:
|
| 94 |
+
break
|
| 95 |
+
|
| 96 |
+
# Collect function calls from parts (the correct attribute is `function_call`)
|
| 97 |
+
tool_calls = []
|
| 98 |
+
for p in parts:
|
| 99 |
+
if getattr(p, "function_call", None):
|
| 100 |
+
# Each part may request one function_call
|
| 101 |
+
call = p.function_call
|
| 102 |
+
# call.name: str, call.args: dict
|
| 103 |
+
if hasattr(call, "name") and hasattr(call, "args"):
|
| 104 |
+
tool_calls.append(call)
|
| 105 |
+
|
| 106 |
+
# If the model didn't request any tool, we're done
|
| 107 |
+
if not tool_calls:
|
| 108 |
break
|
| 109 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
tool_responses = []
|
| 111 |
+
|
| 112 |
for call in tool_calls:
|
| 113 |
if call.name == "get_train_connections":
|
| 114 |
+
start_loc = call.args.get("start_loc", "")
|
| 115 |
+
dest_loc = call.args.get("dest_loc", "")
|
| 116 |
+
yield f"π Fetching train data: **{start_loc}** β **{dest_loc}**...", ""
|
| 117 |
+
|
| 118 |
+
# Call the MCP tool
|
| 119 |
+
train_data = await call_mcp_tool(start_loc, dest_loc)
|
| 120 |
+
|
| 121 |
+
# Return the tool function result to the model
|
| 122 |
+
tool_responses.append(
|
| 123 |
+
types.Part.from_function_response(
|
| 124 |
+
name=call.name,
|
| 125 |
+
response={"result": train_data},
|
| 126 |
+
)
|
| 127 |
+
)
|
| 128 |
+
else:
|
| 129 |
+
# Unknown tool β let the model know it failed
|
| 130 |
tool_responses.append(
|
| 131 |
types.Part.from_function_response(
|
| 132 |
name=call.name,
|
| 133 |
+
response={
|
| 134 |
+
"error": f"Unknown tool '{call.name}'. Only 'get_train_connections' is supported."
|
| 135 |
+
},
|
| 136 |
)
|
| 137 |
)
|
| 138 |
+
|
| 139 |
if tool_responses:
|
| 140 |
yield "π Finalizing response...", ""
|
| 141 |
+
# Provide tool results back to the model (to let it compose the final answer)
|
| 142 |
response = await chat.send_message(tool_responses)
|
| 143 |
else:
|
| 144 |
break
|
| 145 |
|
| 146 |
+
# Prefer the convenience .text; fallback to concatenating text parts
|
| 147 |
+
final_text = getattr(response, "text", "") or ""
|
| 148 |
+
if not final_text and response.candidates:
|
| 149 |
+
parts = getattr(response.candidates[0].content, "parts", [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
|
| 152 |
"""
|