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)

输出结果:

相关推荐
如烟花的信页1 分钟前
易盾滑块逆向分析
javascript·爬虫·python·js逆向
曾几何时`9 分钟前
Go(四)Channel
开发语言·后端·golang
常常有12 分钟前
Redis:哨兵模式 (Sentinel)
redis·python·sentinel
未若君雅裁16 分钟前
Java 线程基础:进程、线程、并发并行、创建方式与生命周期
java·开发语言
sugar__salt18 分钟前
JS正则表达式与字符串高阶实战精讲
开发语言·javascript·正则表达式
程序员三藏20 分钟前
接口测试用例设计
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
AI浩22 分钟前
梯度累积与 Micro-Batch 设计分层式精讲:有效批次、显存边界与分布式同步
开发语言·分布式·batch
未若君雅裁25 分钟前
死锁产生条件与诊断:jps、jstack、VisualVM
java·开发语言
再玩一会儿看代码25 分钟前
Java抽象类和接口区别_场景理解
java·开发语言·经验分享·笔记·python
大蚂蚁2号26 分钟前
Python迭代器与生成器深度剖析:从底层协议到工程实战
python