0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vercel AI SDKのstreamTextでOpenAIのモデルを扱う

Last updated at Posted at 2024-04-12

AI SDKのstreamTextを使うと色んなモデルを統合的に扱えるよ、という記事を書きました。この記事ではOpenAIの場合を書きます。

現行インターフェース

import OpenAI from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const openaiChatStream:ChatStreamFunction = async({model, messages}) => {
    const params = {
         model: model,
         stream: true,
         messages,
    }
    const response = await openai.chat.completions.create(params as any)

    return OpenAIStream(response as any)
}

メッセージに画像が含まれる時は、下記のようにします。

content = [
  { type: 'text', text: message },
  { type: 'image_url', image_url: { url: data!.imageUrl } }
];

新インターフェース

前回の記事のGoogleやAnthropicの場合と同様の記述となります。

import { OpenAI } from 'ai/openai';

const open = new OpenAI({ apiKey: process.env.OPENAI_API_KEY || ''});

const openaiChatStream:ChatStreamFunction = async({model, messages}) => {
    const result = await experimental_streamText({
        model: openai.chat(model),
        messages: messages as ExperimentalMessage[],
    });
    
    return result.toAIStream();    
}

メッセージに画像が含まれる時は、下記のようにします。

content = [
  { type: 'text', text: message },
  { type: 'image', image: new URL(data!.imageUrl) }
];

追記

更に新しいインターフェースができたようなので別記事にしました。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?