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)

输出结果:

相关推荐
惊鸿一博29 分钟前
图标加载方式_zeroIcon_是否加前缀mdi
开发语言·前端·javascript
森G39 分钟前
TypeScript 基础类型
开发语言·typescript
huipeng9261 小时前
企业级微服务开发实战(一):项目启动与工程化设计
java·开发语言·spring boot·spring cloud·微服务·云原生·架构
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
java实现excel导入、下载模板方法
java·开发语言·excel
眠りたいです2 小时前
现代C++:C++14中的新语言特性和库特性
c语言·开发语言·c++
隔壁大炮2 小时前
MNE-Python 第9天学习笔记:源定位基础
python·eeg·mne·脑电数据处理
叶小鸡3 小时前
Java 篇-项目实战-AI 天机学堂(从 0 到 1)-day1
java·开发语言
Daydream.V3 小时前
Python Flask超全入门实战教程|从零基础到项目部署
大数据·python·flask
databook4 小时前
Manim物理模拟:别自己写欧拉了!
python·数学·动效
楼田莉子4 小时前
C++17新特性:__had_include/属性/求值顺序规则
开发语言·c++·后端