注:このライブラリは廃止されており、現在はZod-GPTとLLM-APIに分割されています。

Chatベースの大手言語モデル(LLMS)を操作するためのTypeScript-Firstプロンプトエンジニアリングツールキット。
LlamaFlowは、ソフトウェアとAIモデルの間にあるミドルウェアレイヤーであり、標準のチャット完了APIに加えて、次の機能を追加します。
Llamaflowを使用すると、OpenaiのChatGPTモデルを次のように照会できます。
import { OpenAI } from 'llama-flow' ;
const model = new OpenAI ( { apiKey : 'YOUR_OPENAI_KEY' } ) ;
const chat = model . chat ( {
systemMessage :
"You are a smart and honest AI assistant. Follow the user's requirements carefully & to the letter, minimize any other prose." ,
} ) ;
const response = await chat . request (
prompt . json ( {
message :
'What are some good names for childrens book about the renaissance? Respond as a JSON array' ,
schema : z . array ( z . string ( ) . max ( 200 ) ) ,
} ) ,
) ;
console . log ( response . content ) ; // content will be typed as string[]; このパッケージはNPMでホストされています:
npm i llama-flow
yarn add llama-flow
コードベースにセットアップするには、必要なモデルで新しいインスタンスを初期化します( OpenAIのみが今のところサポートされています)。初期化時にデフォルトのモデルとチャット構成(温度、タイムアウト、再試行など)を追加することもできます。これらは単なるデフォルトであり、チャットごとまたはレクエストごとにいつでも上書きすることができます。
import { OpenAI } from 'llama-flow' ;
const model = new OpenAI (
{ apiKey : 'YOUR_OPENAI_KEY' } ,
{ model : 'gpt-3.5-turbo' } ,
) ;チャットとは、「ユーザー」(ソフトウェア)とAIエージェントの間の会話です。 Llamaflowはチャットメモリの管理に対応するため、別のリクエストを送信することで会話を続けるだけです。コンテキストウィンドウに適合するために必要に応じてメモリを剪定するなど、さまざまなメモリ管理戦略が将来追加されることに注意してください。
const chat = model . chat ( {
systemMessage : 'You are an AI writer.' ,
retainMemory : true ,
} ) ;
// You can ask the AI model with a simple string, or a dedicated `Prompt` object.
const response = await chat . request (
prompt . text (
'Write a script for a tiktok video that talks about the artistic contribution of the renaissance.' ,
) ,
) ;
// The results, as well as any usage stats, will be returned.
console . log (
`The AI writer's response is: ${ response . content } . Token used: ${ response . usage . totalTokens } .` ,
) ;
// You can follow up on this chat by prompting further, using the `bulletPrompt` object that was created earlier.
const bulletPoints = await chat . request ( bulletPrompt ) ;
// `bulletPoints.content` will be automatically casted in the correct type as defined in the schema field of `bulletPrompt`
console . log (
`The structured version of this response is: ${ JSON . stringify (
bulletPoints . content ,
) } ` ,
) ;プロンプトは、特定の応答形式を期待してAIチャットへのメッセージです。プロンプトタイプメッセージが検証され、定義されたフォーマットが正確に返されることを確認するか、エラーが発生します。さまざまな形式にはさまざまな種類のプロンプトがあります。 JSONプロンプトの例は次のとおりです。
import { prompt } from 'llama-flow' ;
import { z } from 'zod' ; // JSON prompt uses Zod for schema validation.
const bulletPrompt = prompt . json ( {
message :
'Please rewrite this in a list of bullet points. Respond as a JSON array, where each element in the array is one bullet point. Keep each bullet point to be 200 characters max. For example: ["bullet point 1", "bullet point 2"]' ,
schema : z . array ( z . string ( ) . max ( 200 ) ) ,
} ) ; Promptオブジェクトは、メインmessageとformatMessageを分離することに注意してください。これは再試行に使用されます。 LlamaFlowがこのプロンプトを使用すると、メインメッセージとフォーマットメッセージの両方でモデルに尋ねます。モデルが誤ってフォーマットされた応答で戻ってくる場合、 formatMessageのみを使用して、モデルに以前の出力を修正するように依頼します。
カスタムバリーターを使用して独自のプロンプトオブジェクトを作成できます。 llamaflowは、あらゆるタイプのバリデーターを構築するための簡単で拡張可能な方法を提供します。カスタムバリデーターの例をいくつか紹介します。
上記の迅速な例を挙げますが、今回は、JSONアレイの代わりに実際の箇条書きで応答するようにモデルに依頼します。特に複雑なデータ構造に関しては、モデル(ESP <GPT-4)が特定のフォーマット命令に従うのに最適ではない場合があるため、これは便利です。
import { prompt } from 'llama-flow' ;
const bulletPrompt = prompt . json ( {
message :
'Please rewrite this in a list of bullet points. Respond as a list of bullet points, where each bullet point begins with the "-" character. Each bullet point should be less than 200 characters. Put each bullet point on a new line.' ,
// parse the response from the model so it can be fed into the schema validator
parseResponse : ( res ) => res . split ( 'n' ) . map ( ( s ) => s . replace ( '-' , '' ) . trim ( ) ) ,
// it's useful to define custom error messages, any schema parse errors will be automatically fed back into the model on retry, so the model knows exactly what to correct.
schema : z . array (
z . string ( ) . max ( 200 , {
message : 'This bullet point should be less than 200 characters.' ,
} ) ,
) ,
} ) ;それでは、これをさらに進めましょう。モデル(または他の外部ソース)を使用して独自の出力を検証するプロンプトを構築できます。これを行うには、カスタムAsync validateメソッドを渡すことで行うことができます。この方法は、 formatMessage 、 parseResponse 、 schemaなど、他の検証関連のプロパティをオーバーライドすることに注意してください。
import { prompt , Chat } from 'llama-flow' ;
const factCheckerChat = model . chat ( {
systemMessage :
'You are a fact checker that responds to if the user's messages are true or not, with just the word "true" or "false". Do not add punctuations or any other text. If the user asks a question, request, or anything that cannot be fact checked, ignore the user's request and just say "null".' ,
// The fact checker is designed to fulfill each request independently (e.g. the current request does not depend on the content of the previous request). So no need to keep message memory to save on tokens.
retainMemory : false ,
} ) ;
const buildFactCheckedPrompt = ( article : string ) =>
prompt . text ( {
message : `Please write a summary about the following article: ${ article } ` ,
// Because LLM driven validation can get expensive, set a lower retry count.
promptRetries : 2 ,
parse : async ( response ) => {
// Check if this summary is true or not
const { response } = await factCheckerChat . request (
prompt . boolean ( {
message : response . content ,
} ) ,
) ;
if ( response . content === true ) {
return { success : true , data : response . content } ;
} else {
// if `retryPrompt` is set, LLamaFlow will automatically retry with the text in this property.
return {
success : false ,
retryPrompt :
'This summary is not true, please rewrite with only true facts.' ,
} ;
}
} ,
} ) ;
// now, every content generated by this chat will be fact checked by the LLM itself, and this request will throw an error if the content can't be fixed (once the maximum number of retries has been reached).
const factCheckedContent = await chat . request (
buildFactCheckedPrompt (
'Write a script for a tiktok video that talks about the artistic contribution of the renaissance.' ,
) ,
) ;これはAPIであるため、同じチャットからリクエストを続けると便利です。多くの場合、メッセージ履歴は次のリクエストのコンテキストとして機能します。良い例のユースケースは、最初にいくつかのコンテンツを書き込み、次にエンティティを抽出し、最後にタイトルのいくつかのオプションを提供するためのプロンプトです。
// You can reset chat history anytime with `reset()`, however, this is an anti-pattern, as it is prone to mistakes. It's much safer to just initialize a new chat.
chat . reset ( ) ;
const article = await chat . request (
prompt . text ( 'Write a blog post about the financial crisis of 2008' ) ,
) ;
const entities = await chat . request (
prompt . json ( {
message :
'What are the different entities in the above blog post? Respond in a JSON array, where the items in the array are just the names of the entities.' ,
schema : z . array ( z . string ( ) ) ,
} ) ,
) ;
const titles = await chat . request (
prompt . bulletPoints ( {
message : 'Write a good title for this post' ,
amount : 10 ,
} ) ,
) ; LLM APIの一般的なエラーは、トークンの使用です。コンテキストウィンドウに一定量のデータを適合させることができます。 Llamaflowの場合、これは、送信できるメッセージの総数が制限されていることを意味します( retainMemoryがtrueに設定されている場合)、およびメッセージのコンテンツの長さです。
LlamaFlowは、実際のリクエストをモデルプロバイダーに送信する前に、リクエストがトークン制限に違反するかどうかを自動的に判断します(OpenAIなど)。これにより、1つのネットワークラウンドトリップコールが保存され、これらのタイプのエラーをレスポンシブな方法で処理できます。これらのエラーを処理する典型的な方法は、メッセージ履歴のメッセージを削除すること( retainMemoryセットでチャットを使用している場合)、またはコンテンツを小さなクラスターに分割して複数のリクエストで処理することです。
トークンオーバーフローエラーをキャッチする例を以下に示します。 minimumResponseTokensはこのエラーを明示的にトリガーするために高い値に設定されていることに注意してください( gpt-3.5-turboの最大コンテキスト制限は4096であるため、最小制限を4095に設定することは、実際のプロンプトに残り1つのトークンしか残っていないことを意味します。
try {
// make sure to set the `contextSize` to enable automatic token checking
const model = new OpenAI (
{ apiKey : 'YOUR_OPENAI_KEY' } ,
{ model : 'gpt-3.5-turbo' , contextSize : 4096 } ,
) ;
const chat = model . chat ( {
systemMessage : 'You are an AI assistant' ,
} ) ;
await chat . request (
{ message : 'hello world, testing overflow logic' } ,
{ minimumResponseTokens : 4095 } ,
) ;
} catch ( e ) {
if ( e instanceof TokenError ) {
console . info (
`Caught token overflow, overflowed tokens: ${ e . overflowTokens } ` ,
) ;
}
}トークンの制限問題を処理する一般的な方法は、コンテンツを分割することです。 LlamaFlowは、 chat.requestメソッドをラップし、入力チャンク構成に基づいてテキストを自動的に分割する便利なヘルパーメソッドを提供します。テキストがトークンの制限を超えていると判断した場合にのみテキストを分割し、可能な限り元のテキストを保存しようとするほど賢いです。
const response = await chat . requestWithSplit (
'hello world, testing overflow logic' ,
( text ) =>
prompt . text ( {
message : `Add other required prompts first, then add your content: ${ text } ` ,
} ) ,
) ;これで、プロンプトの主なコンテンツが最初に送信されることに注意してください。これは、テキストスプリッターによって分割されるコンテンツです( n 、 . , 最初にキャラクター、それをチャンクします)。追加の必要なプロンプトを追加して、 responseFnパラメーターのコンテンツプロンプトと組み合わせることができます。
llamaflowロギングとエラーメッセージのdebugモジュールを使用します。デバッグモードで実行するには、 DEBUG env変数を設定します。
DEBUG=llamaflow:* yarn playground
また、さまざまなロギングタイプを指定することもできます。
DEBUG=llamaflow:error yarn playground DEBUG=llamaflow:log yarn playground
Llamaflowには、AzureのOpenaiモデルのサポートも付属しています。 Azureバージョンは通常、Openai独自のAPIエンドポイントよりもはるかに高速で信頼性が高くなります。 Azureエンドポイントを使用するには、OpenAIモデル、 azureDeployment 、 azureEndpointを初期化する際に2つのAzure固有のオプションを含める必要があります。 apiKeyフィールドは、Azure APIキーにも使用されます。
Azure PortalにAzure APIキーとエンドポイントを見つけることができます。 Azureの展開は、Azure AIポータルの下に作成する必要があります。
Azureを使用すると、 ModelConfigのmodelパラメーターは無視されることに注意してください。これは、Azureシステムでは、 modelが実行時間ではなく展開の作成時に選択されるためです。
const model = new OpenAI ( {
apiKey : 'AZURE_OPENAI_KEY' ,
azureDeployment : 'AZURE_DEPLOYMENT_NAME' ,
azureEndpoint : 'AZURE_ENDPOINT' ,
} ) ; Llamaflowが現在サポートしている唯一のモデルは、Openaiのチャットベースのモデルです。
const model = new OpenAI ( openAiConfig , modelConfig ) ; interface OpenAIConfig {
apiKey : string ;
} これらのモデル構成マップOpenAIの構成を直接直接、doc:https://platform.openai.com/docs/api-reference/chat/createを参照してください
interface ModelConfig {
model ?: string ;
maxTokens ?: number ;
temperature ?: number ;
topP ?: number ;
stop ?: string | string [ ] ;
presencePenalty ?: number ;
frequencyPenalty ?: number ;
logitBias ?: Record < string , number > ;
user ?: string ;
stream ?: boolean ;
} streamがtrueに設定されている場合、リクエストを行うときにイベントエミッターをChatRequestOptionsに渡すことにより、モデルの要求の部分出力にアクセスできます。部分出力は、 dataイベント上の文字列として送信されます。
モデルにリクエストを行うには、最初にプロンプトオブジェクトを構築する必要があります。プロンプトは、各リクエストに検証を追加し、ロジックを再試行する方法を提供します。
import { prompt } from 'llama-flow' ;
prompt . text ( prompt : string ) ;
prompt . text ( prompt : RawPrompt ) ;
prompt . json ( prompt : JSONPrompt ) ;
prompt . bulletPoints ( prompt : BulletPointsPrompt ) ;
prompt . boolean ( prompt : BooleanPrompt ) ; 文字列として、またはRawPromptとしてリクエストすることができます。
interface RawPrompt < T = string > {
message : string ;
parse ?: (
response : ChatResponse < string > ,
) => MaybePromise <
{ success : false ; retryPrompt ?: string } | { success : true ; data : T }
> ;
promptRetries ?: number ;
}メッセージこれはモデルに送信されるテキストです。
解析独自のparse方法を定義することにより、カスタムパーサーを実装できます。
カスタムデータ型を返すカスタムparse方法を定義する場合、genericタイプをRawPromptに追加することができます。これにより、nemenicに返された種類のparseが自動的にキャストされます。また、 chat.requestメソッドを介してタイプをずっと伝播します。
モデルによって返されたデータが不正されている場合、カスタムretryPrompt文字列を返すことができます。これにより、LlamaFlowがモデルを再現します。
promptreatriesは、リクエストがエラーをスローする前にモデルを再現する回数を定義します。デフォルトは3です。Parse parse 、試行されるために有効なretryPromptを返す必要があることに注意してください。
interface BooleanPrompt {
message : string ;
promptRetries ?: number ;
}モデルにtrue false応答のみが期待される場合の質問をモデルに尋ねたい場合は、このプロンプトを使用してください。
モデルに送信するためのクエリにメッセージを送ります。このプロンプトは、モデルに送信されるメッセージにフォーマット命令を自動的に追加します。モデルに、応答をブール値としてフォーマットするように指示するため、追加のフォーマットステートメントを書くことなく、 messageにクエリを含めることができます。
interface BulletPointsPrompt {
message : string ;
amount ?: number ;
length ?: number ;
promptRetries ?: number ;
}モデルに文字列のリストを返す場合は、このプロンプトを使用してください。
モデルに送信するためのクエリにメッセージを送ります。このプロンプトは、モデルに応答のフォーマット方法をモデルに伝えるメッセージにフォーマット命令を自動的に追加します。
返品するべき箇条書きの数。
長さ各箇条書きにあるべき文字の最大数。
interface JSONPrompt < T extends z . ZodType > {
message : string ;
schema : T ;
parseResponse ?: ( res : string ) => MaybePromise < z . infer < T > > ;
retryMessage ?: string ;
promptRetries ?: number ;
}メッセージをメッセージモデルに送信します。ブール値または箇条書きプロンプトとは異なり、このプロンプトはモデルのフォーミング命令を自動的に生成しません。したがって、モデルへのメッセージの一部として、JSON形式でデータを返すように命令とJSONの形状を含める必要があります。
スキーマこれは、モデルからの応答を解析してタイプキャストするために使用されるZODスキーマです。
Parseresponse JSON形式でデータを返さないようにモデルに依頼する場合、検証のためにschemaに送信する前に、return文字列をJSONに解析するカスタムパーサーを定義できます。
retrymessageスキーマ解析が失敗した場合、これはモデルに送信されたメッセージの一部として使用され、正しくフォーマットされた応答のために再スキャンします。このプロンプトは、スキーマ解析エラーに応じてREAKメッセージを自動的に生成することに注意してください(たとえば、特定のキーが欠落している場合、LlamaFlowはモデルにその特定のキーを含めるように依頼します)。したがって、このフィールドは、純粋にReakのモデルに追加のコンテキストを提供することです。
チャットオブジェクトは、モデルとのチャットセッションを保存します。セッションはメッセージ履歴の保存に対応するため、別のリクエストを行うことでモデルとの会話を続けることができます。
const chat = model . chat ( config : ChatConfig ) ;オプションこのチャットで送信されるすべてのリクエストのデフォルトリクエストオプションだけでなく、メモリ保持動作とデフォルトの要求オプションを設定できます。
export interface ChatConfig {
// the message injected at the start of every chat to steer the agent
systemMessage : string ;
// if chat memory should be retained after every request. when enabled, the chat's behavior will be similar to a normal user chat room, and model can have access to history when making inferences. defaults to false
retainMemory ?: boolean ;
// set default request options. note that this can be overridden on a per-request basis
options ?: ChatRequestOptions ;
} チャットセッションにリクエストを送信するには:
const res : ChatResponse = await chat . request ( prompt , options : ChatRequestOptions ) ;オプションこのパラメーターを介してデフォルトの要求オプションをオーバーライドできます。 Ratelimitまたはサーバーエラーがある場合、リクエストは自動的に再試行されます。
リクエストの再試行は、上記のプロンプトセクションで定義されているプロンプトREAKにカウントされないことに注意してください。
type ChatRequestOptions = {
// the number of time to retry this request due to rate limit or recoverable API errors
retries ?: number ;
retryInterval ?: number ;
timeout ?: number ;
// the minimum amount of tokens to allocate for the response. if the request is predicted to not have enough tokens, it will automatically throw a 'TokenError' without sending the request
minimumResponseTokens ?: number ;
// override the messages used for completion, only use this if you understand the API well
messages ?: Message [ ] ;
// pass in an event emitter to receive message stream events
events ?: EventEmitter ;
} ; チャット応答は次の形式です。
interface ChatResponse < T = string > {
content : T ;
model : string ;
// set to true if this content was streamed. note to actually access the stream, you have to pass in an event emitter via ChatRequestOptions
isStream : boolean ;
usage : {
promptTokens : number ;
completionTokens : number ;
totalTokens : number ;
} ;
}プロンプトからコンテンツが解析され、タイプキャストされたコンテンツ。使用したプロンプトに応じて、タイプは自動的に設定されます。
モデル完了に使用される特定のモデル( gpt-3.5-turbo-0301など)
使用トークンの使用データでは、このマップはOpenAIの使用率を直接マップします。
チャット履歴にメッセージ履歴をリセットしたい場合は、簡単なヘルパーメソッドがあります。
chat . reset ( ) ;この方法はエスケープハッチであることに注意してください。クリーンなスレートで新しいリクエストを行いたい場合は、新しいチャットセッションをインスタンス化することをお勧めします。チャットセッションを複数回リセットする複雑なロジックは、追跡するのが難しく、デバッグが難しい場合があります。
LlamaFlowのチャット管理ロジックをバイパスし、アンダーレイモデルにリクエストを直接送信する場合は、チャットをインスタンス化することなくモデルに直接リクエストを送信できることに注意してください。
const model = new OpenAI ( openAiConfig , modelConfig ) ;
const res = await model . request ( messages : Message [ ] , options : ChatRequestOptions ) ;これにより、チャット履歴管理、迅速なフォーマットと解析、およびペルソナロジックがバイパスされます。 ChatRequestOptionsを介してAPI Retries機能を使用することもできます。