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

Flutter集成OpenAI模型遇invalid_request_error问题排查与解决

问题排查与解决方法

核心问题分析

导致invalid_request_error的几个关键原因:

1. API端点与模型类型不匹配

  • gpt-3.5-turbo是Chat Completion模型,对应的API端点是/v1/chat/completions,而非你Schema中写的/gpt-3.5-turbo/completions,且基础服务器URL不应包含/engines,正确基础URL为https://api.openai.com/v1。
  • 错误的端点会直接触发请求格式不兼容的报错。

2. 自定义Schema存在语法与定义错误

  • Schema中存在无效占位符(reps...、responses、components / security part),属于非法JSON语法,导致OpenAI无法解析你的自定义动作配置。
  • required数组中声明的Exercisetype、reps等字段,未在properties中完整定义,Schema校验不通过。
  • 误用了prompt字段,Chat模型的请求体不使用该字段,而是用messages数组。

3. Flutter端Prompt格式错误

  • 你的prompt字符串存在单引号嵌套问题(duration: '15 mins'),会导致JSON序列化失败。
  • 直接拼接键值对的格式不符合Chat模型的输入要求,Chat模型需要结构化的messages数组而非纯文本键值串。

分步解决方法

1. 修正自定义动作Schema

替换为以下合法的Schema(适配Chat Completion模型):

{
  "openapi": "3.0.0",
  "info": {
    "title": "Fit Buddy User Routine Modulator",
    "description": "Generate and revise exercise routines based on user input.",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "https://api.openai.com/v1"
    }
  ],
  "paths": {
    "/chat/completions": {
      "post": {
        "operationId": "ReviseExerciseRoutine",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "model": {
                    "type": "string",
                    "example": "gpt-3.5-turbo"
                  },
                  "messages": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "properties": {
                        "role": {
                          "type": "string",
                          "enum": ["system", "user", "assistant"]
                        },
                        "content": {
                          "type": "string"
                        }
                      },
                      "required": ["role", "content"]
                    }
                  }
                },
                "required": ["model", "messages"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Successfully revised exercise routine",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "choices": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "message": {
                            "type": "object",
                            "properties": {
                              "content": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "BearerAuth": []
          }
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "BearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  }
}

2. 调整Flutter端请求格式

将原来的prompt改为Chat模型要求的messages结构,示例代码:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<String> adjustWorkoutPlan() async {
  final apiKey = 'YOUR_OPENAI_API_KEY';
  final url = Uri.parse('https://api.openai.com/v1/chat/completions');

  final requestBody = jsonEncode({
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "你是Fit Buddy的运动计划调整助手,根据用户提供的当前运动数据和需求,生成适配的运动计划。"
      },
      {
        "role": "user",
        "content": "当前运动:腿部弯举,次数15,组数3,重量40kg,时长15分钟。用户需求:增重"
      }
    ]
  });

  final response = await http.post(
    url,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $apiKey',
    },
    body: requestBody,
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    return data['choices'][0]['message']['content'];
  } else {
    throw Exception('请求失败:${response.body}');
  }
}

3. 额外注意事项

  • 确保API密钥权限正确,开通Chat Completion模型的调用权限。
  • 检查请求体的JSON格式,避免单引号、语法错误,所有字符串用双引号包裹。
  • 若仍报错,直接打印完整的响应体,OpenAI的错误信息会明确指出具体问题(比如缺少某个字段、格式错误等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:12:55