For AI agents: a documentation index is available at the root level at /llms.txt and /llms-full.txt. Append /llms.txt to any URL for a page-level index, or .md for the markdown version of any page.
Sign inTry it free
DocsGuidesSDKsIntegrationsAPI docsTutorialsFlagship blog
DocsGuidesSDKsIntegrationsAPI docsTutorialsFlagship blog
  • SDKs
    • SDK concepts
    • SDK features
    • Client-side SDKs
    • Server-side SDKs
    • AI SDKs
      • .NET AI SDK reference
      • Go AI SDK reference
      • Node.js (server-side) AI SDK reference
      • Python AI SDK reference
      • Ruby AI SDK reference
    • Edge SDKs
    • OpenFeature providers
    • Observability SDKs
    • Relay Proxy
Sign inTry it free
LogoLogo
On this page
  • Overview
  • Get started
  • Install the SDK
  • Initialize the client
  • Configure the context
  • Customize a config
  • Customize configs in completion mode
  • Customize configs in agent mode
  • Use managed objects
  • Create a client or model instance
  • Combine config messages with user messages
  • Call the provider and record AI metrics
  • Supported features
SDKsAI SDKs

Node.js (server-side) AI SDK reference

Was this page helpful?
Previous

Python AI SDK reference

Next
Built with

Overview

This topic documents how to get started with the Node.js (server-side) AI SDK, and links to reference information on all of the supported features. You can use either JavaScript or TypeScript when working with the Node.js (server-side) AI SDK.

The Node.js (server-side) AI SDK is designed for use with AgentControl. It is currently in a pre-1.0 release and under active development. You can follow development or contribute on GitHub.

SDK quick links

LaunchDarkly’s SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, sample applications, and provider-specific packages:

ResourceLocation
SDK API documentationSDK API docs
GitHub repositorynode-server-sdk-ai
Sample applicationUsing Bedrock, Using OpenAI
Published modulenpm
Provider-specific packagesOpenAI, LangChain, Vercel AI
For use in server-side applications only

This SDK is intended for use in multi-user Node.js server applications. To learn more about LaunchDarkly’s different SDK types, read Choosing an SDK type.

Get started

LaunchDarkly AI SDKs interact with AgentControl configs. Configs are the LaunchDarkly resources that manage model configurations and messages for your generative AI applications.

Try the Quickstart

This reference guide describes working specifically with the Node.js (server-side) AI SDK. For a complete introduction to LaunchDarkly AI SDKs and how they interact with configs, read Quickstart for AgentControl.

You can use the Node.js (server-side) AI SDK to customize your config based on the context that you provide. This means both the messages and the model evaluation in your generative AI application are specific to each end user, at runtime. You can also use the AI SDKs to record metrics from your AI model generation, including duration and tokens.

Follow these instructions to start using the Node.js (server-side) AI SDK in your application.

Install the SDK

First, install the AI SDK as a dependency in your application using your application’s dependency manager. If you want to depend on a specific version, refer to the SDK releases page to identify the latest version.

The Node.js (server-side) AI SDK is built on the Node.js (server-side) SDK, so you’ll need to install that as well. Alternatively, you can install a server-side edge SDK instead.

In addition, you can also use provider-specific AI SDK packages for better integration and improved version management with your preferred AI framework.

The following provider-specific packages are available:

  • OpenAI
  • LangChain
  • Vercel AI

These packages require Node.js version 16 or higher.

Provider-specific packages are in early development

These provider-specific packages are currently in early development and are not recommended for production use. They may change without notice, including becoming backwards incompatible.

Here’s how:

Shell
$npm install @launchdarkly/node-server-sdk
$npm install @launchdarkly/server-sdk-ai
$# If you want to install a provider-specific package
$npm install @launchdarkly/server-sdk-ai-openai
$# or
$npm install @launchdarkly/server-sdk-ai-langchain
$# or
$npm install @launchdarkly/server-sdk-ai-vercel

Next, import init, LDContext, and initAi in your application code. If you are using TypeScript, you can optionally import the LaunchDarkly LDAIClient and LDAIConfig. These are implied, so are not strictly required.

Here’s how:

1import { init, LDContext } from '@launchdarkly/node-server-sdk';
2import { initAi, LDAIClient, LDAIConfig } from '@launchdarkly/server-sdk-ai';

Here’s how to import a provider-specific package:

1import { getAIMetricsFromResponse } from '@launchdarkly/server-sdk-ai-openai';
2import { OpenAI } from 'openai';

Initialize the client

After you install and import the SDK, create a single, shared instance of LDClient. When the LDClient is initialized, use it to initialize the LDAIClient. The LDAIClient is how you interact with configs. Specify the SDK key to authorize your application to connect to a particular environment within LaunchDarkly.

The Node.js SDKs use an SDK key

Both the Node.js (server-side) AI SDK and the Node.js (server-side) SDK use an SDK key. Keys are specific to each project and environment. They are available on the SDK keys page under Settings. To learn more about key types, read Keys.

Here’s how:

1const ldClient: LDClient = init('YOUR_SDK_KEY');
2
3try {
4 await ldClient.waitForInitialization({ timeout: 10 });
5 // initialization complete
6} catch (error) {
7 // timeout or SDK failed to initialize
8}
9
10const aiClient: LDAIClient = initAi(ldClient);

Configure the context

Configure the context that will encounter generated AI content in your application. The context attributes determine which variation of the config LaunchDarkly serves to the end user, based on the targeting rules in your config. If you are using template variables in the messages in your config’s variations, the context attributes also fill in values for the template variables.

Here’s how:

1const context: LDContext = {
2 kind: 'user',
3 key: 'example-user-key',
4 firstName: 'Sandy',
5 lastName: 'Smith',
6 email: 'sandy@example.com',
7 groups: ['Acme', 'Global Health Services'],
8};

