File size: 1,564 Bytes
1eda67b
 
f1667c0
1756b81
1eda67b
1756b81
f1667c0
1eda67b
 
54fb2a7
1eda67b
 
 
1756b81
1eda67b
 
72de8a7
1eda67b
 
72de8a7
1eda67b
 
 
 
 
 
 
 
 
 
 
 
72de8a7
1eda67b
72de8a7
1eda67b
 
 
 
 
 
 
 
 
 
 
 
1756b81
1eda67b
 
 
 
 
 
 
 
 
 
 
 
 
0f952a8
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
# example of chat with openAI

import gradio as gr
import openai
import datetime
import os

# openAI Python program guide
# https://github.com/openai/openai-python

# 设置 OpenAI API 密钥
openai.api_key = os.getenv("OPENAI_API_KEY")
MODEL = "gpt-3.5-turbo"

# 文件名
FILE_NAME = "chat_history.log"

# 定义对话函数
def chat(question):
    try:
        # 发送 API 请求
        completion = openai.ChatCompletion.create(
            model=MODEL, 
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": question},
            ],
            temperature=0.8,
            )

        response = completion.choices[0].message.content
    
    except openai.Error as e:
        response = f"OpenAI API error: {e}"
    
    # 获取当前日期和时间
    now = datetime.datetime.now()

    # 将日期和时间转换为字符串格式
    date_string = now.strftime('%Y-%m-%d %H:%M:%S')

    # 将提问和回答保存到聊天历史记录中
    # 打开文件进行追加
    with open(FILE_NAME, 'a') as f:
        f.write(f'\n{date_string}\n')
        f.write('You: ' + question + '\n')
        f.write('chatGPT: ' + response + '\n')

    return response


if __name__ == '__main__':
    # 创建 Gradio 应用程序界面
    iface = gr.Interface(
        fn=chat,
        inputs="text",
        outputs='text',
        title="Chat with OpenAI 3.5",
        #description="Talk to an AI powered by OpenAI's GPT language model.",
    )
    
    iface.launch()