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)

输出结果:

相关推荐
Coder_Boy_6 分钟前
【物联网技术】- 基础理论-0001
java·python·物联网·iot
Jane-6667777 分钟前
C语言——表达式、语句、函数
c语言·开发语言·算法
arron88997 分钟前
C# 项目源码进行全面的技术架构和调用逻辑分析。以下是系统性的技术方案
开发语言·架构·c#
FY_201812 分钟前
SubprocVecEnv 原理、详细使用方法
人工智能·python·机器学习
czliutz13 分钟前
使用pdfplumber库处理pdf文件获取文本图片作者等信息
python·pdf
Sunhen_Qiletian15 分钟前
《Python开发之语言基础》第七集:库--时间库
前端·数据库·python
88号技师16 分钟前
【2025年1区SCI】最新信号分解方法-JMD的参数优化:15种适应度函数-matlab代码
开发语言·matlab·故障诊断·信号分解
zmzb010316 分钟前
C++课后习题训练记录Day44
开发语言·c++
smile_Iris17 分钟前
Day 30 函数定义与参数
开发语言·python
老华带你飞21 分钟前
医院挂号|基于Java医院挂号管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot