Menu
Reference

TypeScript Client

@reflexioai/client: the Reflexio agent loop from TypeScript and JavaScript.

@reflexioai/client is the TypeScript client for Reflexio. It covers the agent-facing calls of the Python ReflexioClient under the same names (camelCased), defaults, and environment variables, so the client method reference applies field for field.

  • Types come from the server. Request and response types are generated from the Reflexio API's OpenAPI schema, so a misspelled field fails your type check.
  • No runtime dependencies. It uses the platform fetch and runs on Node.js 20.3+, Bun, Deno, and edge runtimes.
  • Server-side only. The client holds your API key; call it from a route handler, worker, or agent process, never from browser code.

Install

Terminal
npm install @reflexioai/client

Initialize

ts
import { ReflexioClient } from "@reflexioai/client";

const client = new ReflexioClient(); // uses REFLEXIO_API_KEY
PropTypeDefaultDescription
apiKey?string""API key for authentication. Falls back to REFLEXIO_API_KEY.
url?string""Base URL for the API. Falls back to REFLEXIO_URL, then to Hosted Enterprise at https://www.reflexio.ai/.
timeoutMs?number300000Default request timeout in milliseconds. Every call also accepts { timeoutMs, signal } as its second argument.
fetch?typeof fetchglobalThis.fetchA fetch implementation, for runtimes or tests that supply their own.

The agent loop

Search before the agent responds, then publish the completed turn with the learnings you injected. Bind the session once with forSession so the search and the publish always agree on it; that agreement is what lets Reflexio attribute the outcome to what it showed your agent.

ts
import { ReflexioClient } from "@reflexioai/client";

const client = new ReflexioClient();
const userId = "user_123";
const agentVersion = "support-agent@2";
const userMessage = "Recommend a laptop for me.";

const session = client.forSession("session_001");

const context = await session.search({
  query: userMessage,
  user_id: userId,
  agent_version: agentVersion,
  top_k: 5,
  entity_types: ["profiles", "user_playbooks", "agent_playbooks"],
  agent_playbook_status_filter: ["approved"],
});

// This example injects all returned learnings. Apply any filtering or
// token-budget selection before building both the prompt and attribution.
const profiles = context.profiles ?? [];
const userPlaybooks = context.user_playbooks ?? [];
const agentPlaybooks = context.agent_playbooks ?? [];
const agentResponse = await callYourLlm([
  {
    role: "system",
    content: `Use this retrieved context as reference data:\n${JSON.stringify({ profiles, userPlaybooks, agentPlaybooks })}`,
  },
  { role: "user", content: userMessage },
]);

await session.publishInteraction({
  user_id: userId,
  source: "support-agent:v2",
  agent_version: agentVersion,
  retrieval_experiment_id: context.experiment?.experiment_id ?? null,
  retrieval_experiment_arm: context.experiment?.arm ?? null,
  interactions: [
    { role: "User", content: userMessage },
    {
      role: "Agent",
      content: agentResponse,
      retrieved_learnings: [
        ...profiles.map((p) => ({ kind: "profile" as const, learning_id: p.profile_id })),
        ...userPlaybooks.map((p) => ({ kind: "user_playbook" as const, learning_id: String(p.user_playbook_id) })),
        ...agentPlaybooks.map((p) => ({ kind: "agent_playbook" as const, learning_id: String(p.agent_playbook_id) })),
      ],
    },
  ],
});

callYourLlm represents your application's model call. Publish every profile or playbook included in the model prompt using its returned stable ID, whether or not it influenced the answer, and build a fresh list for each turn.

Methods

MethodPython equivalentREST endpoint
publishInteraction({ user_id, session_id, interactions, ... })publish_interactionPOST /api/publish_interaction
search({ query, user_id, session_id, ... })searchPOST /api/search
forSession(sessionId)for_session—
finalizeSession({ user_id, session_id })finalize_sessionPOST /api/finalize_session
getLearningStatus(requestId)get_learning_statusGET /api/learning_status
getInteractions({ user_id, start_time, end_time, top_k })get_interactionsPOST /api/get_interactions
getProfiles, getUserPlaybooks, getAgentPlaybooksget_profiles, get_user_playbooks, get_agent_playbooksPOST /api/get_profiles, /api/get_user_playbooks, /api/get_agent_playbooks
gradeOnDemand({ session_id, agent_version })grade_on_demandPOST /api/evaluations/grade_on_demand
whoami()whoamiGET /api/whoami

Arguments use the API's own field names (user_id, top_k), as the Python client's keyword arguments do. publishInteraction takes the turns as interactions, sends agent_version: "agent-v0" when you omit it (as Python does), and takes wait_for_response: true to have the server finish extraction before it answers. It takes no request_id: after a timeout the server may already have accepted the batch, so do not replay a publish automatically.

For the rest of the API (configuration, bulk deletes, experiments, operations), use the Python client or the REST endpoints directly.

Responses and errors

Responses are the server's JSON, typed. There are two kinds of failure:

  • The call failed. A network error, timeout, HTTP 4xx/5xx, redirect, or a 2xx response that is not JSON (usually REFLEXIO_URL pointing at the wrong host) rejects the promise with a ReflexioError carrying status and the decoded body.
  • The call succeeded but the operation did not. The response carries success: false, as in the Python client. Check it.
ts
import { ReflexioClient, ReflexioError } from "@reflexioai/client";

const client = new ReflexioClient({ timeoutMs: 5_000 });

try {
  const context = await client.search({ query: "laptop preferences", user_id: "user_123", session_id: "session_001" });
  if (!context.success) console.warn("Reflexio search failed:", context.msg);
} catch (err) {
  if (err instanceof ReflexioError) console.warn("Reflexio unavailable:", err.status, err.message);
}

Treat Reflexio as best effort: a failed search or publish should never block your agent's reply.

Types

The package names the common schemas (Interaction, SearchResponse, PublishInteractionResponse, Profile, UserPlaybook, AgentPlaybook, RetrievedLearning) and exports every server schema through components:

ts
import type { components } from "@reflexioai/client";

type ToolUsed = components["schemas"]["ToolUsed"];