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)

输出结果:

相关推荐
zzwq.2 分钟前
时间序列处理:日期解析与重采样
python·数据分析
DS数模9 分钟前
2026年Mathorcup数学建模竞赛A题思路解析+代码+论文
开发语言·数学建模·matlab·mathorcup·妈妈杯·2026妈妈杯
Wyz2012102412 分钟前
SQL中如何处理GROUP BY的不可排序问题_ORDERBY与聚合
jvm·数据库·python
叶子野格13 分钟前
《C语言学习:编程例题》8
c语言·开发语言·c++·学习·算法·visual studio
Java面试题总结14 分钟前
Python 入门(四)- Openpyxl 操作 Excel 教程
开发语言·python·excel
Polar__Star18 分钟前
jsoup如何读取html
jvm·数据库·python
smj2302_7968265219 分钟前
解决leetcode第3901题好子序列查询
python·算法·leetcode
gCode Teacher 格码致知20 分钟前
Javascript提高:Math.round 详解-由Deepseek产生
开发语言·javascript
a95114164221 分钟前
怎么防范通过phpMyAdmin上传WebShell_禁止into outfile权限
jvm·数据库·python
2401_8858850422 分钟前
群发彩信接口怎么开发?企业级彩信发送说明
前端·python