Jack7510 commited on
Commit
1eda67b
·
1 Parent(s): 72de8a7

Update app.py

Browse files

add history log file

Files changed (1) hide show
  1. app.py +51 -21
app.py CHANGED
@@ -1,32 +1,62 @@
 
 
1
  import gradio as gr
2
  import openai
 
3
  import os
4
 
5
- # Set up the OpenAI API credentials
6
- # openai.api_key = os.environ["OPENAI_API_KEY"]
7
- openai.api_key = os.getenv("OPENAI_API_KEY")
8
- model = "gpt-3.5-turbo"
9
-
10
- # Define the chatbot function
11
- def chatbot(text):
12
 
13
- # Call OpenAI API to generate text completion
14
- completion = openai.ChatCompletion.create(model=model, messages=[{"role": "user", "content": text}])
15
-
16
- # Extract the generated response and return it
17
- return completion.choices[0].message.content
18
 
 
 
19
 
20
- def ask_gpt(prompt):
 
21
  try:
22
- completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}])
23
- return completion.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
24
  except openai.Error as e:
25
- return f"OpenAI API error: {e}"
26
-
27
 
28
- # Create the Gradio interface
29
- iface = gr.Interface(fn=ask_gpt, inputs="text", outputs="text", title="GPT-3.5 Turbo Chatbot")
 
 
 
 
 
 
 
 
 
 
30
 
31
- # Launch the interface
32
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # example of chat with openAI
2
+
3
  import gradio as gr
4
  import openai
5
+ import datetime
6
  import os
7
 
8
+ # openAI Python program guide
9
+ # https://github.com/openai/openai-python
 
 
 
 
 
10
 
11
+ # 设置 OpenAI API 密钥
12
+ openai.api_key = os.getenv("OPENAI_API_KEY")
13
+ MODEL = "gpt-3.5-turbo"
 
 
14
 
15
+ # 文件名
16
+ FILE_NAME = "chat_history.log"
17
 
18
+ # 定义对话函数
19
+ def chat(question):
20
  try:
21
+ # 发送 API 请求
22
+ completion = openai.ChatCompletion.create(
23
+ model=MODEL,
24
+ messages=[
25
+ {"role": "system", "content": "You are a helpful assistant."},
26
+ {"role": "user", "content": question},
27
+ ],
28
+ temperature=0.8,
29
+ )
30
+
31
+ response = completion.choices[0].message.content
32
+
33
  except openai.Error as e:
34
+ response = f"OpenAI API error: {e}"
 
35
 
36
+ # 获取当前日期和时间
37
+ now = datetime.datetime.now()
38
+
39
+ # 将日期和时间转换为字符串格式
40
+ date_string = now.strftime('%Y-%m-%d %H:%M:%S')
41
+
42
+ # 将提问和回答保存到聊天历史记录中
43
+ # 打开文件进行追加
44
+ with open(FILE_NAME, 'a') as f:
45
+ f.write(f'\n{date_string}\n')
46
+ f.write('You: ' + question + '\n')
47
+ f.write('chatGPT: ' + response + '\n')
48
 
49
+ return response
50
+
51
+
52
+ if __name__ == '__main__':
53
+ # 创建 Gradio 应用程序界面
54
+ iface = gr.Interface(
55
+ fn=chat,
56
+ inputs="text",
57
+ outputs='text',
58
+ title="Chat with OpenAI 3.5",
59
+ #description="Talk to an AI powered by OpenAI's GPT language model.",
60
+ )
61
+
62
+ iface.launch(share=True)