Spaces:
Sleeping
Sleeping
File size: 9,986 Bytes
f1b4581 |
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
import json
import os
import base64
from typing import Generator, Dict, Any, Optional, List
import google.generativeai as genai
from .base import BaseModel
class GoogleModel(BaseModel):
"""
Google Gemini API模型实现类
支持Gemini 2.5 Pro等模型,可处理文本和图像输入
"""
def __init__(self, api_key: str, temperature: float = 0.7, system_prompt: str = None, language: str = None, model_name: str = None, api_base_url: str = None):
"""
初始化Google模型
Args:
api_key: Google API密钥
temperature: 生成温度
system_prompt: 系统提示词
language: 首选语言
model_name: 指定具体模型名称,如不指定则使用默认值
api_base_url: API基础URL,用于设置自定义API端点
"""
super().__init__(api_key, temperature, system_prompt, language)
self.model_name = model_name or self.get_model_identifier()
self.max_tokens = 8192 # 默认最大输出token数
self.api_base_url = api_base_url
# 配置Google API
if api_base_url:
# 配置中转API - 使用环境变量方式
# 移除末尾的斜杠以避免重复路径问题
clean_base_url = api_base_url.rstrip('/')
# 设置环境变量来指定API端点
os.environ['GOOGLE_AI_API_ENDPOINT'] = clean_base_url
genai.configure(api_key=api_key)
else:
# 使用默认API端点
# 清除可能存在的自定义端点环境变量
if 'GOOGLE_AI_API_ENDPOINT' in os.environ:
del os.environ['GOOGLE_AI_API_ENDPOINT']
genai.configure(api_key=api_key)
def get_default_system_prompt(self) -> str:
return """You are an expert at analyzing questions and providing detailed solutions. When presented with an image of a question:
1. First read and understand the question carefully
2. Break down the key components of the question
3. Provide a clear, step-by-step solution
4. If relevant, explain any concepts or theories involved
5. If there are multiple approaches, explain the most efficient one first"""
def get_model_identifier(self) -> str:
"""返回默认的模型标识符"""
return "gemini-2.0-flash" # 使用有免费配额的模型作为默认值
def analyze_text(self, text: str, proxies: dict = None) -> Generator[dict, None, None]:
"""流式生成文本响应"""
try:
yield {"status": "started"}
# 设置环境变量代理(如果提供)
original_proxies = None
if proxies:
original_proxies = {
'http_proxy': os.environ.get('http_proxy'),
'https_proxy': os.environ.get('https_proxy')
}
if 'http' in proxies:
os.environ['http_proxy'] = proxies['http']
if 'https' in proxies:
os.environ['https_proxy'] = proxies['https']
try:
# 初始化模型
model = genai.GenerativeModel(self.model_name)
# 获取最大输出Token设置
max_tokens = self.max_tokens if hasattr(self, 'max_tokens') else 8192
# 创建配置参数
generation_config = {
'temperature': self.temperature,
'max_output_tokens': max_tokens,
'top_p': 0.95,
'top_k': 64,
}
# 构建提示
prompt_parts = []
# 添加系统提示词
if self.system_prompt:
prompt_parts.append(self.system_prompt)
# 添加用户查询
if self.language and self.language != 'auto':
prompt_parts.append(f"请使用{self.language}回答以下问题: {text}")
else:
prompt_parts.append(text)
# 初始化响应缓冲区
response_buffer = ""
# 流式生成响应
response = model.generate_content(
prompt_parts,
generation_config=generation_config,
stream=True
)
for chunk in response:
if not chunk.text:
continue
# 累积响应文本
response_buffer += chunk.text
# 发送响应进度
if len(chunk.text) >= 10 or chunk.text.endswith(('.', '!', '?', '。', '!', '?', '\n')):
yield {
"status": "streaming",
"content": response_buffer
}
# 确保发送完整的最终内容
yield {
"status": "completed",
"content": response_buffer
}
finally:
# 恢复原始代理设置
if original_proxies:
for key, value in original_proxies.items():
if value is None:
if key in os.environ:
del os.environ[key]
else:
os.environ[key] = value
except Exception as e:
yield {
"status": "error",
"error": f"Gemini API错误: {str(e)}"
}
def analyze_image(self, image_data: str, proxies: dict = None) -> Generator[dict, None, None]:
"""分析图像并流式生成响应"""
try:
yield {"status": "started"}
# 设置环境变量代理(如果提供)
original_proxies = None
if proxies:
original_proxies = {
'http_proxy': os.environ.get('http_proxy'),
'https_proxy': os.environ.get('https_proxy')
}
if 'http' in proxies:
os.environ['http_proxy'] = proxies['http']
if 'https' in proxies:
os.environ['https_proxy'] = proxies['https']
try:
# 初始化模型
model = genai.GenerativeModel(self.model_name)
# 获取最大输出Token设置
max_tokens = self.max_tokens if hasattr(self, 'max_tokens') else 8192
# 创建配置参数
generation_config = {
'temperature': self.temperature,
'max_output_tokens': max_tokens,
'top_p': 0.95,
'top_k': 64,
}
# 构建提示词
prompt_parts = []
# 添加系统提示词
if self.system_prompt:
prompt_parts.append(self.system_prompt)
# 添加默认图像分析指令
if self.language and self.language != 'auto':
prompt_parts.append(f"请使用{self.language}分析这张图片并提供详细解答。")
else:
prompt_parts.append("请分析这张图片并提供详细解答。")
# 处理图像数据
if image_data.startswith('data:image'):
# 如果是data URI,提取base64部分
image_data = image_data.split(',', 1)[1]
# 使用genai的特定方法处理图像
image_part = {
"mime_type": "image/jpeg",
"data": base64.b64decode(image_data)
}
prompt_parts.append(image_part)
# 初始化响应缓冲区
response_buffer = ""
# 流式生成响应
response = model.generate_content(
prompt_parts,
generation_config=generation_config,
stream=True
)
for chunk in response:
if not chunk.text:
continue
# 累积响应文本
response_buffer += chunk.text
# 发送响应进度
if len(chunk.text) >= 10 or chunk.text.endswith(('.', '!', '?', '。', '!', '?', '\n')):
yield {
"status": "streaming",
"content": response_buffer
}
# 确保发送完整的最终内容
yield {
"status": "completed",
"content": response_buffer
}
finally:
# 恢复原始代理设置
if original_proxies:
for key, value in original_proxies.items():
if value is None:
if key in os.environ:
del os.environ[key]
else:
os.environ[key] = value
except Exception as e:
yield {
"status": "error",
"error": f"Gemini图像分析错误: {str(e)}"
} |