gpt-4o看图说话-根据图片回答问题

问题:中国的人口老龄化究竟有多严重?

代码下实现如下:(直接调用openai的chat接口)

import os

import base64

import requests

def encode_image(image_path):

"""

对图片文件进行 Base64 编码

输入:

  • image_path:图片的文件路径

输出:

  • 编码后的 Base64 字符串

"""

二进制读取模式打开图片文件,

with open(image_path, "rb") as image_file:

将编码后的字节串解码为 UTF-8 字符串,以便于在文本环境中使用。

return base64.b64encode(image_file.read()).decode("utf-8")

中文 Prompt 指令

question = "中国的人口老龄化究竟有多严重?"

prompt = (

f"你的任务是根据图片回答问题,{question}详细回答。"

)

对本地多张图片进行 Base64 编码

images = os.listdir("./images")

images.sort()

images.remove('.ipynb_checkpoints')

print(images)

base64_images = [encode_image("./images/" + image) for image in images]

组织用户消息

user_content = [{"type": "text", "text": prompt}]

base64_images = [

{

"type": "image_url",

"image_url": {

"url": f"data:image/jpeg;base64,{base64_image}",

"detail": "high",

},

}

for base64_image in base64_images

]

user_content.extend(base64_images)

messages_template = [{"role": "user", "content": user_content}]

构造请求参数

payload = {

"model": "gpt-4o",

"messages": messages_template,

"max_tokens": 1600,

"temperature": 0,

"seed": 2024,

}

OpenAI API Key

api_key = "sk-xxx"

请求头

headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}

发送 POST 请求

response = requests.post(

"https://api.openai.com/v1/chat/completions",

headers=headers, json=payload

)

打印生成结果

print(response.json())

result = response.json()["choices"][0]["message"]["content"]

print(result)

输出结果:

相关推荐
小碗羊肉3 分钟前
【JavaWeb | 第七篇】部门管理项目实战
java·开发语言·servlet
维诺菌29 分钟前
claude code安装
java·开发语言·ai编程·calude
谙弆悕博士29 分钟前
快速学C语言—— 第0章:C语言简介
c语言·开发语言·经验分享·笔记·程序人生·课程设计·学习方法
构建的乐趣35 分钟前
测度(Measure)和概率测度(Probability Measure) 测度和度量的区别
python
顶点多余41 分钟前
自定义协议、序列化、反序列化实现
java·linux·开发语言·c++·tcp/ip
清水白石00843 分钟前
把事故变成护城河:如何设计回归测试,防止“订单重复创建”这类历史 Bug 卷土重来?
python·bug
狐狐生风1 小时前
LangGraph 工具调用集成
python·langchain·prompt·agent·langgraph
风味蘑菇干1 小时前
使用接口定义规范,实现类完成具体逻辑。
java·开发语言
MATLAB代码顾问1 小时前
【智能优化】无穷优化算法(INFO)原理与Python实现
开发语言·python·算法
2401_833269301 小时前
Java多线程:从入门到进阶
java·开发语言