
Феноменальное искусство ИИ -это пакет TypeScript для создания поворотного генератора разговорных подсказок для моделей крупных языков. Этот пакет предоставляет строительные блоки для моделирования разговорных взаимодействий между несколькими объектами, которые называются субъектами. Актеры могут делиться информацией, участвовать в диалоге и динамически корректировать курс разговора на основе предопределенных правил.
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. Не стесняйтесь использовать его для своих собственных проектов.
Счастливого кодирования! ?
Если вы сталкиваетесь с какими -либо проблемами или у вас есть предложения по улучшению, не стесняйтесь открывать проблему или запрос на притяжение.
Дайте ️, если вам нравится этот проект!
Кодированный ❤, мы можем добиться большего.