代码拉取完成,页面将自动刷新
import requests
def send_openai_request(base64_image, model, system_message, user_message, messages, api_key,
seed, temperature, max_tokens, top_p, repeat_penalty):
openai_headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
data = {
"model": model,
"messages": prepare_openai_messages(base64_image, system_message, user_message, messages),
"temperature": temperature,
"max_tokens": max_tokens,
"presence_penalty": repeat_penalty,
"top_p": top_p,
"seed": seed
}
api_url = 'https://api.openai.com/v1/chat/completions'
response = requests.post(api_url, headers=openai_headers, json=data)
if response.status_code == 200:
response_data = response.json()
choices = response_data.get('choices', [])
if choices:
choice = choices[0]
message = choice.get('message', {})
generated_text = message.get('content', '')
return generated_text
else:
print("No valid choices in the response.")
print("Full response:", response.text)
return "No valid response generated."
else:
print(f"Failed to fetch response, status code: {response.status_code}")
print("Full response:", response.text)
return "Failed to fetch response from OpenAI."
def prepare_openai_messages(base64_image, system_message, user_message, messages):
openai_messages = [
{"role": "system", "content": system_message},
{"role": "user", "content": user_message}
]
for message in messages:
role = message["role"]
content = message["content"]
if role == "system":
openai_messages.append({"role": "system", "content": content})
elif role == "user":
if base64_image:
openai_messages.append({
"role": "user",
"content": [
{
"type": "text",
"text": content
},
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64," + base64_image,
"data": base64_image
}
}
]
})
else:
openai_messages.append({"role": "user", "content": content})
elif role == "assistant":
openai_messages.append({"role": "assistant", "content": content})
return openai_messages
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。