jsakshi commited on
Commit
f75b1ea
·
verified ·
1 Parent(s): 6a90857

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -27
app.py CHANGED
@@ -1,33 +1,41 @@
 
1
  import requests
2
  import gradio as gr
3
 
4
- # 🔑 Paste your OpenRouter API key here
5
- API_KEY = "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"
6
-
7
- if not API_KEY or API_KEY.startswith("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"):
8
- raise ValueError("Please paste your actual OpenRouter API key in API_KEY variable.")
9
 
10
  # OpenRouter API endpoint
11
  MODEL_URL = "https://openrouter.ai/api/v1/chat/completions"
12
 
13
  HEADERS = {
14
  "Authorization": f"Bearer {API_KEY}",
15
- "Content-Type": "application/json"
 
 
 
16
  }
17
 
18
  def query_gpt35(messages, max_tokens=500, temperature=0.7):
19
- """Send a list of messages to OpenRouter GPT-3.5-Turbo."""
 
 
 
20
  payload = {
21
  "model": "openai/gpt-3.5-turbo",
22
  "messages": messages,
23
  "max_tokens": max_tokens,
24
- "temperature": temperature
25
  }
26
 
27
  try:
28
  resp = requests.post(MODEL_URL, headers=HEADERS, json=payload, timeout=30)
29
  resp.raise_for_status()
30
  data = resp.json()
 
31
  return data["choices"][0]["message"]["content"].strip()
32
  except requests.exceptions.RequestException as e:
33
  return f"Error: Could not connect to the API - {e}"
@@ -35,39 +43,39 @@ def query_gpt35(messages, max_tokens=500, temperature=0.7):
35
  return "Error: Unexpected response format from API"
36
 
37
  def respond(user_message, chat_history):
38
- """Handles the chat flow in Gradio."""
 
 
 
 
 
39
  messages = [
40
- {"role": "system", "content": "You are LocoBot, a helpful assistant."}
41
  ]
42
-
 
43
  if chat_history:
44
  for user, bot in chat_history:
45
  messages.append({"role": "user", "content": user})
46
  messages.append({"role": "assistant", "content": bot})
47
-
 
48
  messages.append({"role": "user", "content": user_message})
 
49
  assistant_reply = query_gpt35(messages)
50
- return chat_history + [(user_message, assistant_reply)], ""
51
 
52
- css = """
53
- button {
54
- background-color: #007bff !important;
55
- color: white !important;
56
- border: none !important;
57
- padding: 10px 20px !important;
58
- border-radius: 5px !important;
59
- }
60
- button:hover {
61
- background-color: #0056b3 !important;
62
- }
63
- """
64
 
65
- with gr.Blocks(css=css) as demo:
66
- gr.Markdown("## LocoBot — Your AI Companion (via OpenRouter GPT-3.5 Turbo)")
 
67
  chatbot = gr.Chatbot()
68
  message = gr.Textbox(placeholder="Type your message and press Enter")
69
  send = gr.Button("Send")
70
 
 
71
  send.click(fn=respond, inputs=[message, chatbot], outputs=[chatbot, message])
72
  message.submit(fn=respond, inputs=[message, chatbot], outputs=[chatbot, message])
73
 
 
1
+ import os
2
  import requests
3
  import gradio as gr
4
 
5
+ # Set this environment variable before running:
6
+ # export OPENROUTER_API_KEY="your_openrouter_api_key_here"
7
+ API_KEY = os.getenv("Open_Router")
8
+ if not API_KEY:
9
+ raise ValueError("OPENROUTER_API_KEY not found. Please set it in your environment variables.")
10
 
11
  # OpenRouter API endpoint
12
  MODEL_URL = "https://openrouter.ai/api/v1/chat/completions"
13
 
14
  HEADERS = {
15
  "Authorization": f"Bearer {API_KEY}",
16
+ "Content-Type": "application/json",
17
+ # Optional headers:
18
+ # "HTTP-Referer": "https://your-app-url.com",
19
+ # "X-Title": "LocoBot"
20
  }
21
 
22
  def query_gpt35(messages, max_tokens=500, temperature=0.7):
23
+ """
24
+ Send a list of messages (OpenAI-style) to OpenRouter and return assistant text.
25
+ messages: [{"role":"system"/"user"/"assistant", "content": "..."} , ...]
26
+ """
27
  payload = {
28
  "model": "openai/gpt-3.5-turbo",
29
  "messages": messages,
30
  "max_tokens": max_tokens,
31
+ "temperature": temperature,
32
  }
33
 
34
  try:
35
  resp = requests.post(MODEL_URL, headers=HEADERS, json=payload, timeout=30)
36
  resp.raise_for_status()
37
  data = resp.json()
38
+ # OpenRouter's response format mirrors OpenAI ChatCompletion:
39
  return data["choices"][0]["message"]["content"].strip()
40
  except requests.exceptions.RequestException as e:
41
  return f"Error: Could not connect to the API - {e}"
 
43
  return "Error: Unexpected response format from API"
44
 
45
  def respond(user_message, chat_history):
46
+ """
47
+ Gradio will pass chat_history as a list of (user, bot) tuples.
48
+ We convert that to a messages list, append the new user message, query the model,
49
+ then append the assistant reply and return updated history.
50
+ """
51
+ # Start with a system prompt to constrain behavior
52
  messages = [
53
+ {"role": "system", "content": "You are LocoBot, a helpful assistant. Answer concisely and politely."}
54
  ]
55
+
56
+ # Recreate prior conversation
57
  if chat_history:
58
  for user, bot in chat_history:
59
  messages.append({"role": "user", "content": user})
60
  messages.append({"role": "assistant", "content": bot})
61
+
62
+ # Add current user message
63
  messages.append({"role": "user", "content": user_message})
64
+
65
  assistant_reply = query_gpt35(messages)
 
66
 
67
+ # Update history for Gradio (list of tuples)
68
+ new_history = chat_history + [(user_message, assistant_reply)]
69
+ return new_history, ""
 
 
 
 
 
 
 
 
 
70
 
71
+ # Build Gradio UI
72
+ with gr.Blocks() as demo:
73
+ gr.Markdown("## LocoBot — Your AI Companion (via OpenRouter GPT-3.5)")
74
  chatbot = gr.Chatbot()
75
  message = gr.Textbox(placeholder="Type your message and press Enter")
76
  send = gr.Button("Send")
77
 
78
+ # Hook up interactions
79
  send.click(fn=respond, inputs=[message, chatbot], outputs=[chatbot, message])
80
  message.submit(fn=respond, inputs=[message, chatbot], outputs=[chatbot, message])
81