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()