admin管理员组文章数量:1631719
chatgpt真是极大提高了开发的效率,现在完全离不开了,只要提出你要的需求,很快就生成你想要的代码,几乎不用修改。
比如提出“设你是python开发工程师,通过chapgpt的api实现在一个页面里输入内容并返回结果”,立即如下生成了代码:
import openai
# OpenAI API 需要一个密钥
openai.api_key = 'your-api-key'
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": input_content}
]
)
# 输出模型的回复
print(response['choices'][0]['message']['content'])
有基本的注释,并给出了对代码的解释:
这个代码将打开一个与ChatGPT的会话,并将
input_content
作为输入。模型的回复可以在响应的'choices'
字段中找到。需要注意的是,你需要将
'your-api-key'
替换为你自己的OpenAI API密钥。你可以在OpenAI的网站上创建一个新的API密钥。
实际上我需要的是一个web页面,能够输入提问,并在页面上返回内容,上面的代码时不满足的。于是接着提问“需要利用flask,有一个专门输入内容和返回内容的对话页面”,立即就把python部分和html的代码都输出了。
from flask import Flask, request, render_template
import openai
app = Flask(__name__)
# OpenAI API 需要一个密钥
openai.api_key = 'your-api-key'
@app.route('/', methods=['GET', 'POST'])
def chat():
if request.method == 'GET':
return render_template('chat.html')
if request.method == 'POST':
user_input = request.form['user_input']
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_input}
]
)
gpt_response = response['choices'][0]['message']['content']
return render_template('chat.html', user_input=user_input, gpt_response=gpt_response)
if __name__ == "__main__":
app.run(port=5000, debug=True)
<!DOCTYPE html>
<html>
<head>
<title>Chat with GPT</title>
</head>
<body>
<h1>Chat with GPT</h1>
<form method="POST">
<label for="user_input">You:</label>
<br>
<input type="text" id="user_input" name="user_input" required>
<input type="submit" value="Submit">
</form>
{% if user_input %}
<p><strong>You:</strong> {{ user_input }}</p>
{% endif %}
{% if gpt_response %}
<p><strong>GPT:</strong> {{ gpt_response }}</p>
{% endif %}
</body>
</html>
代码里只需输入chatgpt的apikey就能运行起来了。
页面其实挺丑的,其实可以进一步对页面美好提出要求,chatgpt也可以根据你的要求不断修正。
版权声明:本文标题:用chatgpt设计调用chatgpt的api进行内容交互 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1729102961a1186741.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论