0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ReactNativeでOpenAIのAPI呼び出しに詰まった

Posted at

OpenAIの公式ドキュメントで、以下の呼び出し方が記載されていました。

import OpenAI from "openai";
const openai = new OpenAI();

const completion = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
        { role: "system", content: "You are a helpful assistant." },
        {
            role: "user",
            content: "Write a haiku about recursion in programming.",
        },
    ],
});

console.log(completion.choices[0].message);

しかし、これをReactNative/Typescriptライクに書き換えても、適切に動きません(そもそも書き換えが待ちが和えている可能性も否めないが)。

解決策

以下のフォーラムで、ReactNativeのSDKがサポートされていないことが原因と書かれています。

OpenAI doesn’t offer a dedicated SDK for React Native. To integrate OpenAI’s API within your React Native and Expo projects, you should use direct HTTP requests. - (https://community.openai.com/t/404-invalid-url-post-v1-chat-completions-chat-completions/680371)

(訳)OpenAIはReact Native専用のSDKを提供していません。 OpenAIのAPIをReact NativeやExpoのプロジェクトに統合するには、直接HTTPリクエストを使用する必要があります。

なので、以下のように直接リクエストを投げると期待した挙動になると思います。

const completion = await fetch('https://api.openai.com/v1/chat/completions', {
	method: 'POST',
	headers: {
		'Content-Type': 'application/json',
		'Authorization': `Bearer ${Config.OPENAI_API_KEY}`,
	},
	body: JSON.stringify({
		model: 'gpt-4o-mini',
		messages: [
			{ role: 'system', content: 'You are a helpful assistant.' },
			{ role: 'user',
				content: "Write a haiku about recursion in programming."
			},
		],
	}),
});

なんとも紛らわしい。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?