Alexander Hux commited on
Commit
9d39c38
·
verified ·
1 Parent(s): d92d124

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -17
app.py CHANGED
@@ -1,30 +1,27 @@
1
  import gradio as gr
2
- import requests
3
  import os
 
4
 
5
- # Retrieve the API key from the environment variables
 
 
 
6
  API_KEY = os.getenv("OPENAI_API_KEY")
7
- API_URL = "https://api.openai.com/v1/chat/completions"
8
 
9
- # Function to call the OpenAI API
10
  def chat_with_model(prompt):
11
  if not API_KEY:
12
  return "Error: API key not found. Please set it in the environment variables."
13
 
14
- headers = {
15
- "Content-Type": "application/json",
16
- "Authorization": f"Bearer {API_KEY}"
17
- }
18
- payload = {
19
- "model": "gpt-4", # Replace with your desired model (e.g., gpt-3.5-turbo, gpt-4)
20
- "messages": [{"role": "user", "content": prompt}]
21
- }
22
-
23
  try:
24
- response = requests.post(API_URL, json=payload, headers=headers)
25
- response.raise_for_status()
26
- return response.json()["choices"][0]["message"]["content"]
27
- except requests.exceptions.RequestException as e:
 
 
28
  return f"Error: {str(e)}"
29
 
30
  # Gradio Interface
 
1
  import gradio as gr
2
+ import openai
3
  import os
4
+ from dotenv import load_dotenv
5
 
6
+ # Load environment variables from .env file
7
+ load_dotenv()
8
+
9
+ # Get the API key from the environment variable
10
  API_KEY = os.getenv("OPENAI_API_KEY")
11
+ openai.api_key = API_KEY
12
 
13
+ # Function to interact with OpenAI API
14
  def chat_with_model(prompt):
15
  if not API_KEY:
16
  return "Error: API key not found. Please set it in the environment variables."
17
 
 
 
 
 
 
 
 
 
 
18
  try:
19
+ response = openai.ChatCompletion.create(
20
+ model="gpt-4", # Replace with your desired model
21
+ messages=[{"role": "user", "content": prompt}]
22
+ )
23
+ return response["choices"][0]["message"]["content"]
24
+ except openai.error.OpenAIError as e:
25
  return f"Error: {str(e)}"
26
 
27
  # Gradio Interface