python调用硅基流动的视觉语言模型

参考: https://docs.siliconflow.cn/cn/userguide/capabilities/vision   

import base64
import json
from openai import OpenAI
from PIL import Image
import io

# 初始化OpenAI客户端
client = OpenAI(
    api_key="sk-**********",  # 替换为实际API密钥
    base_url="https://api.siliconflow.cn/v1"
)

def convert_image_to_webp_base64(input_image_path: str) -> str:
    """将本地图片转换为WebP格式的Base64字符串"""
    try:
        with Image.open(input_image_path) as img:
            # 转换为WebP格式(优化大小)
            byte_arr = io.BytesIO()
            img.save(byte_arr, format='WEBP', quality=85)  # 调整质量平衡大小和清晰度
            byte_arr = byte_arr.getvalue()
            return base64.b64encode(byte_arr).decode('utf-8')
    except Exception as e:
        print(f"图片转换错误: {e}")
        return None

# 1. 转换本地图片
input_image_path = "7125e2e3.jpeg"  # 替换为实际图片路径
base64_image = convert_image_to_webp_base64(input_image_path)

if not base64_image:
    print("图片转换失败,请检查路径和格式")
    exit()

# 2. 创建流式请求
response = client.chat.completions.create(
    model="Qwen/Qwen2.5-VL-72B-Instruct",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/webp;base64,{base64_image}",  # 指定WebP格式
                        "detail": "high"  # 平衡速度与精度
                    }
                },
                {
                    "type": "text",
                    "text": "使用ocr识别图片内容并输出"  # 替换为你的提示词
                }
            ]
        }
    ],
    stream=True,
    max_tokens=1000  # 控制响应长度
)

# 3. 流式处理响应
print("模型响应:")
full_response = ""
for chunk in response:
    if chunk.choices[0].delta.content:
        text_chunk = chunk.choices[0].delta.content
        print(text_chunk, end='', flush=True)
        full_response += text_chunk

print("\n\n完整响应已接收")

### 如何使用Python调用流动模型 API 为了使用 Python 调用流动模型API,可以遵循以下方法构建请求并处理响应。此过程涉及设置必要的库、配置请求参数以及解析返回的数据。 #### 安装依赖库 首先需要安装 `requests` 库来发送 HTTP 请求: ```bash pip install requests ``` #### 构建API请求 下面是一个完整的 Python 示例代码片段,展示了如何向流动模型工作流应用平台发起 POST 请求以利用其服务功能[^3]: ```python import requests import json # 设置请求的目标 URL 和必需的身份验证信息 url = "https://siliconcloud.example.com/api/v1/models/generate" api_key = "your_api_key_here" headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json' } payload = { "prompt": "Explain the concept of artificial intelligence.", "max_tokens": 50, "temperature": 0.7 } response = requests.post(url, headers=headers, data=json.dumps(payload)) if response.status_code == 200: result = response.json() generated_text = result.get('choices', [{}])[0].get('text') print(generated_text) else: error_message = response.text or "Unknown Error" print(f"Failed to generate text: {error_message}") ``` 这段脚本定义了一个简单的接口交互流程,其中包含了创建HTTP头部、准备负载数据结构体以及执行POST操作的具体细节。注意这里的URL应替换为实际的服务端点地址,并且API密钥需由用户提供自己的有效凭证。 此外,在某些情况下可能还需要调整 payload 中其他参数(如 max_tokens 或 temperature),具体取决于所使用的特定模型和服务文档的要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值