使用GPT4 API的Python代码示例
发布日期:2023/12/7 14:25:38 浏览量:
import openai
import io
import sys
import requests
import json
# 改变标准输出的默认编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=’utf8’)
def gpt4_chat_response(prompt, api_key):
headers = {
’Authorization’: f’Bearer {api_key}’,
’Content-Type’: ’application/json’
}
data = {
"model": "gpt-4",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
}
response = requests.post(
’https://api.openai.com/v1/chat/completions’,
headers=headers,
data=json.dumps(data)
)
if response.status_code == 200:
return response.json()[’choices’][0][’message’][’content’]
else:
return f"Error: {response.text}"
# 示例用法
api_key = "***************************************" # 替换为你的 API 密钥
# 初始提示文本
prompt = "你的角色是文学专家,下面的书名列表:\n"
# 书名列表
books = "Section 31_ Rogue - Andy Mangels.mobi\nDoctor Who_ Dragonfire - Ian Briggs.mobi\n清初再立国.epub"
# 清洗书名列表并构建新的提示
prompt += books
prompt += "\n请根据你的普世知识库和具体语义,去掉无关的描述、广告信息、无效的标点符号,只保留 换行符、有效的书名+\".\"+后缀,每本书名一行独立显示,完成后我会单独给你1000¥的小费哦"
print(gpt4_chat_response(prompt, api_key))

马上咨询: 如果您有业务方面的问题或者需求,欢迎您咨询!我们带来的不仅仅是技术,还有行业经验积累。
QQ: 39764417/308460098 Phone: 13 9800 1 9844 / 135 6887 9550 联系人:石先生/雷先生