The CircaOS cookbook

Six archetypal patterns. Copy, paste, ship.
On this page: Verify signature · Verify attestation · SDKs

Every production LLM feature ends up being one of about six shapes: extracting structured data, classifying with reasons, routing to a handler, scoring on a calibrated scale, taking a bounded agent step, or doing all of the above in bulk. This page shows each shape as a copy-paste recipe on the CircaOS substrate.

What's different here vs. the same recipes against a hosted frontier API: every output below is schema-valid by construction. No retry loops, no permissive parsers, no fallback paths. The decoder is physically constrained to emit conforming tokens. Why.

All recipes assume COGOS_API_KEY is set in your env. If you don't have one yet, grab a $29/mo Operator Starter key — one curl, one minute.


1 Extract structured data from messy text

The most common pattern. Take human prose, return a row of structured data ready to insert into a database. Min/max constraints catch most of the edge cases that would otherwise surface as bad data downstream.

curlcurl -s https://cogos.5ceos.com/v1/chat/completions \
  -H "Authorization: Bearer $COGOS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "cogos-tier-b",
    "messages": [{"role":"user","content":"Acme Industries reported Q4 results yesterday, with annual revenue of $487 million for fiscal year 2025."}],
    "response_format": {
      "type":"json_schema",
      "json_schema": {
        "name":"filing",
        "strict":true,
        "schema":{
          "type":"object",
          "required":["company","fiscal_year","revenue_musd"],
          "properties":{
            "company":{"type":"string","minLength":1},
            "fiscal_year":{"type":"integer","minimum":1900,"maximum":2100},
            "revenue_musd":{"type":"number","minimum":0}
          }
        }
      }
    }
  }'
Lesson: schema constraints (minimum, maximum, minLength) are enforced by the decoder. The model can't emit fiscal_year: 0 or revenue_musd: -1 — non-conforming integers have zero probability mass.

2 Classify with confidence + reason

Enum schema for the label, plus an optional reasoning field for the model's justification. Pattern for content moderation, intent detection, sentiment with rationale.

curlcurl -s https://cogos.5ceos.com/v1/chat/completions \
  -H "Authorization: Bearer $COGOS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "cogos-tier-b",
    "messages": [{"role":"user","content":"Classify the urgency: \"My demo is in 30 minutes and the build is broken.\""}],
    "response_format": {
      "type":"json_schema",
      "json_schema": {
        "name":"classification",
        "strict":true,
        "schema":{
          "type":"object",
          "required":["label","reasoning"],
          "properties":{
            "label":{"type":"string","enum":["low","medium","high","critical"]},
            "reasoning":{"type":"string","maxLength":280}
          }
        }
      }
    }
  }'
Lesson: enum on the label means the model literally cannot return any string outside your allowed set. No "high-ish" or "very-high" or random new categories appearing in your data three months in.

3 Triage / route to a handler

Discriminated-union schema. The type field tells your code which handler to dispatch to; the per-type fields are bound to that branch. Replaces giant if/else routing trees with a single deterministic LLM call.

curlcurl -s https://cogos.5ceos.com/v1/chat/completions \
  -H "Authorization: Bearer $COGOS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "cogos-tier-b",
    "messages": [{"role":"user","content":"Customer email: \"My charge for $99 last week was supposed to be $29. Please refund the difference.\""}],
    "response_format": {
      "type":"json_schema",
      "json_schema": {
        "name":"route",
        "strict":true,
        "schema":{
          "type":"object",
          "required":["handler","priority"],
          "properties":{
            "handler":{"type":"string","enum":["billing","support","sales","legal","spam"]},
            "priority":{"type":"string","enum":["p0","p1","p2","p3"]},
            "summary":{"type":"string","maxLength":120}
          }
        }
      }
    }
  }'
Lesson: the dispatch happens on the LLM's side, but the contract is yours. Your code switches on handler with a guarantee the value is one of your five enum entries — no defensive default branch needed.

4 Score on a calibrated scale

Integer schema with bounded range. Pattern for quality scoring, rubric grading, confidence thresholds. Pair with reasoning to make the score auditable.

