sidthephysicskid commited on
Commit
4637859
·
verified ·
1 Parent(s): edf5133

create app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ import gradio as gr
3
+ import os, json
4
+ # Attempt to load configuration from config.json
5
+ try:
6
+ with open('config.json') as config_file:
7
+ config = json.load(config_file)
8
+ OPENAI_API_KEY = config.get("OPENAI_API_KEY")
9
+ SYSTEM_PROMPT = config.get("SYSTEM_PROMPT")
10
+ except FileNotFoundError:
11
+ # If config.json is not found, fall back to environment variables
12
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
13
+ SYSTEM_PROMPT = os.getenv("SYSTEM_PROMPT")
14
+
15
+ # Fallback to default values if necessary
16
+ if not OPENAI_API_KEY:
17
+ raise ValueError("OPENAI_API_KEY is not set in config.json or as an environment variable.")
18
+ if not SYSTEM_PROMPT:
19
+ SYSTEM_PROMPT = "This is a default system prompt."
20
+
21
+ client = OpenAI(api_key=OPENAI_API_KEY)
22
+
23
+ system_prompt = {
24
+ "role": "system",
25
+ "content": SYSTEM_PROMPT
26
+ }
27
+
28
+
29
+ MODEL = "gpt-3.5-turbo"
30
+
31
+ def predict(message, history):
32
+ history_openai_format = [system_prompt]
33
+ for human, assistant in history:
34
+ history_openai_format.append({"role": "user", "content": human })
35
+ history_openai_format.append({"role": "assistant", "content":assistant})
36
+ history_openai_format.append({"role": "user", "content": message})
37
+
38
+ response = client.chat.completions.create(model=MODEL,
39
+ messages= history_openai_format,
40
+ temperature=1.0,
41
+ stream=True)
42
+
43
+ partial_message = ""
44
+ for chunk in response:
45
+ if chunk.choices[0].delta.content:
46
+ partial_message = partial_message + chunk.choices[0].delta.content
47
+ yield partial_message
48
+
49
+ gr.ChatInterface(predict).launch(share=True)