File size: 2,669 Bytes
b276454
11611dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import os
import google.generativeai as genai
from zoho_client_mcp import mcp # Import the MCP instance from our tools file

# --- 1. Gemini Client Initialization ---
# We configure the Gemini client directly in the app before launching the MCP.
# This assumes os.environ['GOOGLE_API_KEY'] is set in config.py.
def configure_gemini():
    """Initializes the Gemini client using the API key from environment variables."""
    try:
        genai.configure(api_key=os.environ.get('GOOGLE_API_KEY'))
        print("Gemini API configured successfully for conversational use.")
    except Exception as e:
        print(f"Error configuring Gemini API: {e}")

# --- 2. Gradio Chat Interface Definition ---
# This defines the web UI required for conversation and file uploads [3, 13, 16, 17].
def chat_interface():
    # Gradio's gr.ChatInterface is used to build a standard chat UI.
    # The submission logic is handled automatically by FastMCP when mcp_server=True is used.
    
    # The file input is added directly to allow attachments (images/PDFs) [13, 18].
    # Files uploaded here will be available to the 'process_document' tool [18].
    file_component = gr.File(label="Upload Image or PDF Document", type="filepath")

    # The gr.ChatInterface sets up the UI structure for the conversation.
    iface = gr.ChatInterface(
        # The function passed here is typically the conversational engine.
        # When mcp_server=True, the MCP framework handles the routing.
        fn=lambda msg, history: f"Thinking...", 
        chatbot=gr.Chatbot(height=400),
        textbox=gr.Textbox(placeholder="Ask me to create a contact, search records, or upload a document...", scale=7),
        theme="soft",
        title="Zoho CRM Agent (Gemini + FastMCP)",
        submit_btn="Send Command",
        clear_btn="Clear History",
        # We attach the file component to the interface so users can upload [3, 16].
        additional_inputs=[file_component] 
    )
    return iface

# --- 3. Server Launch ---

if __name__ == "__main__":
    # Ensure Gemini is ready [11, 19].
    configure_gemini()
    
    # Get the defined Gradio UI
    demo = chat_interface()
    
    # Launch the Gradio UI, instructing it to also start the FastMCP server [4].
    # Gradio automatically connects the UI to the running 'mcp' instance when mcp_server=True [3].
    print("Starting Gradio Web UI and FastMCP Server...")
    demo.launch(
        server_name="0.0.0.0", 
        server_port=7860,
        mcp_server=True,  # Crucial: Starts the FastMCP server instance 'mcp' [4].
        mcp=mcp            # Passes the specific FastMCP instance we defined [4].
    )