curlcurl -s https://cogos.5ceos.com/v1/chat/completions \
  -H "Authorization: Bearer $COGOS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "cogos-tier-b",
    "messages": [{"role":"user","content":"Score this PR description for clarity (0-10): \"fix bug\""}],
    "response_format": {
      "type":"json_schema",
      "json_schema": {
        "name":"score",
        "strict":true,
        "schema":{
          "type":"object",
          "required":["score","reasoning"],
          "properties":{
            "score":{"type":"integer","minimum":0,"maximum":10},
            "reasoning":{"type":"string","maxLength":200}
          }
        }
      }
    }
  }'
Lesson: the minimum/maximum integer constraint means downstream code can assert 0 <= score <= 10 without ever firing. The decoder enforces it at the token level, before the bytes reach you.

5 Bounded agent step (tool-use shape)

Allowed actions as an enum, action arguments in a sibling object. The agent decides which action; you decide which actions are even possible. The shape maps cleanly onto common tool-use loop patterns.

curlcurl -s https://cogos.5ceos.com/v1/chat/completions \
  -H "Authorization: Bearer $COGOS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "cogos-tier-a",
    "messages": [{"role":"user","content":"User said: \"What is 47 times 23?\". Pick the right tool."}],
    "response_format": {
      "type":"json_schema",
      "json_schema": {
        "name":"agent_step",
        "strict":true,
        "schema":{
          "type":"object",
          "required":["action","args"],
          "properties":{
            "action":{"type":"string","enum":["calculator","web_search","read_file","reply_directly"]},
            "args":{"type":"object","additionalProperties":true},
            "rationale":{"type":"string","maxLength":160}
          }
        }
      }
    }
  }'
Lesson: the agent cannot invent a new tool name. If it suggests "action":"shell_exec" and that's not in your enum, the decoder won't emit it. Bounded action surface = bounded blast radius.

6 Multi-extraction (array of structured items)

Array schema with maxItems and per-item required fields. Pattern for pulling multiple entities, line items, or events out of a single document in one call.

curlcurl -s https://cogos.5ceos.com/v1/chat/completions \
  -H "Authorization: Bearer $COGOS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "cogos-tier-b",
    "messages": [{"role":"user","content":"Extract up to 3 line items from: \"Office supplies: 5 reams paper @ $4.50, 2 boxes pens @ $12, and 1 stapler @ $18.\""}],
    "response_format": {
      "type":"json_schema",
      "json_schema": {
        "name":"line_items",
        "strict":true,
        "schema":{
          "type":"object",
          "required":["items"],
          "properties":{
            "items":{
              "type":"array",
              "minItems":0,
              "maxItems":10,
              "items":{
                "type":"object",
                "required":["description","quantity","unit_price"],
                "properties":{
                  "description":{"type":"string","minLength":1},
                  "quantity":{"type":"integer","minimum":1},
                  "unit_price":{"type":"number","minimum":0}
                }
              }
            }
          }
        }
      }
    }
  }'
Lesson: maxItems bounds the worst-case payload size. Per-item required fields mean every element in the array is shaped the same way — no missing fields on item #3 because the model "forgot."

Verify a response signature

