github | npm |文件
現在有了Chatgpt API支持!請參閱使用Chatgpt API 。 (低語即將到來!)
該庫僅作為流返回OpenAI API響應。非流端端點(例如edits等)只是一個只有一個塊更新的流。
process.env中自動加載OPENAI_API_KEY 。默認情況下,使用NodeJS.Readable版本可在openai-streams/node上使用ReadableStream 。
yarn add openai-streams
# -or-
npm i --save openai-streams await OpenAI (
/** 'completions', 'chat', etc. */
ENDPOINT ,
/** max_tokens, temperature, messages, etc. */
PARAMS ,
/** apiBase, apiKey, mode, controller, etc */
OPTIONS
) ;設置OPENAI_API_KEY ENV變量(或傳遞{ apiKey }選項)。
如果庫找不到API鍵,該庫將投擲。您的程序將在process.env.OPENAI_API_KEY默認情況下從運行時加載此程序,但是您可以使用{ apiKey }選項對其進行覆蓋。
重要的是:對於安全性,您只能從process.env變量加載它。
await OpenAI (
"completions" ,
{
/* endpoint params */
} ,
{ apiKey : process . env . MY_SECRET_API_KEY }
) ;通過await OpenAI(endpoint, params, options?) 。
params類型將根據您提供的endpoint推斷,即"edits"端點, import('openai').CreateEditRequest 。
具有raw流模式的示例:
await OpenAI (
"chat" ,
{
messages : [
/* ... */
] ,
} ,
{ mode : "raw" }
) ; 這也將在瀏覽器中工作,但是您需要用戶粘貼其OpenAI鍵,並通過{ apiKey }選項將其傳遞給它。
import { OpenAI } from "openai-streams" ;
export default async function handler ( ) {
const stream = await OpenAI ( "completions" , {
model : "text-davinci-003" ,
prompt : "Write a happy sentence.nn" ,
max_tokens : 100 ,
} ) ;
return new Response ( stream ) ;
}
export const config = {
runtime : "edge" ,
} ; 如果由於另一個原因,您無法使用邊緣運行時或想要消耗node.js流,請使用openai-streams/node :
import type { NextApiRequest , NextApiResponse } from "next" ;
import { OpenAI } from "openai-streams/node" ;
export default async function test ( _ : NextApiRequest , res : NextApiResponse ) {
const stream = await OpenAI ( "completions" , {
model : "text-davinci-003" ,
prompt : "Write a happy sentence.nn" ,
max_tokens : 25 ,
} ) ;
stream . pipe ( res ) ;
}請參見example/src/pages/api/hello.ts中的示例。
默認情況下,使用mode = "tokens" ,您將僅收到消息deltas。對於完整的事件,請使用mode = "raw" 。
請參閱:https://platform.openai.com/docs/guides/chat/introduction
const stream = await OpenAI ( "chat" , {
model : "gpt-3.5-turbo" ,
messages : [
{
role : "system" ,
content : "You are a helpful assistant that translates English to French." ,
} ,
{
role : "user" ,
content : 'Translate the following English text to French: "Hello world!"' ,
} ,
] ,
} ) ;在tokens模式下,您只會收到看起來像這樣的響應塊(用新線插圖以插圖):
Hello
!
How
can
I
assist
you
today
?
使用mode = "raw"以訪問原始事件。
for await (const chunk of yieldStream(stream)) { ... } 。如果您覺得它直觀,我們建議遵循此模式。