Prompt

How do I set up a chat completion API for extraction workflows with streaming responses?

Artificial Intelligence / AI Platforms2 observationsLast seen Nov 19, 2026

Latest observation

Nov 19, 2026OpenAI APIWeb search: off

To set up a chat completion API for extraction workflows with streaming responses, you generally want a pipeline like this:

  1. Send the model a structured extraction prompt
  2. Stream tokens back as they’re generated
  3. Parse the output incrementally or after completion
  4. Validate and store the extracted fields

1) Design the extraction task

For extraction, the model should return a fixed schema rather than free-form text.

Example schema:

{
  "invoice_number": "",
  "date": "",
  "vendor": "",
  "total": "",
  "line_items": [
    {
      "description": "",
      "quantity": "",
      "unit_price": ""
    }
  ]
}

Use a system prompt like:

Extract the following fields from the provided document. Return only valid JSON matching the schema. If a field is missing, use null.

2) Call a chat completion endpoint with streaming enabled

Typical request shape:

Python example

from openai import OpenAI

client = OpenAI()

stream = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[
        {"role": "system", "content": "Extract fields and return only valid JSON."},
        {"role": "user", "content": "Invoice text goes here..."}
    ],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)

JavaScript example

import OpenAI from "openai";

const client = new OpenAI();

const stream = await client.chat.completions.create({
  model: "gpt-4.1-mini",
  messages: [
    { role: "system", content: "Extract fields and return only valid JSON." },
    { role: "user", content: "Invoice text goes here..." }
  ],
  stream: true,
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
}

3) Prefer structured outputs if available

For extraction workflows, the best practice is usually to request structured JSON output or use a JSON schema / tool calling approach so the response is easier to validate.

If your API supports it, define a schema like:

  • required fields
  • optional fields
  • types
  • arrays/objects

This reduces post-processing errors.

4) Handle streaming carefully

With streaming, the model may send partial JSON fragments. Common approaches:

Option A: Buffer until done

  • Append all streamed text
  • Parse once at the end
  • Simpler and more reliable for JSON extraction

Option B: Incremental parsing

  • Use a streaming JSON parser
  • Useful for large outputs
  • More complex

For most extraction workflows, buffering until completion is the safest approach.

5) Validate the result

After the stream finishes:

  • Parse JSON
  • Validate against your schema
  • Normalize values (dates, currency, numbers)
  • Flag missing or ambiguous fields for review

Example validation flow:

import json

result_text = collected_text
data = json.loads(result_text)

assert "invoice_number" in data

6) Recommended architecture

A practical extraction service often looks like:

  • API endpoint receives document text or OCR output
  • Prompt builder creates extraction prompt
  • LLM call with streaming enabled
  • Stream handler collects output
  • Validator checks schema
  • Persistence layer stores structured result
  • Fallback review for low-confidence cases

7) Best practices

  • Keep prompts explicit: “Return only JSON”
  • Use a strict schema
  • Set low temperature for consistency
  • Add examples if needed
  • Handle malformed output gracefully
  • Log raw outputs for debugging
  • Use retries for parse failures

8) Example prompt

You are an information extraction system.
Extract the following fields from the document:
- invoice_number
- invoice_date
- vendor_name
- total_amount
- currency

Return only valid JSON in this format:
{
  "invoice_number": null,
  "invoice_date": null,
  "vendor_name": null,
  "total_amount": null,
  "currency": null
}
If a field is not present, use null.

If you want, I can also give you:

  1. a full Flask/FastAPI backend example,
  2. a Node.js SSE streaming example, or
  3. an end-to-end structured JSON extraction template.

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (2 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.