Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,24 +8,25 @@ import httpx
|
|
| 8 |
import gradio as gr
|
| 9 |
from PIL import Image
|
| 10 |
|
| 11 |
-
#
|
| 12 |
STEPFUN_ENDPOINT = os.getenv("STEPFUN_ENDPOINT", "https://api.stepfun.com/v1")
|
| 13 |
-
MODEL_NAME = os.getenv("STEPFUN_MODEL", "step-3") #
|
| 14 |
REQUEST_TIMEOUT = float(os.getenv("REQUEST_TIMEOUT", "60"))
|
| 15 |
-
#
|
|
|
|
| 16 |
|
| 17 |
|
| 18 |
def _get_api_key() -> Optional[str]:
|
| 19 |
"""
|
| 20 |
-
优先读 OPENAI_API_KEY
|
| 21 |
-
在 HF Space
|
| 22 |
"""
|
| 23 |
return os.getenv("OPENAI_API_KEY") or os.getenv("STEPFUN_KEY")
|
| 24 |
|
| 25 |
|
| 26 |
def _pil_to_data_url(img: Image.Image, fmt: str = "PNG") -> str:
|
| 27 |
"""
|
| 28 |
-
PIL -> data:image/...;base64,... 字符串(适配 OpenAI 兼容的 image_url
|
| 29 |
"""
|
| 30 |
buf = io.BytesIO()
|
| 31 |
img.save(buf, format=fmt)
|
|
@@ -34,17 +35,29 @@ def _pil_to_data_url(img: Image.Image, fmt: str = "PNG") -> str:
|
|
| 34 |
return f"data:{mime};base64,{b64}"
|
| 35 |
|
| 36 |
|
| 37 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
"""
|
| 39 |
直接请求 StepFun 的 /v1/chat/completions(OpenAI 兼容)。
|
| 40 |
-
|
| 41 |
"""
|
| 42 |
api_key = _get_api_key()
|
| 43 |
if not api_key:
|
| 44 |
-
raise
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
|
| 49 |
url = f"{STEPFUN_ENDPOINT.rstrip('/')}/chat/completions"
|
| 50 |
headers = {
|
|
@@ -55,85 +68,83 @@ def _post_chat(messages: List[Dict[str, Any]], temperature: float = 0.7, max_tok
|
|
| 55 |
"model": MODEL_NAME,
|
| 56 |
"messages": messages,
|
| 57 |
"temperature": temperature,
|
| 58 |
-
# StepFun 多数情况下无需强制 max_tokens;需要时再放开
|
| 59 |
}
|
| 60 |
if max_tokens is not None:
|
| 61 |
payload["max_tokens"] = max_tokens
|
| 62 |
|
| 63 |
-
with httpx.Client(timeout=REQUEST_TIMEOUT) as client:
|
| 64 |
-
resp = client.post(url, headers=headers, json=payload)
|
| 65 |
-
# 让 httpx 抛出更清晰的错误
|
| 66 |
-
resp.raise_for_status()
|
| 67 |
-
data = resp.json()
|
| 68 |
-
|
| 69 |
-
# 标准 OpenAI 兼容返回
|
| 70 |
try:
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
|
| 77 |
def chat_with_step3(image: Optional[Image.Image], question: str, temperature: float) -> str:
|
| 78 |
"""
|
| 79 |
-
Gradio
|
|
|
|
| 80 |
"""
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
content: List[Dict[str, Any]] = []
|
| 86 |
-
if image is not None:
|
| 87 |
-
data_url = _pil_to_data_url(image, fmt="PNG")
|
| 88 |
-
content.append({"type": "image_url", "image_url": {"url": data_url}})
|
| 89 |
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
-
|
| 98 |
return _post_chat(messages, temperature=temperature)
|
| 99 |
-
except httpx.HTTPStatusError as e:
|
| 100 |
-
# 返回服务端 HTTP 错误 + 文本体,便于排查
|
| 101 |
-
try:
|
| 102 |
-
detail = e.response.text
|
| 103 |
-
except Exception:
|
| 104 |
-
detail = repr(e)
|
| 105 |
-
return f"[HTTP {e.response.status_code}] 接口错误:{detail}"
|
| 106 |
except Exception as e:
|
| 107 |
-
|
|
|
|
| 108 |
|
| 109 |
|
| 110 |
-
#
|
| 111 |
-
with gr.Blocks(title="Step3 (StepFun API Demo)") as demo:
|
| 112 |
gr.Markdown(
|
| 113 |
"""
|
| 114 |
# Step3 · 图文对话演示(StepFun OpenAI 兼容接口)
|
| 115 |
- 在 **Settings → Variables and secrets** 添加 `OPENAI_API_KEY`(或 `STEPFUN_KEY`)后即可使用
|
| 116 |
-
-
|
| 117 |
"""
|
| 118 |
)
|
| 119 |
|
| 120 |
with gr.Row():
|
| 121 |
image = gr.Image(type="pil", label="上传图片(可选)")
|
|
|
|
| 122 |
question = gr.Textbox(label="问题", placeholder="例如:帮我看看这是什么菜,怎么做?")
|
| 123 |
temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.1, label="Temperature")
|
| 124 |
submit = gr.Button("提交", variant="primary")
|
| 125 |
-
output = gr.Textbox(label="模型回答", lines=
|
| 126 |
|
| 127 |
submit.click(fn=chat_with_step3, inputs=[image, question, temperature], outputs=[output])
|
| 128 |
|
| 129 |
gr.Markdown(
|
| 130 |
"""
|
| 131 |
-
|
| 132 |
-
-
|
| 133 |
-
- 如需改模型:设置环境变量 `STEPFUN_MODEL`,或在代码顶部修改默认值
|
|
|
|
| 134 |
"""
|
| 135 |
)
|
| 136 |
|
| 137 |
if __name__ == "__main__":
|
| 138 |
-
#
|
| 139 |
-
demo.launch()
|
|
|
|
| 8 |
import gradio as gr
|
| 9 |
from PIL import Image
|
| 10 |
|
| 11 |
+
# ========= 基本配置(可用环境变量覆写)=========
|
| 12 |
STEPFUN_ENDPOINT = os.getenv("STEPFUN_ENDPOINT", "https://api.stepfun.com/v1")
|
| 13 |
+
MODEL_NAME = os.getenv("STEPFUN_MODEL", "step-3") # 可改为 step-r1-v-mini
|
| 14 |
REQUEST_TIMEOUT = float(os.getenv("REQUEST_TIMEOUT", "60"))
|
| 15 |
+
MAX_CHARS = int(os.getenv("MAX_CHARS", "20000")) # 返回文本最大展示长度
|
| 16 |
+
# ===========================================
|
| 17 |
|
| 18 |
|
| 19 |
def _get_api_key() -> Optional[str]:
|
| 20 |
"""
|
| 21 |
+
优先读 OPENAI_API_KEY(OpenAI 兼容习惯),否则读 STEPFUN_KEY。
|
| 22 |
+
在 HF Space → Settings → Variables and secrets 添加其中一个即可。
|
| 23 |
"""
|
| 24 |
return os.getenv("OPENAI_API_KEY") or os.getenv("STEPFUN_KEY")
|
| 25 |
|
| 26 |
|
| 27 |
def _pil_to_data_url(img: Image.Image, fmt: str = "PNG") -> str:
|
| 28 |
"""
|
| 29 |
+
PIL.Image -> data:image/...;base64,... 字符串(适配 OpenAI 兼容的 image_url)
|
| 30 |
"""
|
| 31 |
buf = io.BytesIO()
|
| 32 |
img.save(buf, format=fmt)
|
|
|
|
| 35 |
return f"data:{mime};base64,{b64}"
|
| 36 |
|
| 37 |
|
| 38 |
+
def _truncate(text: str, limit: int = MAX_CHARS) -> str:
|
| 39 |
+
"""
|
| 40 |
+
软截断,避免一次性把超长内容写给前端导致传输异常。
|
| 41 |
+
"""
|
| 42 |
+
if text is None:
|
| 43 |
+
return ""
|
| 44 |
+
if len(text) <= limit:
|
| 45 |
+
return text
|
| 46 |
+
return text[:limit] + "\n\n[输出过长,已截断]"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _post_chat(messages: List[Dict[str, Any]], temperature: float = 0.7,
|
| 50 |
+
max_tokens: Optional[int] = None) -> str:
|
| 51 |
"""
|
| 52 |
直接请求 StepFun 的 /v1/chat/completions(OpenAI 兼容)。
|
| 53 |
+
返回纯字符串,不抛异常,交由上层统一处理。
|
| 54 |
"""
|
| 55 |
api_key = _get_api_key()
|
| 56 |
if not api_key:
|
| 57 |
+
# 不 raise,让 UI 只显示字符串,避免 Uvicorn/h11 生成异常页
|
| 58 |
+
return ("[配置错误] 未检测到 API Key。\n"
|
| 59 |
+
"请到 Space 的 Settings → Variables and secrets 添加:\n"
|
| 60 |
+
" OPENAI_API_KEY=你的 StepFun API Key (或使用 STEPFUN_KEY)")
|
| 61 |
|
| 62 |
url = f"{STEPFUN_ENDPOINT.rstrip('/')}/chat/completions"
|
| 63 |
headers = {
|
|
|
|
| 68 |
"model": MODEL_NAME,
|
| 69 |
"messages": messages,
|
| 70 |
"temperature": temperature,
|
|
|
|
| 71 |
}
|
| 72 |
if max_tokens is not None:
|
| 73 |
payload["max_tokens"] = max_tokens
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
try:
|
| 76 |
+
with httpx.Client(timeout=REQUEST_TIMEOUT) as client:
|
| 77 |
+
resp = client.post(url, headers=headers, json=payload)
|
| 78 |
+
resp.raise_for_status()
|
| 79 |
+
data = resp.json()
|
| 80 |
+
# 标准 OpenAI 兼容返回
|
| 81 |
+
content = data["choices"][0]["message"]["content"]
|
| 82 |
+
return _truncate(str(content))
|
| 83 |
+
except httpx.HTTPStatusError as e:
|
| 84 |
+
body = e.response.text if e.response is not None else repr(e)
|
| 85 |
+
code = getattr(e.response, "status_code", "?")
|
| 86 |
+
return _truncate(f"[HTTP {code}] 接口错误:\n{body}")
|
| 87 |
+
except Exception as e:
|
| 88 |
+
# 网络/解析/其他错误
|
| 89 |
+
return _truncate(f"[调用失败] {repr(e)}")
|
| 90 |
|
| 91 |
|
| 92 |
def chat_with_step3(image: Optional[Image.Image], question: str, temperature: float) -> str:
|
| 93 |
"""
|
| 94 |
+
Gradio 回调:接收图片与问题文本,返回字符串。
|
| 95 |
+
任何异常都“吃掉”,只返回文本,防止框架层渲染异常页。
|
| 96 |
"""
|
| 97 |
+
try:
|
| 98 |
+
# 输入兜底
|
| 99 |
+
if image is None and not question.strip():
|
| 100 |
+
return "请上传一张图片,或至少输入一个问题。"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
content: List[Dict[str, Any]] = []
|
| 103 |
+
if image is not None:
|
| 104 |
+
data_url = _pil_to_data_url(image, fmt="PNG")
|
| 105 |
+
content.append({"type": "image_url", "image_url": {"url": data_url}})
|
| 106 |
|
| 107 |
+
if question.strip():
|
| 108 |
+
content.append({"type": "text", "text": question.strip()})
|
| 109 |
+
else:
|
| 110 |
+
content.append({"type": "text", "text": "请描述这张图片。"})
|
| 111 |
|
| 112 |
+
messages = [{"role": "user", "content": content}]
|
| 113 |
return _post_chat(messages, temperature=temperature)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
except Exception as e:
|
| 115 |
+
# 再兜一层底,避免任何未捕获异常冒泡
|
| 116 |
+
return _truncate(f"[运行时错误] {repr(e)}")
|
| 117 |
|
| 118 |
|
| 119 |
+
# ================== Gradio UI ==================
|
| 120 |
+
with gr.Blocks(title="Step3 (StepFun API Demo)", analytics_enabled=False) as demo:
|
| 121 |
gr.Markdown(
|
| 122 |
"""
|
| 123 |
# Step3 · 图文对话演示(StepFun OpenAI 兼容接口)
|
| 124 |
- 在 **Settings → Variables and secrets** 添加 `OPENAI_API_KEY`(或 `STEPFUN_KEY`)后即可使用
|
| 125 |
+
- 后端通过 `https://api.stepfun.com/v1/chat/completions`,不依赖 `openai` SDK
|
| 126 |
"""
|
| 127 |
)
|
| 128 |
|
| 129 |
with gr.Row():
|
| 130 |
image = gr.Image(type="pil", label="上传图片(可选)")
|
| 131 |
+
|
| 132 |
question = gr.Textbox(label="问题", placeholder="例如:帮我看看这是什么菜,怎么做?")
|
| 133 |
temperature = gr.Slider(0.0, 1.5, value=0.7, step=0.1, label="Temperature")
|
| 134 |
submit = gr.Button("提交", variant="primary")
|
| 135 |
+
output = gr.Textbox(label="模型回答", lines=12)
|
| 136 |
|
| 137 |
submit.click(fn=chat_with_step3, inputs=[image, question, temperature], outputs=[output])
|
| 138 |
|
| 139 |
gr.Markdown(
|
| 140 |
"""
|
| 141 |
+
**小贴士:**
|
| 142 |
+
- 如见到 `[配置错误] 未检测到 API Key`,请检查 Space 的 Secrets
|
| 143 |
+
- 如需改模型:设置环境变量 `STEPFUN_MODEL`,或在代码顶部修改默认值
|
| 144 |
+
- 如输出非常长,会自动做软截断避免传输异常
|
| 145 |
"""
|
| 146 |
)
|
| 147 |
|
| 148 |
if __name__ == "__main__":
|
| 149 |
+
# 使用队列降低并发写冲突;关闭错误页,避免长 HTML 异常内容触发 h11 的 Content-Length 问题
|
| 150 |
+
demo.queue(concurrency_count=2, max_size=32).launch(show_error=False, quiet=True)
|