Companion Agent
The CompanionAgent class manages the core logic for an AI companion.
It integrates the agent, memory, workflow, and duplicate detection to handle
message processing and state generation.
Imports
Section titled “Imports”import { CompanionAgent } from "@aikyo/server";Constructor
Section titled “Constructor”constructor( companion: CompanionCard, model: LanguageModel, history: Message[], config?: { maxTurn: number | null; enableRepetitionJudge: boolean })Parameters
Section titled “Parameters”| Parameter | Type | Description | Default |
|---|---|---|---|
companion | CompanionCard | Companion configuration | - |
model | LanguageModel | LLM model from @ai-sdk/* | - |
history | Message[] | Conversation history array | - |
config | object | Configuration settings | See below |
config.maxTurn | number | null | Max turns | null |
config.enableRepetitionJudge | boolean | Enable dup. check | true |
Configuration Details:
companion: Includes metadata, tools, and eventsmodel: Language model instance from AI SDK providershistory: Array reference to conversation messagesconfig: Default is{ maxTurn: null, enableRepetitionJudge: true }
Usage Example
Section titled “Usage Example”import { CompanionAgent } from "@aikyo/server";import { anthropic } from "@ai-sdk/anthropic";import type { Message } from "@aikyo/server";
const history: Message[] = [];
const companion = new CompanionAgent( companionCard, anthropic("claude-3-5-haiku-latest"), history, { maxTurn: 20, // Terminate after 20 turns enableRepetitionJudge: true // Enable duplicate detection });Tested LLM Providers
Section titled “Tested LLM Providers”- Anthropic:
@ai-sdk/anthropic - Google:
@ai-sdk/google
Properties
Section titled “Properties”companion
Section titled “companion”companion: CompanionCardThe companion configuration card.
agent: AgentAn instance of the Mastra Agent responsible for managing interactions with the LLM.
repetitionJudge
Section titled “repetitionJudge”repetitionJudge: RepetitionJudgeA judge for detecting conversation duplicates. See Duplicate Detection for details.
stateJudge
Section titled “stateJudge”stateJudge: StateJudgeA judge that generates the companion’s state (State) based on conversation history. Used for turn-taking management.
history
Section titled “history”history: Message[]Conversation history array (reference).
memory
Section titled “memory”memory: MemoryAn instance of the Memory class managing long-term and working memory.
Persistence:
- Creates a LibSQL database at
db/<companion_id>.db - Utilizes LibSQLStore for storage and LibSQLVector for vector store
- Supports similarity searches using the vector store
Working Memory Schema:
export const MemorySchema = z.object({ messages: z.array( z.object({ from: z.string().describe("ID of the companion who sent the message"), content: z.string().describe("Summary of the message content"), }), ),});runtimeContext
Section titled “runtimeContext”runtimeContext: RuntimeContextThe runtime context referenced during tool execution. Contains the following information:
| Key | Type | Description |
|---|---|---|
id | string | Companion’s ID |
libp2p | Libp2p | libp2p instance |
companions | Map<string, Metadata> | List of connected companions |
pendingQueries | Map | Pending queries |
agent | CompanionAgent | The agent itself |
run: RunA Run instance of the workflow generated by createToolInstructionWorkflow.
count: numberCurrent turn count (used when maxTurn configuration is set).
config
Section titled “config”config: { maxTurn: number | null; enableRepetitionJudge: boolean }Configuration passed to the constructor.
Methods
Section titled “Methods”generateToolInstruction()
Section titled “generateToolInstruction()”Generates a tool execution instruction by evaluating CEL expressions based on the received message.
async generateToolInstruction(input: Message): Promise<string>Parameters:
input: The received message
Returns:
string: Tool execution instruction (e.g., “Introduce yourself. Use the tool to respond.”) or"failed"if event execution fails
Process Flow:
- In Workflow’s
evaluateStep, the LLM evaluates theparamsschema - In
runStep, checks conditions are evaluated based on CEL expressions - Concatenates and returns the
instructionof the matched condition
generateState()
Section titled “generateState()”Generates the companion’s state (State) based on the complete conversation history.
async generateState(): Promise<State>Parameters:
None (internally references this.history)
Returns:
State: State information including speak/listen, importance, selected, and closing statuses
Process Flow:
- Performs duplicate detection if
enableRepetitionJudgeistrue - Adds closing instructions if score > 0.7
- Generates State using
StateJudge - Checks for
maxTurnlimit (if configured)
For details, see Turn-Taking.
input()
Section titled “input()”Receives a message and executes the LLM based on the tool execution instruction.
async input(message: Message): Promise<void>Parameters:
message: The received message
Process Flow:
- Retrieves a tool execution instruction using
generateToolInstruction - Executes the LLM with the instruction and message
- The LLM automatically executes tools as needed