The CircaOS cookbook
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.
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}
}
}
}
}
}'
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}
}
}
}
}
}'
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}
}
}
}
}
}'
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}
}
}
}
}
}'
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}
}
}
}
}
}'
"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}
}
}
}
}
}
}
}
}'
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"));
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:
req_hash—sha256(METHOD || " " || path || " " || ts || " " || sha256(body))of your requestresp_hash—sha256of the raw response body bytes you receivedrev— the cogos-api source revision SHA the response came fromchain_head— therow_hashof the audit row appended for this requestts— server-side issuance timestamp
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).
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)}...`);
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./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.
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
- Run the 90-second proof to verify everything above on your own machine.
- Read the technical whitepaper for the mechanism, bench methodology, and explicit limits.
- Clone the open determinism bench to verify the substrate keeps its promises over time.
- Pick a tier: $29/mo → $100K/yr, month-to-month, cancel any time.
A pattern missing? Open an issue on the bench repo or email support@5ceos.com. The cookbook grows with what devs ask for.