package main
// Imports for every Go tab in this recipe
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"regexp"
"slices"
"strconv"
"strings"
"time"
)
const extractModel = "scaledown/extract"
var invoiceEntities = map[string]string{
"vendor": "Name of the company issuing the invoice",
"invoice_number": "Invoice number or reference",
"subtotal": "Subtotal before tax, with currency",
"vat": "VAT or sales tax amount, with currency",
"total": "Total amount due including tax, with currency",
"due_date": "Payment due date",
}
// A map has no order, so the field order lives here
var invoiceFields = []string{"vendor", "invoice_number", "subtotal", "vat", "total", "due_date"}
// The first test input, used as the "table" invoice in the worked example
const invoice = `INVOICE
Northwind Traders GmbH
Invoice No: NW-2026-0417
Date: 2026-09-30
Due: 2026-10-30
Consulting (10h) EUR 1,500.00
Cloud hosting (Sept) EUR 320.00
Subtotal EUR 1,820.00
VAT 19% EUR 345.80
Total due EUR 2,165.80`
type Entity struct {
Type string `json:"type"`
Text string `json:"text"`
Confidence float64 `json:"confidence"`
Start int `json:"start"`
End int `json:"end"`
}
type Usage struct {
InputTokens int `json:"input_tokens"`
Cost float64 `json:"cost"`
}
type responseBody struct {
Output []struct {
Type string `json:"type"`
Content []struct {
Type string `json:"type"`
Text *string `json:"text"`
} `json:"content"`
} `json:"output"`
Usage Usage `json:"usage"`
}
func extractInvoice(text string) ([]Entity, Usage, error) {
payload, err := json.Marshal(map[string]any{
"model": extractModel,
"input": text,
"provider": map[string]any{"options": map[string]any{"scaledown": map[string]any{"entities": invoiceEntities}}},
})
if err != nil {
return nil, Usage{}, err
}
req, err := http.NewRequest("POST", "https://openrouter.ai/api/v1/responses", bytes.NewReader(payload))
if err != nil {
return nil, Usage{}, err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := (&http.Client{Timeout: 60 * time.Second}).Do(req)
if err != nil {
return nil, Usage{}, err
}
defer res.Body.Close()
raw, err := io.ReadAll(res.Body)
if err != nil {
return nil, Usage{}, err
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, Usage{}, fmt.Errorf("extract %d: %s", res.StatusCode, raw)
}
var body responseBody
if err := json.Unmarshal(raw, &body); err != nil {
return nil, Usage{}, err
}
var outputText *string
for i := len(body.Output) - 1; i >= 0 && outputText == nil; i-- {
if body.Output[i].Type != "message" {
continue
}
for _, part := range body.Output[i].Content {
if part.Type == "output_text" {
outputText = part.Text
break
}
}
break
}
if outputText == nil {
return nil, Usage{}, fmt.Errorf("extract returned no output_text")
}
var extraction struct {
Entities []struct {
Type string `json:"type"`
Text string `json:"text"`
Confidence *float64 `json:"confidence"`
Start *int `json:"start"`
End *int `json:"end"`
} `json:"entities"`
}
if err := json.Unmarshal([]byte(*outputText), &extraction); err != nil {
return nil, Usage{}, err
}
// Unmarshal accepts a missing field as a zero value, so refuse an entity that lacks any field
entities := make([]Entity, 0, len(extraction.Entities))
for _, e := range extraction.Entities {
if e.Type == "" || e.Text == "" || e.Confidence == nil || e.Start == nil || e.End == nil {
return nil, Usage{}, fmt.Errorf("extract returned an entity with a missing field")
}
entities = append(entities, Entity{e.Type, e.Text, *e.Confidence, *e.Start, *e.End})
}
return entities, body.Usage, nil
}