Skip to main content

JS Decorators

Higher-order functions for adding observability context in JavaScript/TypeScript.

Risicare provides higher-order functions that wrap your functions with observability context. These work similarly to Python decorators.

Agent Functions

agent()

Wrap a function as an agent entry point:

import { agent } from 'risicare';
 
const myAgent = agent(
  {
    name: 'researcher',
    role: 'worker',
    agentType: 'search',
    version: 1,
  },
  async (query: string) => {
    // All spans here are associated with this agent
    return await processQuery(query);
  }
);
 
// Use the wrapped function
const result = await myAgent('What is the weather?');

Options (first parameter):

OptionTypeDefaultDescription
agentIdstringauto-generatedStable agent identifier
namestringthe function nameAgent name. The span is named agent:<name>. With no name it is agent:<function name>, or agent:agent for an anonymous function
rolestringundefinedAgent role — any string; canonical values are the AgentRole enum (orchestrator, worker, supervisor, specialist, router, aggregator, broadcaster, critic, planner, executor, retriever, validator, reviewer, custom)
agentTypestringundefinedType identifier
versionnumberundefinedAgent version
metadataobjectundefinedCustom key-value metadata

Session Functions

session()

Bind a function to a user session:

import { session } from 'risicare';
 
const handleRequest = session(
  {
    sessionId: 'sess-123',
    userId: 'user-456',
  },
  async (query: string) => {
    // All traces grouped under this session
    return await processRequest(query);
  }
);

You can also use a resolver function for dynamic sessions:

const handleRequest = session(
  (sessionId: string, userId: string, _query: string) => ({
    sessionId,
    userId,
  }),
  async (sessionId: string, userId: string, query: string) => {
    return await processRequest(query);
  }
);

SessionOptions:

OptionTypeRequiredDescription
sessionIdstringYesSession identifier
userIdstringNoUser identifier

Phase Functions

Track semantic decision phases:

traceThink()

import { traceThink } from 'risicare';
 
const analyze = traceThink(async (context: Context) => {
  // Reasoning logic
  return analysis;
});

traceDecide()

import { traceDecide } from 'risicare';
 
const plan = traceDecide(async (options: Option[]) => {
  // Decision logic
  return selectedOption;
});

traceAct()

import { traceAct } from 'risicare';
 
const execute = traceAct(async (action: Action) => {
  // Action execution
  return result;
});

The span has the kind tool_call and the phase act. Its name is act:<function name> for a named function, and phase:act for an anonymous function (as in the example above). traceAct('name', fn) chooses the name. See Trace your own tool function.

traceObserve()

import { traceObserve } from 'risicare';
 
const checkState = traceObserve(async (key: string) => {
  // State reading
  return memory.get(key);
});

Trace your own tool function

patchOpenAI and patchAnthropic trace the model call. They record on its span that the model asked for a tool: the name, and the arguments when content capture is on. They do not trace the function of yours that runs the tool. In an agent loop that you write yourself, wrap that function. Then each run of the tool is a span of its own, with its time, its status and its exception.

The Tools column of the trace list counts the spans of kind tool_call. A trace in which you wrap no tool function shows 0 tools.

import { init, agent, traceAct, getTracer, SpanKind } from 'risicare';
 
init(); // reads RISICARE_API_KEY
 
// 1. traceAct(): a span of kind tool_call with the phase act, named lookup_order
const lookupOrder = traceAct('lookup_order', async (orderId: string) => {
  return await findOrder(orderId);
});
 
// 2. getTracer().startSpan(): a span of kind tool_call, with the input and the output
async function getWeather(city: string): Promise<string> {
  const tracer = getTracer();
  if (!tracer) return fetchWeather(city); // no tracer before init()
  return tracer.startSpan({ name: 'get_weather', kind: SpanKind.TOOL_CALL }, async (span) => {
    span.setAttribute('tool.input', JSON.stringify({ city }));
    const weather = await fetchWeather(city);
    span.setAttribute('tool.output', JSON.stringify(weather));
    return weather;
  });
}
 
// One trace for the whole loop
const run = agent({ name: 'support-agent' }, async (question: string) => {
  // your loop: call the model, run getWeather or lookupOrder, call the model again
});
FormName of the spanKindPhase
traceAct('lookup_order', fn)The name that you give. Without a name, act:<function name> (phase:act for an anonymous function)tool_callact
getTracer().startSpan({ name, kind: SpanKind.TOOL_CALL }, fn)The name that you givetool_callNone

SpanKind is a runtime export of risicare: import it as a value, not with import type. Both forms work on sync and async functions. Call the tools inside the function that agent() wraps, so that the model calls and the tool calls are in one trace.

A tool that fails. When the tool throws (or its promise rejects), its span has the status error and the exception, and the error goes on to your code. You do not call reportError() for it.

The input and the output. traceAct() does not record the arguments or the return value of your function. To show them, use the second form and set the keys tool.input and tool.output. They are content: with traceContent: false, the SDK replaces both with <risicare:content-omitted>.

For Python, see Trace your own tool function.

Multi-Agent Functions

traceMessage()

Track inter-agent message passing:

import { traceMessage } from 'risicare';
 
const sendMessage = traceMessage(
  { to: 'reviewer-agent' },
  async (message: string) => {
    return await router.send('reviewer-agent', message);
  }
);

traceDelegate()

Track task delegation:

import { traceDelegate } from 'risicare';
 
const delegateTask = traceDelegate(
  { to: 'worker-agent' },
  async (task: Task) => {
    return await workers.get('worker-agent').execute(task);
  }
);

traceCoordinate()

Track multi-agent coordination:

import { traceCoordinate } from 'risicare';
 
const syncAgents = traceCoordinate(
  { participants: ['agent-a', 'agent-b', 'agent-c'] },
  async () => {
    return await coordinator.sync(['agent-a', 'agent-b', 'agent-c']);
  }
);

Complete Multi-Agent Example

import { agent, traceThink, traceDecide, traceAct, traceDelegate } from 'risicare';
 
// Define sub-agents
const researcher = agent(
  { name: 'researcher', role: 'worker' },
  async (query: string) => {
    const analyze = traceThink(async () => parseQuery(query));
    const search = traceAct(async () => searchDatabase(query));
 
    await analyze();
    return await search();
  }
);
 
// Define orchestrator
const orchestrator = agent(
  { name: 'orchestrator', role: 'orchestrator' },
  async (task: string) => {
    const plan = traceDecide(async () => createPlan(task));
    const delegate = traceDelegate(
      { to: 'researcher' },
      async () => researcher(task)
    );
 
    await plan();
    return await delegate();
  }
);
 
// Run
const result = await orchestrator('Research AI trends');

An abort is not an error

Since npm 0.19.1, an AbortError (for example from an AbortController abort) that ends agent(), the phase functions, session() or withSession() is not an error. That span, and the session.end marker, have no error status, no exception record and no error.code. They have these three attributes:

AttributeValue
risicare.cancelledtrue
risicare.cancel_typeAbortError
risicare.lifecycle.statuscancelled

A filter on risicare.lifecycle.status can see this new value, cancelled. Another error is an error, as before. An abort of an OpenAI or Anthropic client call (APIUserAbortError) is not an AbortError: its span still reads as a failed call, with a timeout code. Through npm 0.19.0, the span of an abort had the status error. For Python, see A close and a cancel are not errors.

Next Steps