2025-06-13【api】阿里百炼api调用方法

在这里插入图片描述
在这里插入图片描述

通过调用各种大模型可以完成对文生文,文生图,图片理解,文生视频,音频识别,文转音频等需求。

#方法一
import os
from openai import OpenAI

# 初始化客户端
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

# 构造请求
completion = client.chat.completions.create(
    model="qwen-vl-max-latest",  # 使用支持图像理解的模型
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": "https://wx3.sinaimg.cn/mw690/006i0nC8ly1hss7s32z03j31da2yo1is.jpg"}},
                {"type": "text", "text": "用20个字左右来描写图片里的内容"},
            ],
        }
    ],
)

# 输出结果
print(completion.choices[0].message.content)


#方法二
from openai import OpenAI

# 初始化客户端(直接写入API_KEY)
client = OpenAI(
    api_key="替换为你的实际API_KEY", 
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

# 构造请求
completion = client.chat.completions.create(
    model="qwen-vl-max-latest",  # 使用支持图像理解的模型
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": "https://wx3.sinaimg.cn/mw690/006i0nC8ly1hss7s32z03j31da2yo1is.jpg"}},
                {"type": "text", "text": "用20个字左右来描写图片里的内容"},
            ],
        }
    ],
)

# 输出结果
print(completion.choices[0].message.content)

#方法三 识别本地图片
import base64
from openai import OpenAI

def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

client = OpenAI(
    api_key="your-api",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

base64_image = encode_image("1.jpg")


# 构造请求
completion = client.chat.completions.create(
    model="qwen-vl-max-latest",  # 使用支持图像理解的模型
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{base64_image}"  # 指定图片格式(如 jpeg/png)
                    },
                },
                {"type": "text", "text": "什么风格的室内设计"},
            ],
        }
    ],
)

# 输出结果
print(completion.choices[0].message.content)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值