Zenith Wang commited on
Commit
578098f
·
1 Parent(s): 5637d75

彻底解决代理参数问题,添加 requests 备用方案

Browse files
Files changed (2) hide show
  1. app.py +101 -21
  2. requirements.txt +2 -1
app.py CHANGED
@@ -1,11 +1,18 @@
1
  import gradio as gr
2
  import time
3
  import base64
4
- from openai import OpenAI
5
  import os
6
  from io import BytesIO
7
  from PIL import Image
8
 
 
 
 
 
 
 
 
 
9
  # 配置
10
  BASE_URL = "https://api.stepfun.com/v1"
11
  # 从环境变量获取API密钥
@@ -27,6 +34,48 @@ def image_to_base64(image):
27
 
28
  return None
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  def call_step_api(image, prompt, model, temperature=0.7, max_tokens=2000):
31
  """调用Step API进行分析,支持纯文本和图像+文本"""
32
 
@@ -75,27 +124,58 @@ def call_step_api(image, prompt, model, temperature=0.7, max_tokens=2000):
75
  }
76
  ]
77
 
78
- # 创建OpenAI客户端 - 简化初始化
79
- try:
80
- # 直接使用最基本的参数初始化
81
- client = OpenAI(
82
- api_key=STEP_API_KEY,
83
- base_url=BASE_URL,
84
- # 不传递任何其他参数,避免版本兼容问题
85
- )
86
- except Exception as e:
87
- # 如果失败,尝试通过环境变量
88
  try:
89
- os.environ['OPENAI_API_KEY'] = STEP_API_KEY
90
- os.environ['OPENAI_BASE_URL'] = BASE_URL
91
- # 清理可能导致问题的环境变量
92
- for key in ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']:
93
- if key in os.environ:
94
- del os.environ[key]
95
- client = OpenAI()
96
- except Exception as e2:
97
- yield "", f"❌ 客户端初始化失败: {str(e)}"
98
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
  try:
101
  # 记录开始时间
 
1
  import gradio as gr
2
  import time
3
  import base64
 
4
  import os
5
  from io import BytesIO
6
  from PIL import Image
7
 
8
+ # 清理环境变量中的代理设置,避免与 OpenAI 客户端冲突
9
+ for key in list(os.environ.keys()):
10
+ if 'proxy' in key.lower() or 'PROXY' in key:
11
+ del os.environ[key]
12
+
13
+ # 导入 OpenAI(在清理环境变量后)
14
+ from openai import OpenAI
15
+
16
  # 配置
17
  BASE_URL = "https://api.stepfun.com/v1"
18
  # 从环境变量获取API密钥
 
34
 
35
  return None
36
 
37
+ def create_client():
38
+ """创建 OpenAI 客户端,处理各种环境问题"""
39
+ import importlib
40
+ import sys
41
+
42
+ # 重新加载 openai 模块以确保干净的状态
43
+ if 'openai' in sys.modules:
44
+ importlib.reload(sys.modules['openai'])
45
+
46
+ # 尝试不同的初始化方式
47
+ try:
48
+ # 方式1:只传递必需参数
49
+ return OpenAI(
50
+ api_key=STEP_API_KEY,
51
+ base_url=BASE_URL
52
+ )
53
+ except:
54
+ pass
55
+
56
+ try:
57
+ # 方式2:通过环境变量
58
+ os.environ['OPENAI_API_KEY'] = STEP_API_KEY
59
+ os.environ['OPENAI_BASE_URL'] = BASE_URL
60
+ return OpenAI()
61
+ except:
62
+ pass
63
+
64
+ # 方式3:使用 httpx 客户端自定义
65
+ try:
66
+ import httpx
67
+ http_client = httpx.Client()
68
+ return OpenAI(
69
+ api_key=STEP_API_KEY,
70
+ base_url=BASE_URL,
71
+ http_client=http_client
72
+ )
73
+ except:
74
+ pass
75
+
76
+ # 如果都失败,返回 None
77
+ return None
78
+
79
  def call_step_api(image, prompt, model, temperature=0.7, max_tokens=2000):
80
  """调用Step API进行分析,支持纯文本和图像+文本"""
81
 
 
124
  }
125
  ]
126
 
127
+ # 创建OpenAI客户端
128
+ client = create_client()
129
+ if client is None:
130
+ # 如果客户端创建失败,尝试直接使用 requests
 
 
 
 
 
 
131
  try:
132
+ import requests
133
+
134
+ headers = {
135
+ "Authorization": f"Bearer {STEP_API_KEY}",
136
+ "Content-Type": "application/json"
137
+ }
138
+
139
+ data = {
140
+ "model": model,
141
+ "messages": messages,
142
+ "temperature": temperature,
143
+ "max_tokens": max_tokens,
144
+ "stream": False
145
+ }
146
+
147
+ response = requests.post(
148
+ f"{BASE_URL}/chat/completions",
149
+ headers=headers,
150
+ json=data,
151
+ timeout=60
152
+ )
153
+
154
+ if response.status_code == 200:
155
+ result = response.json()
156
+ if result.get("choices") and result["choices"][0].get("message"):
157
+ content = result["choices"][0]["message"]["content"]
158
+
159
+ # 解析 reasoning 标记
160
+ reasoning_content = ""
161
+ final_answer = content
162
+
163
+ if "<reasoning>" in content and "</reasoning>" in content:
164
+ parts = content.split("<reasoning>")
165
+ before = parts[0]
166
+ after_reasoning = parts[1].split("</reasoning>")
167
+ reasoning_content = after_reasoning[0]
168
+ final_answer = before + after_reasoning[1] if len(after_reasoning) > 1 else before
169
+
170
+ yield reasoning_content, final_answer
171
+ else:
172
+ yield "", "❌ API 返回格式错误"
173
+ else:
174
+ yield "", f"❌ API 请求失败: {response.status_code}"
175
+
176
+ except Exception as e:
177
+ yield "", f"❌ 请求失败: {str(e)}"
178
+ return
179
 
180
  try:
181
  # 记录开始时间
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  gradio==4.19.2
2
  openai>=1.0.0,<2.0.0
3
  Pillow>=10.0.0
4
- httpx>=0.24.0
 
 
1
  gradio==4.19.2
2
  openai>=1.0.0,<2.0.0
3
  Pillow>=10.0.0
4
+ httpx>=0.24.0
5
+ requests>=2.25.0