SAKChatBot / app.py
Vamshiboss8055's picture
Rename gradio_app.py to app.py
abf444a verified
import gradio as gr
import requests
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# OpenRouter API Configuration
API_KEY = "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"
BASE_URL = "https://openrouter.ai/api/v1/chat/completions"
MODEL = "arcee-ai/trinity-large-preview:free"
def get_ai_response(user_message, history):
"""Get response from OpenRouter API"""
try:
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# Build messages from history
messages = [{"role": "system", "content": "You are a helpful chatbot. Provide concise and helpful responses."}]
# Add history - handle different formats safely
if history:
for item in history:
if isinstance(item, (list, tuple)) and len(item) >= 2:
messages.append({"role": "user", "content": item[0]})
if item[1]: # Only add if assistant response exists
messages.append({"role": "assistant", "content": item[1]})
messages.append({"role": "user", "content": user_message})
payload = {
"model": MODEL,
"messages": messages,
"temperature": 0.7,
"max_tokens": 500
}
response = requests.post(BASE_URL, headers=headers, json=payload, timeout=10)
response.raise_for_status()
data = response.json()
if "choices" in data and len(data["choices"]) > 0:
return data["choices"][0]["message"]["content"]
else:
return "I apologize, but I couldn't generate a response. Please try again."
except Exception as e:
logger.error(f"API Error: {str(e)}")
return f"Error: {str(e)}"
def chat(user_message, history):
"""Main chat function"""
if not user_message.strip():
return ""
# Get AI response
bot_response = get_ai_response(user_message, history)
return bot_response
# Create the Gradio interface
demo = gr.ChatInterface(
chat,
examples=["Hello"],
title="SAK Informatics Chatbot By Namani Vamshi Krishna",
description="Chat with an AI assistant",
)
if __name__ == "__main__":
demo.launch()