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)

输出结果:

相关推荐
python在学ing16 小时前
Django框架学习笔记:从零基础到项目实战
数据库·python·django·sqlite
PAK向日葵16 小时前
从零实现 Python 虚拟机(二):S.A.A.U.S.O 的总体架构设计
c++·python
无限进步_16 小时前
【C++】weak_ptr、循环引用与线程安全
开发语言·数据结构·c++·算法·安全
程序员小远16 小时前
系统性能指标全解析
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·性能测试
菜菜的顾清寒16 小时前
力扣hot100(37)栈-有效的括号
java·开发语言
@我们的天空17 小时前
Claude Code + GLM-5 深度赋能测试:开发 8 大 Skill 构建 AI 测试助手集群
人工智能·python·测试工具·自动化·ai编程
Circ.17 小时前
Java 远程调用 NX 11 完整实战:参数读取、修改、STP 文件导出(附环境配置 + 源码)
java·开发语言·nx11
2401_8332693017 小时前
【无标题】
java·开发语言
宇宙realman_99917 小时前
420B污染度等级查询代码
java·开发语言·算法
小白学大数据17 小时前
Playwright 爬虫:Python 爬取 JS 渲染的 JSP 网站
开发语言·javascript·爬虫·python·数据分析