
경이로운 AI는 큰 언어 모델을위한 턴 기반 대화 프롬프트 생성기를 구축하기위한 타입 스크립트 패키지입니다. 이 패키지는 액터라고하는 여러 엔티티 간의 대화 상호 작용을 시뮬레이션하기위한 빌딩 블록을 제공합니다. 행위자는 정보를 공유하고 대화에 참여하며 사전 정의 된 규칙에 따라 대화 과정을 동적으로 조정할 수 있습니다.
mustache )이 하나만있어 가볍고 사용하기 쉽습니다. npm 을 통해 패키지를 설치할 수 있습니다.
npm install @wecandobetter/phenomenal-ai또는 원사를 통해 :
yarn add @wecandobetter/phenomenal-ai Conversation 수업은 모든 배우를 캡슐화하고 배우의 역사, 맥락 및 행위자의 차례 일정을 관리합니다. Actor 수업은 대화에서 배우를 나타냅니다.
다음 예는 Conversation 클래스를 사용하여 두 배우 간의 대화를 시뮬레이션하는 방법을 보여줍니다.
import { Actor , Conversation } from "@wecandobetter/phenomenal-ai" ;
import { generateText } from "./text-generation" ; // provide your own text generation function
// Define your actors
const actors = [
new Actor ( "John" ) ,
new Actor ( "Emma" ) ,
] ;
// Initialize a conversation
const conversation = new Conversation ( "Morning Talk" , { actors } ) ;
// Add a context entry
conversation . context . set ( "topic" , "Current topic of conversation" , "AI Ethics" ) ;
// Make a query:
const response = await conversation . query ( {
speaker : actors [ 0 ] , // the speaker, i.e. the actor asking the question
answerer : actors [ 1 ] , // the answerer, i.e. the actor answering the question
query : "What is the topic of conversation?" , // the query to be answered
generateText , // provide your own text generation function
store : true , // store the response in the history
} ) ;
console . log ( ` ${ response . speaker } : ${ response . text } ` ) ;
// Moderate the conversation by injecting a new message:
conversation . inject ( "Let's get back to the topic of conversation." , {
speaker : "Moderator" , // the speaker of the message (defaults to `System`)
ephemeral : true , // this message will not be stored in the history
} ) ;
// Make one turn:
const turn = await conversation . turn ( {
actor : conversation . scheduler . getNextSpeaker ( ) , // get the next speaker from the scheduler
generateText , // provide your own text generation function
} ) ;
console . log ( ` ${ turn . speaker } : ${ turn . text } ` ) ;
// or use an async generator:
const ac = new AbortController ( ) ;
const loop = conversation . loop ( {
signal : ac . signal , // provide an AbortSignal to stop the loop
generateText , // provide your own text generation function
scheduler : conversation . scheduler , // provide your own scheduler
} ) ;
for await ( const turn of loop ) {
console . log ( ` ${ turn . speaker } : ${ turn . text } ` ) ;
} 이 패키지의 주요 클래스는 Conversation , ConversationHistory 및 Actor 입니다.
Conversation 수업은 여러 배우 간의 지속적인 대화를 나타냅니다.
id : 대화를위한 고유 식별자.name : 대화 이름.actors : 대화에 참여하는 Actor 의 배열.history : 대화의 역사.context : 대화에서 모든 배우들 사이의 공유 맥락. 이들은 Conversation 클래스에서 사용할 수있는 방법입니다.
new Conversation(name: string, { actors: Actor[], generateText?: GenerateText, scheduler?: Scheduler, messages?: Message[], windowss?: { history?: number } }) Conversation 클래스의 새 인스턴스를 초기화합니다.
const conversation = new Conversation ( "Morning Talk" , {
actors : [
new Actor ( "John" ) ,
new Actor ( "Emma" ) ,
] ,
generateText : generateText , // provide your own text generation function
scheduler : RoundRobinScheduler , // provide your own scheduler
messages : [ ] , // bootstrap the conversation with messages
windows : { // configure the conversation window
max : 1024 , // the maximum number of tokens to unmask in the history
} ,
} ) ; conversation.inject(text: string, { speaker = "System" embeddings?: number[][], ephemeral?: true })대화에 새 메시지를 주입합니다. 주입 된 메시지를 반환합니다.
const message = conversation . inject (
"Let's get back to the topic of conversation." ,
{
speaker : "Moderator" ,
ephemeral : true , // if true, the message will not be stored in the history after the next turn
} ,
) ; conversation.query({ speaker: Actor, answerer: Actor, query: string, generateText?: GenerateText, store = false })턴 응답으로 해결되는 약속을 반환합니다.
const response = await conversation . query ( {
speaker : actors [ 0 ] , // the speaker, i.e. the actor asking the question
answerer : actors [ 1 ] , // the answerer, i.e. the actor answering the question
query : "What is the topic of conversation?" , // the query to be answered
generateText , // provide your own text generation function
store : true , // store the response in the history
} ) ;
console . log ( ` ${ response . speaker } : ${ response . text } ` ) ; conversation.turn({ actor: Actor, generateText?: GenerateText })턴 응답으로 해결되는 약속을 반환합니다.
const response = await conversation . turn ( {
actor : conversation . scheduler . getNextSpeaker ( ) , // get the next speaker from the scheduler
generateText , // provide your own text generation function
} ) ;
console . log ( ` ${ response . speaker } : ${ response . text } ` ) ; conversation.loop({ signal: AbortSignal; generateText?: GenerateText })스피커, 텍스트 및 선택적으로 대화에서 각 턴의 임베딩을 생성하는 비동기 생성기.
const ac = new AbortController ( ) ;
// start the loop, which will yield the responses
const loop = conversation . loop ( {
signal : ac . signal , // provide an AbortSignal to stop the loop
generateText , // provide your own text generation function
} ) ;
for await ( const response of loop ) {
console . log ( ` ${ response . speaker } : ${ response . text } ` ) ;
} conversation.toJSON()대화의 JSON 표현을 반환합니다.
const json = conversation . toJSON ( ) ; ConversationHistory 수업은 대화의 역사를 나타냅니다.
messages : 대화에서 메시지 배열. 이들은 ConversationHistory 클래스에서 사용할 수있는 방법입니다.
new ConversationHistory(messages?: Message[]) ConversationHistory 클래스의 새 인스턴스를 초기화합니다.
const history = new ConversationHistory ( [
{ speaker : "John" , text : "Hello, Emma!" } ,
{ speaker : "Emma" , text : "Hi, John!" } ,
] ) ; history.push(message: PartialBy<Message, "feedback">)역사에 새로운 메시지를 푸시합니다.
history . push ( { actor : "John" , text : "Hello, Emma!" } ) ; history.getMessagesFor(actor: string)주어진 액터에 대한 인덱스 및 메시지 맵을 반환합니다.
const messages = history . getMessagesFor ( "John" ) ; history.getStats()역사에 대한 통계를 반환합니다. 통계는 배우별로 그룹화합니다.
const stats = history . getStats ( ) ;
console . log ( stats ) ;
// {
// "Bob": {
// count: 2, // total number of messages
// textCount: 22, // total number of characters
// percentage: 0.5, // percentage of messages in the conversation
// textPercentage: 0.5, // percentage of characters in the conversation
// },
// } history.cleanEphemeral()역사에서 임시 메시지를 제거합니다.
history . cleanEphemeral ( ) ; history.up(message: Message)주어진 메시지에 긍정적 인 피드백을 추가하십시오.
const message = history . messages [ 0 ] ; // get message from somewhere
history . up ( message ) ; history.down(message: Message)주어진 메시지에 부정적인 피드백을 추가하십시오.
const message = history . messages [ 0 ] ; // get message from somewhere
history . down ( message ) ; history.first(): Message역사상 첫 번째 메시지를 반환합니다.
history.last(): Message역사상 마지막 메시지를 반환합니다.
history.toJSON()역사의 JSON 표현을 반환합니다.
history.clear()역사를 정리합니다.
Actor 수업은 대화에 참여하는 엔티티를 나타냅니다.
id : 배우의 고유 식별자.name : 배우의 이름.template : 배우의 프롬프트 템플릿.context : 대화에서 모든 배우들 사이의 공유 맥락.persona : 배우의 페르소나.knowledge : 배우에 대한 지식.memory : 배우의 기억. 이들은 Actor 수업에서 사용할 수있는 방법입니다.
new Actor(name: string, { template?: string, persona?: Persona, knowledge?: Knowledge, memory?: Memory }) Actor 클래스의 새 인스턴스를 초기화합니다. 템플릿이 제공되지 않으면 기본 템플릿이 사용됩니다.
const actor = new Actor ( "John" , {
template : "Hello, my name is {{name}}." ,
) ; actor.render(conversation: Conversation)배우의 템플릿을 프롬프트로 만듭니다. 프롬프트는 선택한 대형 언어 모델에서 응답을 생성하기 위해 사용할 수있는 메시지입니다.
const prompt = actor . render ( conversation ) ; actor.toJSON()배우의 JSON 표현을 반환합니다.
풀 요청을 환영합니다. 주요 변경 사항을 위해 먼저 문제를 열어 변경하고 싶은 것을 논의하십시오. 문제 페이지를 확인하십시오.
이 프로젝트는 MIT 라이센스에 따라 라이센스가 부여됩니다. 자신의 프로젝트에 자유롭게 사용하십시오.
행복한 코딩! ?
문제가 발생하거나 개선에 대한 제안이있는 경우, 문제 또는 풀 요청을 자유롭게 열어주십시오.
이 프로젝트가 마음에 들면 옆을주세요!
우리는 더 잘할 수 있습니다.