Update app.py
Browse files
app.py
CHANGED
|
@@ -1,67 +1,21 @@
|
|
| 1 |
-
# Change the function to be async
|
| 2 |
async def generate(input_text):
|
| 3 |
if not GEMINI_API_KEY:
|
| 4 |
-
yield "Error: GEMINI_API_KEY is not set."
|
| 5 |
-
return
|
| 6 |
|
| 7 |
-
|
| 8 |
-
model_id = "gemini-3-flash-preview"
|
| 9 |
-
|
| 10 |
-
train_tool = types.Tool(
|
| 11 |
-
function_declarations=[
|
| 12 |
-
types.FunctionDeclaration(
|
| 13 |
-
name="get_train_connections",
|
| 14 |
-
description="Finds live train connections between two German stations.",
|
| 15 |
-
parameters={
|
| 16 |
-
"type": "OBJECT",
|
| 17 |
-
"properties": {
|
| 18 |
-
"start_loc": {"type": "STRING", "description": "Departure city"},
|
| 19 |
-
"dest_loc": {"type": "STRING", "description": "Destination city"}
|
| 20 |
-
},
|
| 21 |
-
"required": ["start_loc", "dest_loc"]
|
| 22 |
-
}
|
| 23 |
-
)
|
| 24 |
-
]
|
| 25 |
-
)
|
| 26 |
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
response = await chat.send_message_async(input_text)
|
| 36 |
-
|
| 37 |
-
max_turns = 5
|
| 38 |
-
for _ in range(max_turns):
|
| 39 |
-
if not response.candidates[0].content.parts:
|
| 40 |
-
break
|
| 41 |
-
|
| 42 |
-
tool_calls = [p.tool_call for p in response.candidates[0].content.parts if p.tool_call]
|
| 43 |
-
if not tool_calls:
|
| 44 |
-
break
|
| 45 |
-
|
| 46 |
-
tool_responses = []
|
| 47 |
-
for call in tool_calls:
|
| 48 |
-
if call.name == "get_train_connections":
|
| 49 |
-
# Now we can simply await the tool call directly
|
| 50 |
-
train_data = await call_mcp_tool(call.args["start_loc"], call.args["dest_loc"])
|
| 51 |
-
|
| 52 |
-
tool_responses.append(
|
| 53 |
-
types.Part.from_function_response(
|
| 54 |
-
name=call.name,
|
| 55 |
-
response={"result": train_data}
|
| 56 |
-
)
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
if tool_responses:
|
| 60 |
-
response = await chat.send_message_async(tool_responses)
|
| 61 |
-
else:
|
| 62 |
-
break
|
| 63 |
|
| 64 |
-
|
|
|
|
| 65 |
|
| 66 |
except Exception as e:
|
| 67 |
-
|
|
|
|
|
|
|
| 1 |
async def generate(input_text):
|
| 2 |
if not GEMINI_API_KEY:
|
| 3 |
+
yield "Error: GEMINI_API_KEY is not set.", ""
|
| 4 |
+
return # Stops the generator
|
| 5 |
|
| 6 |
+
# ... (setup code) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
try:
|
| 9 |
+
yield "Thinking...", "" # UI update
|
| 10 |
+
|
| 11 |
+
# ... (logic loop) ...
|
| 12 |
+
|
| 13 |
+
if tool_calls:
|
| 14 |
+
yield "Fetching live train data from MCP server...", ""
|
| 15 |
+
# ... (execute tool) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Final result
|
| 18 |
+
yield response.text, ""
|
| 19 |
|
| 20 |
except Exception as e:
|
| 21 |
+
yield f"### Logic Error\n{str(e)}", ""
|