Using Context

Access request context for user tracking and custom data

This example shows how to use the optional ctx parameter to access request context like user IDs, conversation IDs, and custom fields.

The Agent

import { Agent, serve, Context } from '@reminix/runtime';

const agent = new Agent('support', {
  metadata: { description: 'Customer support agent' },
});

// Handle invoke with context
agent.onInvoke(async (input, ctx) => {
  const userId = ctx?.userId;
  const tenantId = ctx?.custom?.tenant_id as string | undefined;
  const task = input.task as string;

  return {
    output: `Processing '${task}' for user ${userId} (tenant: ${tenantId})`,
  };
});

// Handle chat with conversation tracking
agent.onChat(async (messages, ctx) => {
  const conversationId = ctx?.conversationId;
  const userId = ctx?.userId;

  const lastMessage = messages[messages.length - 1];
  const content = typeof lastMessage?.content === 'string' ? lastMessage.content : '';

  // Use conversationId for stateful conversations
  const greeting = conversationId ? `[Conv: ${conversationId}] ` : '';
  const userNote = userId ? `(User: ${userId}) ` : '';

  return {
    message: {
      role: 'assistant',
      content: `${greeting}${userNote}You said: ${content}`,
    },
  };
});

serve(agent, { port: 8080 });

Context Fields

The ctx parameter is an object with these optional fields:

FieldTypeDescription
conversationIdstringTrack multi-turn conversations
userIdstringIdentify the user
customRecord<string, unknown>Any additional custom fields

Testing

# Invoke with context
curl -X POST http://localhost:8080/agent/support/invoke \
    -H "Content-Type: application/json" \
    -d '{
      "input": {"task": "check order status"},
      "context": {
        "user_id": "user_123",
        "custom": {"tenant_id": "acme_corp"}
      }
    }'

# Chat with conversation context
curl -X POST http://localhost:8080/agent/support/chat \
    -H "Content-Type: application/json" \
    -d '{
      "messages": [{"role": "user", "content": "Hello!"}],
      "context": {
        "conversation_id": "conv_abc",
        "user_id": "user_123"
      }
    }'

Response Examples

Invoke response:

{"output": "Processing 'check order status' for user user_123 (tenant: acme_corp)"}

Chat response:

{"message": {"role": "assistant", "content": "[Conv: conv_abc] (User: user_123) You said: Hello!"}}

Backward Compatibility

The ctx parameter is optional. Handlers without it continue to work:

// This still works - no ctx parameter
agent.onInvoke(async (input) => {
  return { output: 'processed' };
});

Next Steps

On this page