Prompt
How do I set up a chat completion API for extraction workflows with streaming responses?
Latest observation
To set up a chat completion API for extraction workflows with streaming responses, you generally want a pipeline like this:
- Send the model a structured extraction prompt
- Stream tokens back as they’re generated
- Parse the output incrementally or after completion
- 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:
- a full Flask/FastAPI backend example,
- a Node.js SSE streaming example, or
- an end-to-end structured JSON extraction template.
Brands