File size: 2,448 Bytes
ddeb907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()