Spaces:
Sleeping
Sleeping
# 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() | |