Implement lifecycle hooks to automatically inject context into prompts before an LLM call or to extract insights from the LLM response after it is generated.
beforeLlmCall(array $inputMessages, AgentContext $context): array
Use this hook to build a context summary (e.g., from current state) and inject it into the system message. This ensures the LLM is aware of the current session state before it generates a response.
afterLlmResponse(Response|Generator $response, AgentContext $context): mixed
Use this hook to parse the LLM's response and update the AgentContext. This is the ideal place to extract user preferences, update goals, or perform structured data extraction from the response text.
// Example: Injecting context before LLM call
public function beforeLlmCall(array $inputMessages, AgentContext $context): array
{
$cart = $context->getState('cart', []);
$budget = $context->getState('budget');
$preferences = $context->getState('preferences', []);
$totalSpent = $context->getState('total_spent', 0);
$contextSummary = $this->buildContextSummary($cart, $budget, $preferences, $totalSpent);
// Inject into the first message (usually the system instruction)
$inputMessages[0]['content'] = $this->instructions . "\n\n" . $contextSummary;
return $inputMessages;
}
// Example: Extracting insights after LLM response
public function afterLlmResponse(Response|Generator $response, AgentContext $context): mixed
{
$responseText = $response->getContent(); // Assuming response provides content
$this->extractAndStorePreferences($responseText, $context);
$this->updateShoppingGoals($responseText, $context);
return $response;
}