> ## Documentation Index
> Fetch the complete documentation index at: https://launchdarkly.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Building a data extraction pipeline with LaunchDarkly

> Turn unstructured text into structured JSON with runtime-configurable schemas. Production-ready pipeline with AgentControl for instant model and prompt changes.

**Developer**

**Federal docs**

**EU docs**

*Published January 9, 2026*

Portrait of Scarlett Attensil.

by Scarlett Attensil

Every conversation contains signals your ML models need. Customer calls reveal buying intent. Support tickets expose product friction. Interview transcripts capture technical depth. The problem? Those signals are buried in thousands of words of unstructured text.

This tutorial shows you how to build a data extraction pipeline that turns messy transcripts into structured JSON - using AgentControl to control everything (models, prompts, schemas) without redeploying.

**What you'll build:** A pipeline that extracts 50-70 structured fields from any transcript - sentiment scores, engagement metrics, binary signals, text statistics - all instantly configurable through the LaunchDarkly UI.

**The key insight:** When you discover that `customer_question_count` predicts engagement better than talk time, or that Opus 4.5 handles technical jargon better than GPT-5.2, you can update your extraction logic immediately. No PR, no deploy, no waiting.

> **Ready to build?** Clone the [complete example repository](https://github.com/launchdarkly-labs/scarlett-feature-extraction) to start extracting structured data from your transcripts in minutes.

## The problem with unstructured text

Your organization has valuable signals buried in text such as customer conversations, support tickets, interview transcripts, product reviews. Tools like Gong, Chorus, and conversation intelligence platforms are excellent for their designed purpose, but you need something different: extracting specific features for your ML models, with a schema you control completely.

**What you typically have:**

```lines wrap theme={null}
"Yeah, so we've been looking at different solutions. The other vendor's
pricing was reasonable but their timeline was concerning. We need this
rolled out before Q3..."
```

**What your models need:**

```json lines wrap theme={null}
{
  "alternatives_mentioned": true,
  "pricing_sentiment": 0.3,
  "timeline_mentioned": true,
  "urgency_score": 0.8,
  "decision_timeframe": "Q3"
}
```

## How the pieces fit together

```lines wrap theme={null}
┌─────────────┐      ┌──────────────────┐      ┌─────────────┐
│  Your Text  │ ---> │ Vercel AI Gateway│ ---> │     LLM     │
└─────────────┘      │   (unified API)  │      │ (GPT/Claude)│
                     └──────────────────┘      └─────────────┘
                              ↑                        │
                              │                        ↓
                     ┌──────────────────┐      ┌─────────────┐
                     │  LaunchDarkly    │      │  Structured │
                     │   config      │      │    JSON     │
                     │ (model, prompts, │      └─────────────┘
                     │  6 tool schemas) │
                     └──────────────────┘
```

The model classifies each transcript as prospecting, discovery, demo, proposal, technical, or customer success in its `call_category` field, and the pipeline labels the row with the matching tool. The extraction itself uses the first attached tool's schema, which carries the core fields all six tools share.

**What stays in LaunchDarkly:**

* Model selection (GPT-5.2, Opus 4.5, Gemini 3)
* System and user prompts
* All 6 extraction tool schemas (50-70 fields each)
* Temperature and other parameters
* The classification instructions in the system prompt
* Targeting rules for different use cases

**What stays in your code:**

* Reading input files
* Passing transcript text
* Writing output CSV/JSON

## Why this approach

### Change schemas in 2 minutes, not 2 sprints

This separation matters when you discover issues in production. For example, if the model is classifying certain transcript types incorrectly, you can instantly adjust the prompt or model using LaunchDarkly - takes 2 minutes in the UI instead of a hotfix deploy.

**Key benefits:**

* **Instant schema updates**: Add fields to any of the 6 tools when you discover new predictive signals.
* **[A/B testing models](https://launchdarkly.com/docs/home/agentcontrol/experimentation.md)**: Test Google Gemini 3 vs Anthropic Claude Opus 4.5 to see which classifies and extracts more accurately.
* **[Schemas as tools](https://launchdarkly.com/docs/home/agentcontrol/tools.md)**: Six schemas (prospecting, discovery, demo, proposal, technical, customer success) live in LaunchDarkly as tools. You can edit fields without a deploy.
* **Privacy compliance**: Different configurations for different regions using [targeting rules](https://launchdarkly.com/docs/home/flags/segment-targeting.md) - GDPR-compliant schemas for European customers.

### One gateway, all the models

Vercel brings specific advantages for data extraction workloads:

* **Server-sent events for real-time progress**: Processing 1,000 transcripts? Stream progress updates to your UI as each completes using the [Vercel AI SDK](https://sdk.vercel.ai/).
* **Automatic scaling**: From 1 transcript to 10,000 - Vercel functions scale without configuration.
* **Built-in reliability**: Automatic retries and failover when LLM providers have issues.
* **One credential everywhere**: The same `AI_GATEWAY_API_KEY` works locally and on Vercel deployments.
* **Unified LLM access**: One endpoint for OpenAI GPT-5.2, Anthropic Claude Opus 4.5, and Google Gemini 3 models through [Vercel AI Gateway](https://vercel.com/docs/ai-gateway).

![Extraction progress view showing transcript processing status](https://mintcdn.com/launchdarkly/AAfzx725JxtBqiAm/images/tutorials/data-extraction-pipeline/progress_screen.png?fit=max\&auto=format\&n=AAfzx725JxtBqiAm\&q=85\&s=8166d6c5adc0017084b91df237fd8d9c)

Real-time progress showing extraction status for batch processing

Deploy once, then tune everything through LaunchDarkly while Vercel handles the infrastructure.

## Complete setup

### Prerequisites

* Node.js 18+ and basic TypeScript knowledge
* LaunchDarkly account with [AgentControl enabled](https://launchdarkly.com/docs/home/agentcontrol) ([quickstart guide](https://launchdarkly.com/docs/home/agentcontrol/quickstart))
* Vercel account with an AI Gateway API key. The free tier works with the bootstrap's default model, `gpt-4o-mini`; Claude models need paid gateway credits.
* 100+ transcripts or documents to process (any format)

### Quick start

Clone the [complete example](https://github.com/launchdarkly-labs/scarlett-feature-extraction) to skip setup and start extracting immediately:

```bash lines wrap theme={null}
git clone https://github.com/launchdarkly-labs/scarlett-feature-extraction.git
cd scarlett-feature-extraction
```

### Install dependencies

```bash lines wrap theme={null}
# Node.js dependencies for the extraction pipeline
npm install @launchdarkly/node-server-sdk @launchdarkly/ai-server@0.3.0
npm install ai @ai-sdk/openai
```

> **SDK Documentation**: The [LaunchDarkly Node.js AI SDK](https://launchdarkly.com/docs/sdk/ai/node-js) reference covers all SDK features. This tutorial calls the Vercel AI SDK through a small handler of its own rather than a provider package, which means `ai` and `@ai-sdk/openai` are ordinary dependencies here.

For ML model training (optional), set up a Python environment:

```bash lines wrap theme={null}
python3 -m venv venv && source venv/bin/activate
pip install catboost scikit-learn pandas numpy joblib requests python-dotenv
```

> **Note**: For Python-based pipelines, see the [LaunchDarkly Python AI SDK](https://launchdarkly.com/docs/sdk/ai/python) (doesn't include Vercel provider).

### Configure environment

```bash lines wrap theme={null}
# 1. Configure environment variables
cp .env.example .env
# Add your keys to .env:
#   LAUNCHDARKLY_SDK_KEY=sdk-xxxxx
#   LD_API_KEY=api-xxxxx (for bootstrap only)
#   LD_PROJECT_KEY=your-project (for bootstrap only)
#   AI_GATEWAY_API_KEY=your-gateway-key

# 2. Or, in a linked Vercel project, pull a short-lived token instead
npx vercel env pull  # Generates VERCEL_OIDC_TOKEN, refresh every 12 hours

# 3. Bootstrap config (one-time)
python bootstrap/create_unified_config.py
```

**Environment variables explained:**

* `LAUNCHDARKLY_SDK_KEY`: Runtime SDK key for feature flags.
* `AI_GATEWAY_API_KEY`: Required for Vercel deployments, and works locally too.
* `VERCEL_OIDC_TOKEN`: Optional local fallback, generated by `npx vercel env pull`. Used only when `AI_GATEWAY_API_KEY` is unset.
* `LD_API_KEY` & `LD_PROJECT_KEY`: Only for bootstrap script to create configs.

### Project structure

```lines wrap theme={null}
your-project/
├── bootstrap/
│   └── create_unified_config.py    # Creates config (run once)
├── lib/
│   ├── pipeline.ts                 # Extraction pipeline
│   └── launchdarkly-client.ts      # LaunchDarkly AI SDK integration
├── app/
│   ├── page.tsx                    # Upload UI
│   └── api/
│       └── extract-stream/         # API endpoint for extraction
├── LAUNCHDARKLY_TOOLS.json         # Your field schemas (customize this!)
└── .env                             # Your API keys
```

### configuration

#### Where the extraction schemas live

The field definitions and extraction schemas are stored in two key locations:

1. **`LAUNCHDARKLY_TOOLS.json`** - Contains all field schemas:
   * 40 core fields shared across all tools (sentiment scores, engagement metrics, etc.)
   * Tool-specific fields for each document type
   * This file defines what data you'll extract

2. **`bootstrap/create_unified_config.py`** - Sets up LaunchDarkly:
   * Reads the schemas from `LAUNCHDARKLY_TOOLS.json`
   * Creates the config in LaunchDarkly named `transcript-extraction-unified`
   * Attaches all 6 extraction tools to this single config
   * Safe to re-run: It deletes and recreates only its own config and tools.

#### The 6 extraction tools

Each tool is defined in `LAUNCHDARKLY_TOOLS.json` with specific fields for different call types:

**Prospecting tool** (`extract_prospecting_features` - 50 fields)

* **Where it's defined**: `LAUNCHDARKLY_TOOLS.json` → `variation_a_prospecting`
* **Use case**: First contact, cold outreach, gatekeeper conversations.
* **Example fields**: `gatekeeper_encountered`, `callback_scheduled`, `interest_level`

**Discovery tool** (`extract_discovery_features` - 55 fields)

* **Where it's defined**: `LAUNCHDARKLY_TOOLS.json` → `variation_b_discovery`
* **Use case**: Qualification calls, needs assessment.
* **Example fields**: `budget_confirmed`, `authority_level`, `qualification_score`

**Demo tool** (`extract_demo_features` - 65 fields)

* **Where it's defined**: `LAUNCHDARKLY_TOOLS.json` → `variation_c_demo`
* **Use case**: Product demonstrations, feature walkthroughs.
* **Example fields**: `customer_wow_moments`, `demo_effectiveness_score`, `trial_poc_requested`

**Proposal tool** (`extract_proposal_features` - 60 fields)

* **Where it's defined**: `LAUNCHDARKLY_TOOLS.json` → `variation_d_proposal`
* **Use case**: Pricing discussions, contract negotiations.
* **Example fields**: `close_probability`, `discount_requested`, `blockers_to_close`

**Technical tool** (`extract_technical_features` - 70 fields)

* **Where it's defined**: `LAUNCHDARKLY_TOOLS.json` → `variation_e_technical`
* **Use case**: Architecture reviews, technical deep-dives.
* **Example fields**: `technical_fit_score`, `technical_risk_score`, `scalability_concerns`

**Customer Success tool** (`extract_customer_success_features` - 60 fields)

* **Where it's defined**: `LAUNCHDARKLY_TOOLS.json` → `variation_f_customer_success`
* **Use case**: Quarterly Business Reviews (QBRs), renewal discussions, expansion opportunities.
* **Example fields**: `account_health_score`, `renewal_likelihood`, `churn_risk`

> **ML Preview**: These extracted fields become features for predictive models - Part 2 shows you how to train models that predict deal outcomes, customer churn, and more using the data you extract here.

#### How to customize the schemas

You have two options for customizing your extraction schemas:

**Option 1: Edit directly in LaunchDarkly UI**

1. Navigate to LaunchDarkly → AgentControl → `transcript-extraction-unified`
2. Click on any tool (e.g., "Extract Prospecting Features")
3. Edit the JSON schema directly in the UI - add/remove fields instantly
4. Save changes - they apply immediately, no deployment needed!

This is perfect for quick iterations - discover a new predictive signal? Add it in 30 seconds.

**Option 2: Update via code**

1. Edit `LAUNCHDARKLY_TOOLS.json`:

```json lines wrap theme={null}
// Add a new field to prospecting tool:
"variation_a_prospecting": {
  "function": {
    "parameters": {
      "properties": {
        // Add your custom field here:
        "competitor_switching_intent": {
          "type": "boolean",
          "description": "Intent to switch from competitor"
        }
      }
    }
  }
}
```

2. Re-run bootstrap to update LaunchDarkly:

```bash lines wrap theme={null}
python bootstrap/create_unified_config.py
```

3. Run an extraction. It picks up the new schema automatically, with no code changes needed.

Start with 100 transcripts to validate your schemas. You'll likely learn more from the first 100 extractions than weeks of planning. Watch the `call_category` and `tool_used` columns and refine the prompt if transcripts are misclassified.

## Implementation & usage

### Core implementation

Here's the extraction implementation:

```typescript expandable lines wrap theme={null}
// Source: github.com/launchdarkly-labs/scarlett-feature-extraction
// lib/launchdarkly-client.ts (simplified)
import * as ld from "@launchdarkly/node-server-sdk";
import {
  config,
  createHandler,
  initClient,
  parseTemplate,
} from "@launchdarkly/ai-server";
import type { LDContext } from "@launchdarkly/ai-server";
import { createOpenAI } from "@ai-sdk/openai";
import { generateText, jsonSchema, Output } from "ai";

// On Vercel deployments only AI_GATEWAY_API_KEY works: VERCEL_OIDC_TOKEN
// authenticates to Vercel platform services, not to the gateway. Locally the
// API key still wins, so a stale VERCEL_OIDC_TOKEN from `npx vercel env pull`
// (it expires every 12 hours) is only used when no API key is set.
function gatewayApiKey(): string {
  const isVercelDeployment = process.env.VERCEL === "1";
  const apiKey =
    process.env.AI_GATEWAY_API_KEY?.trim() ||
    (isVercelDeployment ? undefined : process.env.VERCEL_OIDC_TOKEN?.trim());

  if (!apiKey) {
    throw new Error(
      "No Vercel AI Gateway API key found. Set AI_GATEWAY_API_KEY environment variable"
    );
  }

  return apiKey;
}

// Built on first use rather than at module load, so a missing gateway key
// fails the request that needs it instead of the Next.js build that imports
// this file.
let gateway: ReturnType<typeof createOpenAI> | null = null;

function vercelGateway(): ReturnType<typeof createOpenAI> {
  if (!gateway) {
    gateway = createOpenAI({
      baseURL: "https://ai-gateway.vercel.sh/v1",
      apiKey: gatewayApiKey(),
    });
  }
  return gateway;
}

// Map LaunchDarkly model parameters to Vercel AI SDK parameters.
function mapParameters(
  parameters: Record<string, unknown> | undefined
): Record<string, unknown> {
  if (!parameters) return {};
  const mapping: Record<string, string> = {
    max_tokens: "maxOutputTokens",
    max_completion_tokens: "maxOutputTokens",
    temperature: "temperature",
    top_p: "topP",
    top_k: "topK",
    presence_penalty: "presencePenalty",
    frequency_penalty: "frequencyPenalty",
    stop: "stopSequences",
    seed: "seed",
  };
  const params: Record<string, unknown> = {};
  for (const [from, to] of Object.entries(mapping)) {
    if (parameters[from] !== undefined) params[to] = parameters[from];
  }
  return params;
}

// Structured-output strict mode only accepts schemas where every property is
// required and no extra properties are allowed. The extraction schemas leave
// most fields optional, so make those nullable instead. Without strict mode
// the model is free to skip required fields or echo the schema back.
function toStrictSchema(schema: Record<string, any>): Record<string, any> {
  if (schema.type === "array" && schema.items) {
    return { ...schema, items: toStrictSchema(schema.items) };
  }
  if (schema.type !== "object" || !schema.properties) return schema;
  const required = new Set<string>(schema.required ?? []);
  const properties: Record<string, any> = {};
  for (const [name, property] of Object.entries<any>(schema.properties)) {
    const strict = toStrictSchema(property);
    properties[name] = required.has(name)
      ? strict
      : { anyOf: [strict, { type: "null" }] };
  }
  return {
    ...schema,
    properties,
    required: Object.keys(properties),
    additionalProperties: false,
  };
}

// Drop the nulls strict mode uses to stand in for omitted optional fields.
function dropNulls(value: Record<string, unknown>): Record<string, unknown> {
  return Object.fromEntries(
    Object.entries(value).filter(([, field]) => field !== null)
  );
}

// A handler is the seam between LaunchDarkly and whatever actually calls the
// model. The first argument says which configs it can serve: any provider,
// in messages mode. The config's provider is whoever owns the model (openai,
// anthropic, google), and the gateway fronts all of them.
const extractionHandler = createHandler(
  ["*", "messages"],
  async (aiConfig, transcript = "", _toolHandlers, variables = {}) => {
    // Tools arrive as a keyed map. All six share the core fields, so the
    // first one's parameters double as the output schema.
    const schema = Object.values(aiConfig.tools ?? {})[0]?.parameters;
    if (!schema) throw new Error("No tools found in AI config");

    // invoke() forwards `variables` without substituting them, so a handler
    // you write yourself has to interpolate the prompt. Skip this and your
    // mustache placeholders reach the model verbatim.
    const system = (aiConfig.messages ?? [])
      .filter((message) => message.role === "system")
      .map((message) => parseTemplate(message.content, variables))
      .join("\n");

    const result = await generateText({
      ...mapParameters(aiConfig.model.parameters),
      model: vercelGateway().chat(
        `${aiConfig.provider.name.toLowerCase()}/${aiConfig.model.name}`,
      ),
      ...(system ? { system } : {}),
      messages: [{ role: "user", content: `Transcript:\n\n${transcript}` }],
      output: Output.object({ schema: jsonSchema(toStrictSchema(schema)) }),
    });

    // The SDK derives total tokens from input + output, so there is no
    // total_tokens field to return.
    return {
      output: dropNulls(result.output as Record<string, unknown>),
      usage: {
        input_tokens: result.usage.inputTokens,
        output_tokens: result.usage.outputTokens,
      },
    };
  },
);

export class LaunchDarklyAIClient {
  private ldClient!: ld.LDClient;

  async initialize(): Promise<void> {
    this.ldClient = ld.init(process.env.LAUNCHDARKLY_SDK_KEY!);
    await this.ldClient.waitForInitialization({ timeout: 5 });
    // Hand the already-initialized client to the AI SDK. There is no separate
    // AI client object to keep: config() uses this one. The cast is needed
    // because node-server-sdk's close() returns void where the AI SDK's
    // LDClientInterface declares Promise<void>.
    await initClient(
      this.ldClient as unknown as Parameters<typeof initClient>[0],
    );
  }

  async extractStructuredFeatures(params: {
    configKey: string;  // "transcript-extraction-unified"
    context: LDContext;
    transcript: string;
  }): Promise<Record<string, any>> {
    // One call evaluates the config, picks the model named in it, runs the
    // extraction, and records tokens, latency, and success or error.
    const result = await config({
      key: params.configKey,
      handler: extractionHandler,
    }).invoke<Record<string, any>>(params.transcript, params.context);

    // The handler returned an object, so the response already is one.
    return result.response;
  }
}
```

The repository's version also maps LaunchDarkly provider and model names to the gateway's names where they differ, such as `gemini` to `google` and `claude-sonnet-4-5` to `claude-sonnet-4.5`.

> [!NOTE]
>
> There is no fallback argument. `invoke()` throws if the config has targeting
> off, if the variation is invalid, or if LaunchDarkly is unreachable. The
> decision about what to do in those cases stays in your application. If you
> need to branch before spending a model call, ask first with `inspectConfig()`,
> which returns `{ enabled, config, meta }`, never throws, and sends no events:
>
> ```typescript theme={null}
> import { inspectConfig } from "@launchdarkly/ai-server";
>
> const { enabled } = await inspectConfig(configKey, context);
> if (!enabled) {
>   return { skipped: true };  // queue the transcript for a later run
> }
> ```

### How to run the extraction pipeline

Once your schemas are configured, running extraction is straightforward:

```bash lines wrap theme={null}
# 1. Start the development server
npm run dev

# 2. Open http://localhost:3000
# 3. Click the upload box and choose a folder of transcripts
#    (every .txt and .md file in it is processed; try data/test-transcripts)
# 4. Click "Extract Features"
# 5. The CSV with all extracted fields downloads automatically
```

Each row in the CSV records the model's `call_category` and the matching `tool_used` label. A transcript that isn't a sales call comes back with a `call_category` such as `invalid` and a `tool_used` of `unknown`.

## Beyond sales calls - what else you can extract

This architecture works for any unstructured data extraction need. The pipeline code never changes - just the configuration.

**Support ticket analysis**

* Extract urgency scores, issue categories, product areas, customer effort scores
* Route urgent tickets to detailed schemas, low-priority to streamlined ones
* **ML applications**: Predict escalation likelihood, estimate resolution time, auto-assign to right team, identify product bugs from patterns

**Customer review mining**

* Pull out feature mentions with sentiment, competitor comparisons, recommendation likelihood
* Different product lines can use different configs with tailored extraction tools
* **ML applications**: Predict NPS scores, identify feature requests, forecast churn from negative patterns, cluster customers by satisfaction drivers

**Interview transcript processing**

* Extract technical competency signals, communication clarity, culture fit indicators
* Different roles need different schemas - handle this through LaunchDarkly targeting rules
* **ML applications**: Predict candidate success probability, identify skill gaps, score cultural alignment, reduce hiring bias through standardized signals

**Medical consultation transcripts**

* Extract symptoms, treatment discussions, medication mentions, follow-up requirements
* Ensure HIPAA compliance by redacting PII before extraction
* **ML applications**: Predict readmission risk, identify medication adherence issues, flag potential diagnoses for review, optimize appointment scheduling

**Legal document analysis**

* Extract contract terms, risk clauses, obligations, and deadlines
* Route different document types (NDAs, MSAs, employment contracts) to specialized schemas
* **ML applications**: Assess contract risk scores, identify non-standard terms, predict negotiation outcomes, flag compliance issues

**Earnings call transcripts**

* Extract forward-looking statements, financial metrics, competitive positioning
* Capture management sentiment and guidance changes
* **ML applications**: Predict stock price movements, identify leadership confidence levels, detect financial health indicators, compare guidance to historical accuracy

**Privacy and sensitive data**

* Add PII detection step before extraction - scan for emails, phone numbers, SSNs, names
* Either redact (\[REDACTED]) or skip extraction based on compliance requirements
* **ML applications**: Route by geography using LaunchDarkly targeting - EU transcripts use privacy-safe schemas, other regions get full extraction

## When to use this approach

**Use this when:**

* Processing 100-10,000 documents monthly
* Schema needs frequent iteration
* Different document types need different treatment
* You're bootstrapping training data

**Skip this when:**

* Processing millions of documents (use traditional NLP)
* Schema is fixed and proven
* You need sub-second latency
* Documents follow strict templates

## What's next

In Part 2, I'll show how to use these extracted features for ML models. The challenge: sparse outcomes (most deals don't close, most candidates aren't hired). I'll demonstrate a zero-inflated regression approach that actually works with real-world data.

Ready to build? Start with your messiest transcripts - that's where you'll learn what features really matter.

## Further reading

* [CI/CD for AgentControl](https://launchdarkly.com/docs/tutorials/aic-cicd.md) - Run evaluations on every pull request and gate the merge on the result
* [Multi-agent systems with LangGraph](https://launchdarkly.com/docs/tutorials/agents-langgraph.md) - Build complex AI workflows
* [Smart AI Agent Targeting with Model Context Protocol (MCP) Tools](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting.md) - Route extraction jobs to different schemas by user segment or geography
* [Evaluate LLM code generation with LLM-as-judge evaluators](https://launchdarkly.com/docs/tutorials/custom-evals-claude-code.md) - Custom judges for grading specialized outputs
* [Build AgentControl configs with Agent Skills](https://launchdarkly.com/docs/tutorials/agent-skills-quickstart.md) - Spin up new extraction configs from your coding assistant
