要在Django
应用程序中接入ChatGPT
并使用中文,你可以按照以下步骤进行操作:
1.确保你已经安装了OpenAI
的openai
库。可以使用以下命令进行安装:
pip install openai
2.在Django项目的根目录下创建一个名为chatgpt.py
的文件,并将以下代码添加到文件中:
import openai
# 设置OpenAI的API密钥
openai.api_key = 'YOUR_API_KEY'
def generate_response(message):
# ChatGPT的调用参数
model = 'gpt-3.5-turbo'
prompt = 'User: {}\nAI:'.format(message)
max_tokens = 50
# 调用ChatGPT生成回复
response = openai.Completion.create(
engine=model,
prompt=prompt,
max_tokens=max_tokens,
n=1,
stop=None,
temperature=0.7
)
# 提取回复内容
reply = response.choices[0].text.strip().split('AI: ')[1]
return reply
请确保将YOUR_API_KEY
替换为你的OpenAI API
密钥。
3.在Django应用程序中的视图中,调用chatgpt.py
中的generate_response
函数来获取ChatGPT的回复。
假设你有一个名为chat的视图,可以按照以下方式进行操作:
from django.shortcuts import render
from .chatgpt import generate_response
def chat(request):
if request.method == 'POST':
message = request.POST['message']
reply = generate_response(message)
return render(request, 'chat.html', {'reply': reply})
return render(request, 'chat.html')
这个视图接收POST
请求,获取用户的消息(在表单中名为message
),然后调用generate_response
函数来获取ChatGPT
的回复。
最后,将回复传递给模板进行渲染。
4.创建一个名为chat.html的模板文件,并将以下代码添加到文件中:
<h1>Chat with AI</h1>
<form method="post" action="{% url 'chat' %}">
{% csrf_token %}
<input type="text" name="message" placeholder="Your message">
<button type="submit">Send</button>
</form>
{% if reply %}
<p><strong>AI:</strong> {{ reply }}</p>
{% endif %}
在这个模板中,用户可以在文本框中输入消息,点击发送按钮后,表单将以POST方式提交到chat视图。如果有回复,则将回复显示在页面上。
5.最后,确保在urls.py
文件中定义了正确的URL路由:
from django.urls import path
from .views import chat
urlpatterns = [
path('chat/', chat, name='chat'),
]
这将为/chat/
路径映射到chat
视图。
现在你的Django应用程序已经接入了Chat
附加内容
如果你想继续实现一个持续的对话流程,可以通过在会话期间保持上下文来完成。下面是一个示例,展示如何在Django应用程序中实现连续的对话:
1.在chatgpt.py
中,添加一个全局变量来存储会话上下文:
conversation_history = []
2.修改generate_response
函数,以便在每次调用时将会话历史传递给ChatGPT:
def generate_response(message):
# 将会话历史与用户消息合并
user_message = 'User: {}'.format(message)
conversation = conversation_history + [user_message]
# ChatGPT的调用参数
model = 'gpt-3.5-turbo'
prompt = '\n'.join(conversation)
max_tokens = 50
# 调用ChatGPT生成回复
response = openai.Completion.create(
engine=model,
prompt=prompt,
max_tokens=max_tokens,
n=1,
stop=None,
temperature=0.7
)
# 提取回复内容
reply = response.choices[0].text.strip().split('AI: ')[1]
# 将用户消息和回复添加到会话历史
conversation_history.append(user_message)
conversation_history.append('AI: {}'.format(reply))
return reply
3.在chat
视图中,检查用户是否点击了重置按钮,并在重置会话时清空会话历史:
def chat(request):
if request.method == 'POST':
if 'reset' in request.POST:
# 重置会话
conversation_history.clear()
return render(request, 'chat.html')
message = request.POST['message']
reply = generate_response(message)
return render(request, 'chat.html', {'reply': reply})
return render(request, 'chat.html')
在上述代码中,我们添加了一个检查,如果用户点击了名为reset
的按钮,则会话历史会被清空,从而重置会话。
4.修改chat.html
模板,以添加一个重置按钮:
<h1>Chat with AI</h1>
<form method="post" action="{% url 'chat' %}">
{% csrf_token %}
<input type="text" name="message" placeholder="Your message">
<button type="submit">Send</button>
<button type="submit" name="reset" value="true">Reset</button>
</form>
{% if reply %}
<p><strong>AI:</strong> {{ reply }}</p>
{% endif %}
这个模板中,我们添加了一个名为reset
的按钮,当用户点击该按钮时,会将reset
的值设置为true
,并将其提交到chat视图,从而触发会话重置。
现在你的Django
应用程序可以进行连续的对话,并且会话历史会被保留,以实现更自然的交互体验。