Customize a config

Customize your config to set values for variables used in messages or instructions based on the context attributes and variables you provide.

The details of customizing a config depend on whether you are using configs in completion mode or agent mode. You set the mode for a particular config when you create it in the LaunchDarkly UI.

Customize configs in completion mode

In completion mode, each variation in your config includes a single set of roles and messages used to prompt your generative AI model.

In completion mode, use completionConfig() to customize the config. The completionConfig() function takes a config key, a context, a fallback value, and optional variables to use in the customization. It performs the evaluation, then returns the customized messages and model along with a tracker instance for recording metrics. If it cannot perform the evaluation or LaunchDarkly is unreachable, it returns the fallback value. For example, you might use an empty, disabled configuration object as a fallback value, or a fully configured default. Either way, you should make sure to check for this case and handle it appropriately in your application.

Here’s how:

1const fallbackConfig = { enabled: false };
2
3const aiConfig: LDAIConfig = await aiClient.completionConfig(
4 'example-config-key',
5 context,
6 fallbackConfig,
7 { 'exampleCustomVariable': 'exampleCustomValue' },
8);

Customize configs in agent mode

In agent mode, each variation in your config includes a set of instructions, which enable multi-step workflows.

In agent mode, use agentConfig() or agentConfigs() to customize the config. The agentConfig() function customizes a single agent config, while the agentConfigs() function customizes an array of agent configurations.

The instructions returned by the SDK come directly from the instructions you define for the config variation in the LaunchDarkly UI. The goal or task shown in the UI is delivered unchanged as the instructions field in the SDK.

Customization requires a config key, fallback value, and optional variables for each agent-mode evaluation. Additionally, customization requires a context. Both functions perform the evaluation and then return the customized instructions for each config, along with a tracker instance for recording metrics. If the function cannot perform the evaluation or LaunchDarkly is unreachable, it returns the fallback value.

For example, you might use an empty, disabled configuration object as a fallback value, or a fully configured default. Either way, you should make sure to check for this case and handle it appropriately in your application.

Here’s how:

1const fallbackConfig = { enabled: false };
2
3const agent: LDAIAgentConfig = await aiClient.agentConfig(
4 'example-config-key',
5 context,
6 fallbackConfig,
7 { 'exampleCustomVariable': 'exampleCustomValue' },
8);

To learn more, read Customizing configs.

Use managed objects

As an alternative to the lower-level flow described in the rest of this guide, the SDK provides higher-level managed objects that combine model invocation, message conversion, and metrics tracking. Use createModel(), createAgent(), or createJudge() on the LDAIClient to get a ManagedModel, ManagedAgent, or Judge. This is the recommended pattern for new applications because it handles provider routing and metric extraction automatically.

Managed model (TypeScript)
1const fallback: LDAICompletionConfigDefault = { enabled: false };
2const model = await aiClient.createModel('example-ai-config-key', context, fallback);
3
4if (model) {
5 const result = await model.run('What is the capital of France?');
6 console.log(result.content, result.metrics);
7}

Create a client or model instance

If you’re using a provider-specific package, you can create a client (OpenAI) or a model instance (LangChain and Vercel AI). Here’s how:

1const client = new OpenAI({
2 apiKey: process.env.OPENAI_API_KEY,
3});

Combine config messages with user messages

With your model ready, you can now combine the LaunchDarkly-provided messages with user input. If you’re using a provider-specific package, you can combine a config message with a user message. Here’s how:

1const configMessages = aiConfig.messages || [];
2const userMessage = { role: 'user', content: 'What is the capital of France?' };
3const allMessages = [...configMessages, userMessage];

Call the provider and record AI metrics

Finally, using a provider-specific package, make a request to your generative AI provider and record metrics from your AI model generation.

Tracking AI metrics does not automatically associate traces with the config.

Run model calls inside an active span to associate traces

LaunchDarkly can associate traces with an evaluated config only when the model request runs inside an active OpenTelemetry span. For new application development, we recommend using the LaunchDarkly Observability SDK plugin to create and manage spans.

If the model call does not run inside an active span, LaunchDarkly cannot associate the trace with the config.

To learn more, read LLM observability and Monitor configs.

The following example shows how to use the LaunchDarkly Observability SDK plugin to run a model request inside an active span so LaunchDarkly can associate the resulting trace with the evaluated config.

This example assumes you have configured the LaunchDarkly Observability SDK plugin and have access to request headers.

Using the LaunchDarkly Observability SDK plugin
1const tracker = aiConfig.createTracker();
2
3await LDObserve.runWithHeaders('llm.chat', req.headers, async (span) => {
4 return await tracker.trackMetricsOf(
5 getAIMetricsFromResponse,
6 () => client.chat.completions.create({
7 model: aiConfig.model?.name || 'gpt-4',
8 messages: aiConfig.messages || [],
9 })
10 );
11});

After you ensure your model request runs inside an active span, you can call your provider and record AI metrics as shown in the examples below.

1const tracker = aiConfig.createTracker();
2
3const response = await tracker.trackMetricsOf(
4 getAIMetricsFromResponse,
5 () => client.chat.completions.create({
6 model: aiConfig.model?.name || 'gpt-4',
7 messages: aiConfig.messages || [],
8 temperature: (aiConfig.model?.parameters?.temperature as number) ?? 0.5,
9 })
10);
11
12console.log('AI Response:', response.choices[0].message.content);

To learn more, read Tracking AI metrics.

Supported features

This SDK supports the following features:

  • Anonymous contexts
  • Context configuration
  • Customizing configs
  • Private attributes
  • Tracking AI metrics