참고 :이 라이브러리는 더 이상 사용되지 않으며 이제 Zod-Gpt 및 LLM-API로 분할되었습니다.

채팅 기반의 대형 언어 모델 (LLM)으로 작업하기위한 TypeScript First Prompt Engineering Toolkit.
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
Codebase에서 설정하려면 원하는 모델로 새 인스턴스를 초기화하십시오 ( 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.' ,
} ) ,
) ,
} ) ; 이제 더 나아가 봅시다. 모델 (또는 기타 외부 소스)을 사용하여 자체 출력을 유효성으로하는 프롬프트를 작성할 수 있습니다. 사용자 정의 비동기 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)에 보내기 전에 요청이 토큰 한도를 위반하는지 자동으로 결정합니다. 이렇게하면 하나의 네트워크 왕복 호출을 저장하고 이러한 유형의 오류를 반응적인 방식으로 처리 할 수 있습니다. 이러한 오류를 처리하는 일반적인 방법은 메시지 기록에서 메시지를 제거하거나 ( retainMemory Set과 채팅을 사용하는 경우) 콘텐츠를 작은 클러스터로 나누고 여러 요청에서 처리하는 것입니다.
다음은 토큰 오버 플로우 오류를 잡는 예입니다. 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 usese 로깅 및 오류 메시지를위한 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의 구성에 직접적으로 문서를 참조하십시오 : 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 메소드 parse 정의 할 때는 RawPrompt 에 일반 유형을 추가 할 수 있습니다. 또한 chat.request 메소드를 통해 유형을 완전히 전파합니다.
모델에서 반환 된 데이터가 잘못식 된 경우 사용자 정의 retryPrompt 문자열을 반환하여 Llamaflow가 모델을 다시 얻게됩니다.
Promptretries 요청이 오류가 발생하기 전에 모델을 다시 할 수있는 횟수를 정의합니다. 기본값은 3에서 3까지. 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 형식으로 데이터를 반환 하지 않도록 요청하면 사용자 정의 파서를 정의하여 Return 문자열을 JSON으로 구문 분석하여 유효성 검사를 위해 schema 로 보내기 전에 보낼 수 있습니다.
RetryMessage 스키마 구문 분석이 실패하면 이는 모델로 전송 된 메시지의 일부로 사용하여 올바르게 형식화 된 응답을 다시 시작합니다. 이 프롬프트는 스키마 구문 분석 오류에 따라 리스크 메시지를 자동으로 생성합니다 (예 : 특정 키가 없으면 Llamaflow는 모델에 해당 특정 키를 포함하도록 요청합니다). 따라서이 필드는 순전히 Reask의 모델에 대한 추가 컨텍스트를 제공합니다.
채팅 객체는 모델과 채팅 세션을 저장합니다. 이 세션은 메시지 기록 저장을 처리하므로 다른 요청을하여 모델과의 대화를 계속할 수 있습니다.
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 또는 Server 오류가 있으면 요청이 자동으로 retsied됩니다.
요청의 재 시도는 위의 프롬프트 섹션에 정의 된 프롬프트 리스크에 포함되지 않습니다.
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 리트리 기능을 계속 사용할 수 있습니다.