
A IA fenomenal é um pacote digital para criar um gerador de prompt de conversação baseado em turnos para grandes modelos de idiomas. Este pacote fornece os blocos de construção para simular interações de conversação entre várias entidades, chamadas de atores. Os atores podem compartilhar informações, se envolver no diálogo e ajustar dinamicamente o curso da conversa com base em regras predefinidas.
mustache ), tornando -o leve e fácil de usar. Você pode instalar o pacote via npm :
npm install @wecandobetter/phenomenal-aiOu via Yarn:
yarn add @wecandobetter/phenomenal-ai A classe de Conversation encapsula todos os atores e gerencia a história, o contexto e a programação das voltas do ator. A classe Actor representa um ator na conversa.
O exemplo a seguir mostra como usar a classe Conversation para simular uma conversa entre dois atores.
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 } ` ) ;
} As principais classes deste pacote são Conversation , ConversationHistory e Actor .
A aula Conversation representa uma conversa contínua entre vários atores.
id : Identificador exclusivo para a conversa.name : Nome da conversa.actors : Matriz de Actor participando da conversa.history : A história da conversa.context : contexto compartilhado entre todos os atores da conversa. Estes são os métodos disponíveis na aula Conversation .
new Conversation(name: string, { actors: Actor[], generateText?: GenerateText, scheduler?: Scheduler, messages?: Message[], windowss?: { history?: number } }) Inicializa uma nova instância da classe 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 })Injeta uma nova mensagem na conversa. Retorna a mensagem injetada.
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 })Retorna uma promessa que resolve a uma resposta de turno.
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 })Retorna uma promessa que resolve a uma resposta de turno.
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 })Um gerador assíncrono que gera o alto -falante, o texto e, opcionalmente, as incorporações de cada turno na conversa.
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()Retorna uma representação JSON da conversa.
const json = conversation . toJSON ( ) ; A aula ConversationHistory representa a história de uma conversa.
messages : Matriz de mensagens na conversa. Estes são os métodos disponíveis na aula ConversationHistory .
new ConversationHistory(messages?: Message[]) Inicializa uma nova instância da aula ConversationHistory .
const history = new ConversationHistory ( [
{ speaker : "John" , text : "Hello, Emma!" } ,
{ speaker : "Emma" , text : "Hi, John!" } ,
] ) ; history.push(message: PartialBy<Message, "feedback">)Empurra uma nova mensagem para a história.
history . push ( { actor : "John" , text : "Hello, Emma!" } ) ; history.getMessagesFor(actor: string)Retorna um mapa de índices e mensagens para o ator especificado.
const messages = history . getMessagesFor ( "John" ) ; history.getStats()Retorna estatísticas sobre a história. As estatísticas são agrupadas pelo ator.
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()Remove mensagens efêmeras da história.
history . cleanEphemeral ( ) ; history.up(message: Message)Adicione feedback positivo à mensagem fornecida.
const message = history . messages [ 0 ] ; // get message from somewhere
history . up ( message ) ; history.down(message: Message)Adicione feedback negativo à mensagem fornecida.
const message = history . messages [ 0 ] ; // get message from somewhere
history . down ( message ) ; history.first(): MessageRetorna a primeira mensagem na história.
history.last(): MessageRetorna a última mensagem na história.
history.toJSON()Retorna uma representação JSON da história.
history.clear()Limpa a história.
A classe Actor representa uma entidade que está participando de uma conversa.
id : Identificador exclusivo para o ator.name : Nome do ator.template : modelo para os prompts do ator.context : contexto compartilhado entre todos os atores da conversa.persona : Persona do ator.knowledge : Conhecimento do ator.memory : Memória do ator. Estes são os métodos disponíveis na classe Actor .
new Actor(name: string, { template?: string, persona?: Persona, knowledge?: Knowledge, memory?: Memory }) Inicializa uma nova instância da classe Actor . Se nenhum modelo for fornecido, o modelo padrão será usado.
const actor = new Actor ( "John" , {
template : "Hello, my name is {{name}}." ,
) ; actor.render(conversation: Conversation)Torna o modelo do ator em um prompt. O prompt é uma mensagem que pode ser usada pelo modelo de idioma grande escolhido para gerar uma resposta.
const prompt = actor . render ( conversation ) ; actor.toJSON()Retorna uma representação JSON do ator.
Solicitações de tração são bem -vindas. Para grandes mudanças, abra um problema primeiro para discutir o que você gostaria de mudar. Sinta -se à vontade para verificar a página de problemas.
Este projeto está licenciado sob a licença do MIT. Sinta -se à vontade para usá -lo para seus próprios projetos.
Codificação feliz! ?
Se você encontrar algum problema ou tiver sugestões de melhorias, sinta -se à vontade para abrir um problema ou uma solicitação de tração.
Dê a um ️ se você gosta deste projeto!
Codificado com ❤️ por nós podemos fazer melhor.