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)) { ... } 。如果您觉得它直观,我们建议遵循此模式。