Streamlit集成GPT-4 Turbo with Vision拍照分析异常排查求助
Streamlit调用GPT-4V拍照后无响应排查方案
核心问题及修复步骤
- 模型名称错误:你当前使用的
gpt-4-turbo不支持视觉分析,GPT-4 Turbo with Vision的正确模型ID是gpt-4-turbo-vision-preview,错误的模型名会导致API请求失败,但因无异常处理,程序静默停止。 - 缺失异常捕获:代码未对API请求、数据处理环节做异常捕获,网络故障、密钥无效、请求格式错误等情况发生时,无法输出错误信息,导致排查困难。
- Streamlit输出格式问题:直接用
st.text(response.json())输出JSON对象,可能因格式问题导致渲染异常,建议改用st.json()或格式化文本。
修改后的完整代码
import streamlit as st import base64 import requests # OpenAI API Key api_key = "xxx" title = st.text_input("Your prompt:", "What is in the picture?") img_file_buffer = st.camera_input("Take a picture") if img_file_buffer is not None: try: # 读取图片字节数据 bytes_data = img_file_buffer.getvalue() # 转换为base64编码 base64_encoded = base64.b64encode(bytes_data).decode() headers = { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}" } payload = { # 使用正确的视觉模型ID "model": "gpt-4-turbo-vision-preview", "messages": [ { "role": "user", "content": [ { "type": "text", "text": title }, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{base64_encoded}" } } ] } ], "max_tokens": 300 } # 发送API请求并捕获异常 response = requests.post( "https://api.openai.com/v1/chat/completions", headers=headers, json=payload ) response.raise_for_status() # 触发HTTP错误异常 result = response.json() print(result) # 使用Streamlit的JSON组件输出结果 st.json(result) except Exception as e: # 输出详细错误信息到控制台和页面 print(f"Error: {str(e)}") st.error(f"发生错误: {str(e)}")
额外建议
- 确保你的OpenAI API密钥拥有GPT-4V模型的调用权限,可在OpenAI后台查看模型权限。
- 测试时可先使用本地图片(
st.file_uploader)替代相机输入,排查是否为相机输入的特殊场景问题。
内容的提问来源于stack exchange,提问作者bitterjam
相关产品推荐
相关产品推荐

