You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为McKay Wrigley开发的Chatbot-ui添加GPT-4 Vision API功能?

为Chatbot-ui添加GPT-4 Vision API功能步骤

一、准备工作

  • 拉取最新的Chatbot-ui代码到本地,或确保现有部署的项目代码是最新版本
  • 确认你的OpenAI API密钥拥有GPT-4 Vision模型的调用权限

二、前端修改

1. 添加模型选项

在前端模型选择的配置文件(比如utils/models.ts)中,新增GPT-4 Vision模型条目:

{
  value: "gpt-4-vision-preview",
  label: "GPT-4 Vision",
},

2. 新增图片上传功能

在聊天输入组件(比如components/ChatInput.tsx)中添加图片上传按钮:

  • 添加文件选择输入框:
<input
  type="file"
  accept="image/*"
  onChange={handleImageUpload}
  className="hidden"
  id="image-upload"
/>
<label htmlFor="image-upload" className="cursor-pointer">
  <IconImage className="h-5 w-5 text-gray-500 hover:text-gray-700" />
</label>
  • 实现图片读取与base64转换的函数:
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
  const file = e.target.files?.[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (event) => {
    const base64Image = event.target?.result as string;
    setImageAttachment(base64Image);
  };
  reader.readAsDataURL(file);
};

3. 调整消息发送逻辑

当选择GPT-4 Vision模型时,构造符合OpenAI API要求的消息格式:

const sendMessage = async () => {
  // ...原有逻辑
  const model = selectedModel.value;
  let content: any = [{ type: "text", text: input }];

  if (model === "gpt-4-vision-preview" && imageAttachment) {
    content.push({
      type: "image_url",
      image_url: { url: imageAttachment }
    });
  }

  await fetch("/api/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      // ...其他参数
      messages: [...messages, { role: "user", content }],
      model
    })
  });
  // ...后续逻辑
};

4. 渲染图片消息

在聊天消息组件(比如components/ChatMessage.tsx)中,处理包含图片的消息内容:

{message.content && Array.isArray(message.content) ? (
  <div className="flex flex-col gap-2">
    {message.content.map((item, index) => {
      if (item.type === "text") {
        return <p key={index}>{item.text}</p>;
      }
      if (item.type === "image_url") {
        return <img key={index} src={item.image_url.url} className="max-w-md rounded" alt="用户上传的图片" />;
      }
      return null;
    })}
  </div>
) : (
  <p>{message.content}</p>
)}

三、后端修改

在API路由文件(比如app/api/chat/route.ts)中,适配GPT-4 Vision的请求特性:

const response = await openai.chat.completions.create({
  model: model,
  messages: messages.map(msg => ({
    role: msg.role,
    content: msg.content
  })),
  // GPT-4 Vision暂不支持流式响应,需判断模型关闭stream
  stream: model !== "gpt-4-vision-preview"
});

四、测试功能

  • 启动Chatbot-ui项目,进入聊天界面
  • 在模型选择下拉框中选择「GPT-4 Vision」
  • 点击图片上传按钮,选择本地图片,输入相关问题后发送
  • 检查是否能收到包含图片分析结果的回复

内容的提问来源于stack exchange,提问作者Collin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 02:22:35