hit-cxf
2026-04-08 182ed0f585cef59a7058f332d7ecb70d747f4fed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# -*- coding: utf-8 -*-
"""
Google Gemini 多模态大模型 API 客户端 (OpenAI 兼容格式)
支持 gemini-2.5-flash-image, gemini-2.5-pro 等视觉模型
 
可用模型:
    - gemini-2.5-flash-image (性价比最高)
    - gemini-2.5-pro (效果最好)
    - gemini-3-pro-preview
    - gemini-3-pro-image-preview
"""
 
import os
import time
import base64
from openai import OpenAI
from typing import Dict, List, Optional
 
class GeminiVLClient:
    """
    Gemini VLM 客户端,使用 OpenAI 兼容格式调用
    """
    def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
        """
        Gemini 多模态客户端
        :param api_key: Gemini API Key
        :param base_url: 自定义 Base URL(可选,用于代理)
        """
        self.api_key = api_key or os.getenv("GEMINI_API_KEY")
        default_url = "http://35.164.11.19:3887/v1"
        self.base_url = base_url or os.getenv("GOOGLE_GEMINI_BASE_URL", default_url)
        if self.base_url and not self.base_url.endswith("/v1"):
            self.base_url = self.base_url.rstrip("/") + "/v1"
        self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
        self.max_attempts = 10
        self.max_tokens = 20000
 
    def _encode_image(self, image_path: str) -> str:
        """将本地图片编码为 base64"""
        abs_path = os.path.abspath(image_path)
        with open(abs_path, "rb") as f:
            return base64.b64encode(f.read()).decode("utf-8")
 
    def _get_mime_type(self, image_path: str) -> str:
        """根据文件扩展名获取 MIME 类型"""
        ext = os.path.splitext(image_path)[1].lower()
        mime_types = {
            ".jpg": "image/jpeg",
            ".jpeg": "image/jpeg",
            ".png": "image/png",
            ".webp": "image/webp",
            ".gif": "image/gif"
        }
        return mime_types.get(ext, "image/jpeg")
 
    def chat(self, text: str, images: List[str], model: str = "gemini-2.5-flash-image",
             parameters: Optional[Dict] = None) -> str:
        """
        使用 Gemini 进行多模态对话(文本+图片)
        :param text: 文本内容
        :param images: 图片路径列表(支持本地路径或URL)
        :param model: 模型名(如 gemini-2.5-flash-image, gemini-2.5-pro)
        :param parameters: 其他API参数
        :return: API响应内容
        """
        # 构建消息格式
        content: list = [{"type": "text", "text": text}]
 
        # 处理图片
        if images:
            for img_path in images:
                if img_path.startswith("data:"):
                    # Base64 数据 URL,直接使用
                    content.append({
                        "type": "image_url",
                        "image_url": {"url": img_path}
                    })
                elif img_path.startswith("http"):
                    # URL 图片
                    content.append({
                        "type": "image_url",
                        "image_url": {"url": img_path}
                    })
                else:
                    # 本地图片 - 转为 base64
                    mime_type = self._get_mime_type(img_path)
                    base64_data = self._encode_image(img_path)
                    data_url = f"data:{mime_type};base64,{base64_data}"
                    content.append({
                        "type": "image_url",
                        "image_url": {"url": data_url}
                    })
 
        messages = [{"role": "user", "content": content}]
 
        attempts = 0
        while attempts < self.max_attempts:
            try:
                # 直接使用模型名
                response = self.client.chat.completions.create(
                    model=model,
                    messages=messages,
                    max_tokens=self.max_tokens,
                    temperature=parameters.get("temperature", 0.7) if parameters else 0.7
                )
 
                if response.choices and len(response.choices) > 0:
                    return response.choices[0].message.content
 
            except Exception as e:
                print(f"GeminiVL 请求错误: {e}")
                attempts += 1
                if attempts < self.max_attempts:
                    time.sleep(10)
 
        raise Exception("GeminiVL: 达到最大重试次数,仍未获得有效响应。")
 
 
if __name__ == "__main__":
    import sys
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from config import Config
 
    # 支持的 VLM 模型列表
    MODELS = ["gemini-2.5-flash-image", "gemini-2.0-flash"]
 
    print("=== Gemini VL 多模态可用性测试 ===")
    api_key = Config.GEMINI_API_KEY
    if not api_key:
        print("✗ GEMINI_API_KEY 未设置,跳过")
        sys.exit(1)
    print(f"  API Key: {api_key[:6]}***")
    client = GeminiVLClient(api_key=api_key)
 
    # 测试图片(使用示例图片)
    img_path = ""
    if not os.path.exists(img_path):
        print(f"✗ 测试图片不存在: {img_path}")
        img_path = "backend/code/result/image/test_avail/test_input.png"
        if not os.path.exists(img_path):
            print("✗ 跳过图片测试(无测试图片)")
            sys.exit(0)
 
    text = "请描述这张图片的内容"
    print(f"\n[多模态] Prompt: {text}")
    print(f"  图片: {img_path}")
 
    for model in MODELS:
        print(f"\n--- 测试模型: {model} ---")
        t0 = time.time()
        try:
            result = client.chat(text=text, images=[img_path], model=model)
            elapsed = time.time() - t0
            if result:
                print(f"✓ 返回结果 ({elapsed:.1f}s): {result[:200]}")
            else:
                print(f"✗ 返回空结果 ({elapsed:.1f}s)")
        except Exception as e:
            print(f"✗ 失败: {e}")