Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI | |
| import gradio as gr | |
| import google.generativeai as genai | |
| from weather import get_current_weather | |
| import os | |
| import uvicorn | |
| import json | |
| app = FastAPI() | |
| genai.configure(api_key=os.getenv("GEMINI_API_KEY")) | |
| model = genai.GenerativeModel('gemini-pro') | |
| # Tools configuration | |
| tools = [ | |
| { | |
| "name": "get_current_weather", | |
| "description": "Get current weather information", | |
| "parameters": { | |
| "type": "object", | |
| "properties": { | |
| "location": { | |
| "type": "string", | |
| "description": "City name, e.g. Paris, France" | |
| } | |
| }, | |
| "required": ["location"] | |
| } | |
| } | |
| ] | |
| def execute_tool_call(tool_call): | |
| func_name = tool_call["name"] | |
| args = json.loads(tool_call["arguments"]) | |
| if func_name == "get_current_weather": | |
| return get_current_weather(args["location"]) | |
| else: | |
| return f"Error: Unknown function {func_name}" | |
| def process_message(message): | |
| # Generate tool use suggestions | |
| response = model.generate_content( | |
| f"Analyze if user needs weather info: {message}. Respond ONLY with JSON:" | |
| '{{"needs_weather": true|false, "location": "city"}}' | |
| ) | |
| try: | |
| analysis = json.loads(response.text) | |
| if analysis.get("needs_weather", False): | |
| location = analysis.get("location", "London") | |
| return get_current_weather(location) | |
| except: | |
| pass | |
| # Regular response | |
| chat = model.start_chat(history=[]) | |
| response = chat.send_message(message) | |
| return response.text | |
| # Gradio Interface with new message format | |
| with gr.Blocks() as demo: | |
| chatbot = gr.Chatbot(height=500, type="messages") | |
| msg = gr.Textbox(label="Message") | |
| clear = gr.Button("Clear") | |
| def respond(message, chat_history): | |
| bot_message = process_message(message) | |
| # Append user and bot messages | |
| chat_history.append({"role": "user", "content": message}) | |
| chat_history.append({"role": "assistant", "content": bot_message}) | |
| return "", chat_history | |
| msg.submit(respond, [msg, chatbot], [msg, chatbot]) | |
| clear.click(lambda: None, None, chatbot, queue=False) | |
| app = gr.mount_gradio_app(app, demo, path="/") | |
| if __name__ == "__main__": | |
| port = int(os.getenv("PORT", 8000)) | |
| uvicorn.run(app, host="0.0.0.0", port=port) |