OpenRouter TypeScript SDK

repository·main·Indexed 42 days ago

https://github.com/openrouterteam/typescript-sdk

A type-safe toolkit for building AI applications with access to 400+ language models through a unified API. Version 1.2.148 supports streaming, pagination, and efficient file uploads across any JS/TS runtime. It includes specialized tools like AdvisorServerToolOpenRouter for consulting higher-intelligence models and ApplyPatchServerTool for validating V4A diff patches.

Tokens
297.2K
Snippets
753
Records
989
Agent score
77%

What's inside OpenRouter

  1. Overview of SCIM Management Endpoints

    main

    The SCIM management endpoints allow for the management of SCIM group-to-workspace mappings. These endpoints are authenticated using a management key.

    Important Distinction: These are not the SCIM 2.0 connector endpoints used by your identity provider. When configuring provisioning in your identity provider, you should use the specific SCIM endpoint URL provided in the OpenRouter dashboard under Settings > Members > SCIM Mappings.

  2. Overview of OpenRouter Datasets

    main

    The OpenRouter Datasets API provides access to public usage datasets. This data is licensed under CC BY 4.0, allowing for reuse and republication (including commercially) provided that attribution is given to OpenRouter.

    Available Operations

    • getAppRankings: Returns top public apps ranked by token usage.
    • getRankingsDaily: Returns daily token totals for the top 50 models.
    • getSessionCost: Returns cost per session by harness and model.

    Usage Constraints & Requirements

    • Authentication: Use any valid OpenRouter API key (the same key used for inference).
    • Rate Limits: 30 requests/minute per key and 500 requests/day per account.
    • Attribution: When quoting or republishing, use the format: "Source: OpenRouter (openrouter.ai/apps), as of {as_of}."
  3. Manage OpenRouter Interns

    main

    OpenRouter Interns can be managed (created, inspected, updated, provisioned, suspended, or deleted) through the SDK using an API key. Additionally, you can interact with them via a chat route that streams OpenAI-compatible completions. When an intern requires permission or an answer, the stream will pause and issue an openrouter.provide_input tool call.

    Note: These features are only available to members of the interns programme; other callers will receive a 404 error. Requests made to regional hostnames (e.g., eu.openrouter.ai) will be refused.

  4. Overview of Vault operations

    main

    The Vault service allows you to store host-bound secrets for either a workspace or a specific intern. The scope of the operation (workspace vs. intern) is determined by the provided API key.

    Important Security Note: Responses from Vault API calls return metadata only (such as names, bound hosts, fingerprints, and creation times). The actual secret values are never returned by the API.

    Requirements & Constraints:

    • Every Vault route requires access to the Intern API programme; otherwise, it returns a 404.
    • Requests made to regional hostnames (e.g., eu.openrouter.ai) will be refused.
    • There is no default workspace; the API key must explicitly target a scope.
  5. Use ContainerReferenceEnvironment to reference containers

    main

    The ContainerReferenceEnvironment model allows you to reference a container using its canonical ID (a previously returned container_id) or a fresh name to create a persistent container. This is used when you want to interact with an existing container session rather than starting a new one.

    import { ContainerReferenceEnvironment } from "@openrouter/sdk/models";
    
    let value: ContainerReferenceEnvironment = {
      containerId: "sess_abc123",
      type: "container_reference",
    };
  6. Understand the OutputShellCallOutputItem model

    main

    The OutputShellCallOutputItem is a data structure that matches the OpenAI Responses API shape for shell_call_output items. It is used to represent the results of shell commands executed in a sandbox.

    Each item contains:

    • callId: The identifier for the specific call.
    • id: The message identifier.
    • output: An array of command results, where each result includes stdout, stderr, and an outcome (containing exitCode and the type, such as exit or timeout).
    • status: The execution status (e.g., completed or incomplete).
    • type: Set to shell_call_output.

    Note: If a sandbox failure occurs, the item is marked as incomplete and the error field is populated.

    import { OutputShellCallOutputItem } from "@openrouter/sdk/models";
    
    let value: OutputShellCallOutputItem = {
      callId: "<id>",
      id: "msg-abc123",
      output: [
        {
          outcome: {
            exitCode: 0,
            type: "exit",
          },
          stderr: "",
          stdout: "total 0\n",
        },
      ],
      status: "completed",
      type: "shell_call_output",
    };
  7. Manage subagent instance identity with instanceName

    main

    When working with multiple subagents, the instanceName field is used to distinguish between them.

    • Default Instance: The first subagent entry in the request tools array is the default instance and will not include an instanceName.
    • Non-default Instances: The second and subsequent subagent entries in the tools array will include a provider-safe name (e.g., openrouter_subagent__1).
    • Positional Identity: The instanceName is derived from the index of the subagent in the tools array. To ensure correct transcript rehydration during replays, you must keep the order of subagent entries stable across all requests in a conversation.
  8. Understand the ScimSyncJob model

    main

    The ScimSyncJob model represents the state and metadata of a SCIM (System for Cross-domain Identity Management) synchronization task. It provides details about when a job started and finished, its current execution status, and the outcome of the synchronization (such as the number of groups synced or deleted).

    import { ScimSyncJob } from "@openrouter/sdk/models";
    
    let value: ScimSyncJob = {
      createdAt: "1717120563145",
      deletedGroups: null,
      errorMessage: "<value>",
      finishedAt: "<value>",
      id: "15580601-fb00-4868-a8e7-1e1a16bb7a7f",
      startedAt: "<value>",
      status: "succeeded",
      syncedGroups: null,
    };
  9. Understand the GenerationContentData model

    main

    The GenerationContentData type represents the stored content of a model generation, including the original prompt (input), the resulting completion (output), and any error information if the generation failed. It is used to track the lifecycle and results of a single generation request.

    import { GenerationContentData } from "@openrouter/sdk/models";
    
    let value: GenerationContentData = {
      error: null,
      input: {
        messages: [
          {
            "content": "What is the meaning of life?",
            "role": "user",
          },
        ],
      },
      output: {
        completion: "The meaning of life is a philosophical question...",
        reasoning: null,
      },
    };
  10. Understand the ModelResponse type

    main

    The ModelResponse type represents a single model object returned by the OpenRouter API. It contains metadata about the model's capabilities, such as its architecture (input/output modalities), context length, pricing, and supported parameters. This type is used when inspecting model details or listing available models via the SDK.

    import { ModelResponse } from "@openrouter/sdk/models";
    
    let value: ModelResponse = {
      data: {
        architecture: {
          inputModalities: ["text"],
          modality: "text->text",
          outputModalities: ["text"],
        },
        canonicalSlug: "openai/gpt-4",
        contextLength: 8192,
        created: 1692901234,
        defaultParameters: null,
        id: "openai/gpt-4",
        links: {
          details: "/api/v1/models/openai/gpt-4/endpoints",
        },
        name: "GPT-4",
        perRequestLimits: null,
        pricing: {
          completion: "0.00006",
          prompt: "0.00003",
        },
        supportedParameters: [
          "temperature",
          "top_p",
          "max_tokens",
        ],
        supportedVoices: null,
        topProvider: {
          isModerated: true,
        },
      },
    };