1 Star 0 Fork 0

yuyangup/ComfyUI-IF_AI_tools

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
openai_api.py 2.78 KB
一键复制 编辑 原始数据 按行查看 历史
ImpactFrames 提交于 2024-06-10 01:29 . Add files via upload
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
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuyangup/ComfyUI-IF_AI_tools.git
git@gitee.com:yuyangup/ComfyUI-IF_AI_tools.git
yuyangup
ComfyUI-IF_AI_tools
ComfyUI-IF_AI_tools
IF_AI_tools_RAG_linux_mac

搜索帮助

0d507c66 1850385 C8b1a773 1850385