File size: 4,487 Bytes
c49fc0c
 
 
 
 
ed0f938
 
c49fc0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import os
import requests
import gradio as gr

# Set your API keys
os.environ['XAI_API_KEY'] = 'xai-Gxw7oW4yR6Q6oTd0v9lDRLotXZQYJNz9YKlH7R6eMyTmqIV9h6uustEGZAaJEvGmewlwbUnM1jTX4chj'  # Replace with your actual xAI API key
os.environ['SPORTS_API_KEY'] = '21253d4ad8mshc858b5f3ba04919p1b5a03jsna381170f15fe'  # Replace with your sports data API key

# Initialize conversation history
conversation_history = []

def fetch_sports_scores(sport):
    """Fetches real-time sports scores for the specified sport."""
    url = f"https://api.sportsdata.io/v4/{sport}/scores"
    headers = {
        "User-Agent": "YourAppName",
        "Authorization": f"Bearer {os.environ['SPORTS_API_KEY']}"
    }
    
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()  # Return JSON data
    else:
        return f"Error fetching sports data: {response.text}"

def browse_web_page(url):
    """Simulated function to browse a web page."""
    return f"Browsing to {url}..."

def chat_with_bot(user_input):
    # Append user input to conversation history
    conversation_history.append({"role": "user", "content": user_input})

    url = "https://api.x.ai/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {os.environ['XAI_API_KEY']}"
    }
    
    messages = [{"role": "system", "content": "You are a helpful assistant."}] + \
               [{"role": msg["role"], "content": msg["content"]} for msg in conversation_history]

    data = {
        "messages": messages,
        "model": "grok-beta",
        "functions": [
            {
                "name": "fetch_sports_scores",
                "description": "Fetch real-time scores for a specific sport.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "sport": {
                            "type": "string",
                            "description": "The sport you want scores for.",
                            "example_value": "football",
                        },
                    },
                    "required": ["sport"],
                },
            },
            {
                "name": "browse_web_page",
                "description": "Browse a web page.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "url": {
                            "type": "string",
                            "description": "The URL of the web page to browse.",
                            "example_value": "https://example.com",
                        },
                    },
                    "required": ["url"],
                },
            },
        ],
        "stream": False,
        "temperature": 0.7
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        bot_response = response.json()['choices'][0]['message']
        
        # Check if there's a function call request
        if 'function_call' in bot_response:
            function_name = bot_response['function_call']['name']
            args = bot_response['function_call']['arguments']
            
            if function_name == 'fetch_sports_scores':
                sport = args.get('sport')
                result = fetch_sports_scores(sport)
                bot_response_content = str(result)
            elif function_name == 'browse_web_page':
                url = args.get('url')
                bot_response_content = browse_web_page(url)
            else:
                bot_response_content = bot_response['content']
        else:
            bot_response_content = bot_response['content']
        
        # Append bot response to conversation history
        conversation_history.append({"role": "assistant", "content": bot_response_content})
        
        # Format the chat history for display
        chat_display = "\n".join([f"{msg['role'].capitalize()}: {msg['content']}" for msg in conversation_history])
        
        return chat_display
    else:
        return f"Error: {response.text}"

# Create Gradio interface
iface = gr.Interface(
    fn=chat_with_bot,
    inputs="text",
    outputs="text",
    title="xAI Chatbot with Function Calling",
    description="Chat with Grok! Type your message below.",
)

# Launch the interface
if __name__ == "__main__":
    iface.launch()