Chat_Gpt API调用上传图片示例

一、API调用现状

跟据https://platform.openai.com/docs/api-reference/chat/create所述,我们可以通过API调用其多模态大模型,而目前国内支持多模态API调用的几乎没有。所以本文后续提供一个通过API调用GPT-4o模型,进行多模态(图片)交互的示例。

二、获取图片的URL

由于openai的官方文档中对图片参数的需求是统一资源定位符(URL),我们需要先将自己本地的图片通过一定方式转换成URL,这里我使用的是sm.ms图床,它提供5GB的免费空间,且它还支持API调用,我们可以通过API调用批量提交图片获取其对应的URL,具体操作流程参考【python】调用sm.ms图床api接口,实现上传图片并返回url_smms图床网页接口-CSDN博客

三 、调用CHAT_Gpt API

首先拿到自己的API_KEY,将自己的API_KEY替换掉YOUR_API_KEY,点击运行就能与GPT-4o进行多模态的交互啦

import requests

def chat_with_gpt(prompt,img_url):
    api_key = "YOUR_API_KEY"
    model = "gpt-4o"
    url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": model,
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url":img_url
                        }
                    }
                ]
            },
            {
                "role": "system",
                "content": [
                    {
                        "type": "text",
                        "text": prompt
                    }
                ]
            } 
        ]
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        response_data = response.json()
        return response_data['choices'][0]['message']['content']

    else:
        return f"Error: {response.status_code}, {response.text}"

if __name__=="__main":
    img_url="https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"
    prompt="图片里面有什么"
    response = chat_with_gpt(prompt,img_url) 
    print(response)

    #response=这张图片展示了一位坐在沙滩上的女性和她的狗狗。她们正在互动,狗狗举起一只前爪,她伸出手与狗狗互动。背景是一个波光粼粼的大海,天空是明亮的日落时分,整个场景显得温馨而美好。

050a294c37cd48789d7cd1c225916980.jpeg

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值