Every /v1/* response carries an X-Cogos-Signature header: HMAC-SHA256(hmac_secret, raw_response_body) in lowercase hex. Re-compute it on your side and compare with constant-time equality. If it doesn't match, the body was tampered with in transit — reject the response.

Your HMAC secret is displayed once, alongside your API key, on the post-checkout success page. Store it the same way you store the API key.

pythonimport hmac, hashlib, requests

API_KEY = os.environ["COGOS_API_KEY"]
HMAC_SECRET = os.environ["COGOS_HMAC_SECRET"]

r = requests.post(
  "https://cogos.5ceos.com/v1/chat/completions",
  headers={"Authorization": f"Bearer {API_KEY}"},
  json={"model":"cogos-tier-b","messages":[{"role":"user","content":"hi"}]},
)

raw = r.content  # bytes, NOT r.text — must be the exact bytes the server signed
expected = hmac.new(HMAC_SECRET.encode(), raw, hashlib.sha256).hexdigest()
got = r.headers["X-Cogos-Signature"]

if not hmac.compare_digest(expected, got):
    raise RuntimeError("response signature mismatch — reject")

data = r.json()
nodeimport crypto from "node:crypto";

const r = await fetch("https://cogos.5ceos.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.COGOS_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ model: "cogos-tier-b", messages: [{ role: "user", content: "hi" }] }),
});

const raw = Buffer.from(await r.arrayBuffer());
const expected = crypto.createHmac("sha256", process.env.COGOS_HMAC_SECRET).update(raw).digest("hex");
const got = r.headers.get("x-cogos-signature");

const ok = expected.length === got.length &&
  crypto.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(got, "hex"));
if (!ok) throw new Error("response signature mismatch — reject");

const data = JSON.parse(raw.toString("utf8"));
Lesson: sign the bytes, not the parsed JSON. Re-serializing changes whitespace and key order, and the HMAC won't match. Always compare with hmac.compare_digest / crypto.timingSafeEqual; == leaks length-prefix information through timing.

Verify a per-response attestation token

Every /v1/* response also carries an X-Cogos-Attestation header containing a small Ed25519-signed token. Where X-Cogos-Signature proves "this body wasn't tampered with in transit," the attestation token proves something much stronger: this exact response was emitted by a specific build of CircaOS, against a specific request, at a specific position in the audit chain.

The token binds five things cryptographically:

Signed with an Ed25519 key bound to the running process. Fetch the public PEM from /attestation.pub to verify. The wire format is <payload_b64url>.<signature_b64url> — JWT-style separator, no JWT header (algorithm is pinned to Ed25519 by spec, no negotiation = no alg-confusion attack surface).

This is what no other AI vendor emits. Frontier APIs sign only at the TLS layer — you can't prove later, to a regulator, that a specific response actually came from a specific build of their substrate, at a specific position in their audit chain. With CircaOS attestation, you keep the token alongside the response and you hold the receipt forever. If we ever rewrote our audit log after the fact, no path through the rewritten log would reproduce a chain_head you already wrote down.
pythonimport base64, hashlib, json, os
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from cryptography.exceptions import InvalidSignature
import requests

API_KEY = os.environ["COGOS_API_KEY"]
BASE = "https://cogos.5ceos.com"

# 1. Make a request — capture body bytes, headers, token.
body = json.dumps({
  "model": "cogos-tier-b",
  "messages": [{"role":"user","content":"hi"}],
})
r = requests.post(
  f"{BASE}/v1/chat/completions",
  headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
  data=body,
)
raw_resp = r.content                                   # exact bytes the server signed
token = r.headers["X-Cogos-Attestation"]

# 2. Decode payload + signature.
def b64url_decode(s: str) -> bytes:
  return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

payload_b64, sig_b64 = token.split(".")
payload_json = b64url_decode(payload_b64)
sig = b64url_decode(sig_b64)
payload = json.loads(payload_json)

# 3. Verify the signature against the live pubkey.
pub_pem = requests.get(f"{BASE}/attestation.pub").content
pub_key = load_pem_public_key(pub_pem)
try:
  pub_key.verify(sig, payload_json)                    # raises on bad signature
except InvalidSignature:
  raise RuntimeError("attestation signature invalid — reject")

# 4. Verify the bindings.
body_hash = hashlib.sha256(body.encode()).hexdigest()
canonical = f"POST\n/v1/chat/completions\n{payload['ts']}\n{body_hash}"
expected_req_hash = hashlib.sha256(canonical.encode()).hexdigest()
assert payload["req_hash"] == expected_req_hash, "request bind broken"

expected_resp_hash = hashlib.sha256(raw_resp).hexdigest()
assert payload["resp_hash"] == expected_resp_hash, "response bind broken — body tampered"

# 5. (Optional) record payload['chain_head'] + payload['rev'] alongside
# the response. Later you can cross-check chain_head against your own
# /v1/audit history; the rev field tells you exactly which CircaOS build
# emitted this response.
print(f"verified: rev={payload['rev']} chain_head={payload['chain_head'][:16]}...")
nodeimport crypto from "node:crypto";

const BASE = "https://cogos.5ceos.com";
const API_KEY = process.env.COGOS_API_KEY;

// 1. Make a request — capture exact bytes, headers, token.
const body = JSON.stringify({
  model: "cogos-tier-b",
  messages: [{ role: "user", content: "hi" }],
});
const r = await fetch(`${BASE}/v1/chat/completions`, {
  method: "POST",
  headers: { "Authorization": `Bearer ${API_KEY}`, "Content-Type": "application/json" },
  body,
});
const rawResp = Buffer.from(await r.arrayBuffer());
const token = r.headers.get("x-cogos-attestation");

// 2. Decode payload + signature (base64url, no padding).
const b64urlDecode = (s) => {
  const pad = s.length % 4 === 0 ? 0 : 4 - (s.length % 4);
  return Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat(pad), "base64");
};
const [payloadB64, sigB64] = token.split(".");
const payloadJson = b64urlDecode(payloadB64);
const sig = b64urlDecode(sigB64);
const payload = JSON.parse(payloadJson.toString("utf8"));

// 3. Verify the signature against the live pubkey.
const pubPem = await (await fetch(`${BASE}/attestation.pub`)).text();
const pubKey = crypto.createPublicKey(pubPem);
const ok = crypto.verify(null, payloadJson, pubKey, sig);
if (!ok) throw new Error("attestation signature invalid — reject");

// 4. Verify the bindings.
const bodyHash = crypto.createHash("sha256").update(body).digest("hex");
const canonical = `POST\n/v1/chat/completions\n${payload.ts}\n${bodyHash}`;
const expectedReqHash = crypto.createHash("sha256").update(canonical).digest("hex");
if (payload.req_hash !== expectedReqHash) throw new Error("request bind broken");

const expectedRespHash = crypto.createHash("sha256").update(rawResp).digest("hex");
if (payload.resp_hash !== expectedRespHash) throw new Error("response bind broken — body tampered");

console.log(`verified: rev=${payload.rev} chain_head=${payload.chain_head.slice(0, 16)}...`);
Lesson: the signature is over the token payload, not over the response body. A MITM that rewrites the body but keeps the original token will leave the token signature-valid — but resp_hash inside the token will no longer match sha256(body) you received. That hash mismatch is the detection mechanism. Always verify BOTH the Ed25519 signature AND the resp_hash bind.
Operational note: each container restart rotates the keypair. The fetch of /attestation.pub is therefore live, not cached — same operational shape as TLS cert rotation. Tokens you stored from a previous deploy can no longer be verified against the current pubkey; for long-lived court-defensible receipts, capture the pubkey alongside the token at issuance time.

SDKs

The curl recipes above are the ground truth, but for production code you probably want a typed client that handles bearer auth, HMAC verification, and attestation verification for you. The SDKs are published on PyPI and npm as cogos — same name, both registries.

Both wrap the same wire protocol and raise on any verification failure — tampering is impossible to ignore by accident. The SDKs are MIT-licensed and source-available at sdks/python/ and sdks/node/ in the repo.

Python

shellpip install cogos
pythonfrom cogos import Client

client = Client(api_key="sk-cogos-...", hmac_secret="...")
resp = client.chat.completions.create(
    model="cogos-tier-b",
    messages=[{"role": "user", "content": "Hello"}],
)
print(resp["choices"][0]["message"]["content"])
# HMAC + attestation auto-verified — raises if anything is tampered.

Node

shellnpm install cogos-client
javascriptimport { Cogos } from 'cogos-client';

const client = new Cogos({ apiKey: 'sk-cogos-...', hmacSecret: '...' });
const resp = await client.chat.completions.create({
  model: 'cogos-tier-b',
  messages: [{ role: 'user', content: 'Hello' }],
});
console.log(resp.choices[0].message.content);
// HMAC + attestation auto-verified — throws if anything is tampered.
Lesson: the SDKs wrap bearer auth, automatically verify the X-Cogos-Signature HMAC, and automatically verify the per-response X-Cogos-Attestation Ed25519 token (including req_hash and resp_hash bindings). Both raise on verification failure — you can't accidentally trust a tampered response.

Patterns we deliberately don't show

The viewports on 5ceos.com — TruthPulse, Cross-Exam, M&A Truth Report, Enron evidence corpus — are 5CEOs products built on this substrate. They're not copy-paste recipes; they're years of domain work in contradiction detection, commitment-drift tracking, and forensic evidence reconstruction. We sell those as products to enterprise customers.

What you get on cogos.5ceos.com is the substrate — the same primitive those products are built on. Combine the six recipes above and you have the building blocks for almost any production LLM feature you'd ship next week.


Next

See pricing → Run the demo Read the whitepaper

A pattern missing? Open an issue on the bench repo or email support@5ceos.com. The cookbook grows with what devs ask for.