見出し画像

You didn't provide an API key. You need toprovide your API key in an Authorization header using Bearerauth (i.e. Authorization: Bearer YOUR_KEY)の対処法

FlutterでChatGPTを搭載したアプリを開発しています。

以下のエラーが出たので、その対処法についてご紹介します!

エラー

{error: {message: You didn't provide an API key. You need to
provide your API key in an Authorization header using Bearer
auth (i.e. Authorization: Bearer YOUR_KEY), or as the password
field (with blank username) if you're accessing the API from
your browser and are prompted for a username and password. You
can obtain an API key from
https://platform.openai.com/account/api-keys., type:
invalid_request_error, param: null, code: null}}

コード

このコードは、OpenAIのチャットモデルを使用してHTTP POSTリクエストを行う非同期関数の一部です。
以下の 'Authorization': '$env'のところでエラーが出ました。

import 'package:flutter_dotenv/flutter_dotenv.dart';

~省略~
var env = dotenv.env['OPENAI_API_KEY'];
    
var response = await http.post(
      Uri.parse(url),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': '$env', //here
      },
      body: jsonEncode({
        'model': 'gpt-3.5-turbo',
        'messages': [
          {
            'role': 'system',
            'content': 'You are a helpful assistant.',
          },
          {
            'role': 'user',
            'content': message,
          },
        ]
      }),
    );

responseのAuthorization headerに、OpenAIのAPIキーを与えないといけないのですが、それがおかしいとのこと。
自分はflutter_dotenvを使って.envファイルにAPIキーを登録し、var env = dotenv.env['OPENAI_API_KEY'];で取り出せるようにしていました。
このenvにAPIキーが入ってないのかと思いprintしたら入ってたので、よく見返すとAuthorization headerにBearerが抜けていました。(エラー文にAuthorization: Bearer YOUR_KEYと書いてる。。)
以下コードに書き換えるとこのエラーは消えてくれました。

    var response = await http.post(
      Uri.parse(url),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $env',
      },
      body: jsonEncode({
        'model': 'gpt-3.5-turbo',
        'messages': [
          {
            'role': 'system',
            'content': 'You are a helpful assistant.',
          },
          {
            'role': 'user',
            'content': message,
          },
        ]
      }),
    );


この記事が気に入ったらサポートをしてみませんか?