# TianSphere: full site content > AI engineering consultancy in Hong Kong. We put AI into products and systems: agents, LLM features and MCP servers, with every model choice backed by an eval. This file holds the full text of https://tiansphere.com for AI agents: every service, case study and published field note. For a short index, read https://tiansphere.com/llms.txt. TianSphere is an AI engineering consultancy in Hong Kong, founded by Tadej Polajnar. To start a project, email info@tiansphere.com or use https://tiansphere.com/contact. We reply within one working day. ## Services ### AI integration https://tiansphere.com/services/ai-integration Agents and LLM features inside your product and internal systems, built for real users and real data. Most AI features stall between demo and production. The prototype works on ten examples, then meets real data, real permissions and real users. We build the parts a demo skips: data access with the right permissions, confirmation before an agent changes anything, checks against made-up output, and evals that tell you when a change makes things worse. How we work: 1. **Pick the use case.** Find the job where AI saves real time and where errors are visible and cheap to fix. 2. **Prototype against an eval.** Write test cases from real tasks first. The prototype has to pass them before it goes further. 3. **Integrate.** Connect to your data, auth and workflows. Add confirmation for actions that change data. Verify output in code. 4. **Ship and measure.** Track cost, latency and quality per feature. Re-run the evals on every prompt or model change. Proof: **0** hallucinations in document extraction after we moved verification into code (EU compliance platform · field accuracy 0.923 → 0.976). **Can you work with our existing stack?** Yes. We add AI features to the product you have, in your language and framework, behind your own auth. We do not ask you to move to a new platform. **Which model providers do you use?** We test models from several providers on your own cases and pick on evidence. We keep the integration provider-neutral, so you can switch later. **How do you stop the AI from making things up?** We check output in code, not only in the prompt. For extraction, every value must quote its source. For agents, any action that changes data needs confirmation first. **How long does a first integration take?** It depends on your data and systems. The scoping call gives you a realistic estimate and a first use case that can ship on its own. ### Evals & model selection https://tiansphere.com/services/ai-evals Replayable eval harnesses that tell you which model to run, and what it costs. Teams pick models from benchmarks and launch posts. Then the bill arrives, or quality drops after a prompt change, and nobody can say why. An eval suite built from your own recorded cases answers both questions. It also catches a quieter failure: an eval tuned so long on one model that it rewards that model's habits. How we work: 1. **Record real cases.** Use production traffic, or synthetic cases that mirror it. Agree what correct means before any model runs. 2. **Build a replayable harness.** Save every response, so re-running a past comparison costs nothing. Put a confidence interval on every pass rate. 3. **Lock a holdout set.** Write holdout cases before anyone sees model output, and never tune on them. 4. **Compare and decide.** Put accuracy, latency and cost per call side by side. Use paired tests to tell real differences from noise. Proof: **10×** lower AI cost per suggestion after testing 23 models on the same cases (Enclave · 23 models · 95% CI · locked holdout). **How many test cases do we need?** Enough that the confidence interval is narrower than the difference you care about. We show the interval, so you can see when the set is too small. **Can we run the evals ourselves after the engagement?** Yes. The harness lives in your repository, runs in CI, and re-running saved cases costs nothing. **What is eval overfitting?** When a prompt or scorer is tuned on the same cases you measure with, scores rise without real quality gains. Locked holdout cases and scorer rules fixed before re-scoring prevent it. ### LLM cost & latency https://tiansphere.com/services/llm-cost Lower AI bills and faster answers, with evals that show what, if anything, you gave up. AI cost grows quietly: longer prompts, bigger tool lists, the most expensive model as the default. Latency grows with it. Most of the waste is structural. Fixed text that is not cached, tool definitions nobody trimmed, one model for every job. Each fix is small, and the eval suite tells you which ones are safe. How we work: 1. **Measure.** Find cost, tokens and latency per feature and per customer. 2. **Cache and trim.** Order prompts so fixed text is cached. Give tool lists a token budget and enforce it in CI. 3. **Route.** Use a cheaper model for each job that passes its eval. Batch where latency allows. 4. **Cap.** Set spend limits per customer that reserve cost before each call and settle it after. Proof: **−79%** agent cost after reordering prompts for caching (Enclave · 92% of input tokens from cache · −20% latency). **Will cheaper models hurt quality?** Sometimes. That is why every switch goes through the eval suite and a live price check first. In one case a model that looked cheaper cost 22% more at live prices. **What is prompt caching?** Providers bill cached input tokens at a fraction of the normal price. If the fixed parts of a prompt come first and stay identical, most of each request is served from the cache. **Can you limit AI spend per customer?** Yes. We reserve the expected cost before each call and settle the real cost after, so one customer cannot run up your bill. ### MCP servers https://tiansphere.com/services/mcp Let Claude, ChatGPT and your customers' agents use your product, safely. Your customers already ask AI assistants to do their work. Without an MCP server, the assistant cannot reach your product, or it guesses. A good MCP server is more than an API wrapper. Each tool should answer a question in one call, descriptions must steer the model to the right tool, and every action must respect the user's permissions. How we work: 1. **Map the jobs.** List the questions and actions your customers bring to an assistant. 2. **Design the tools.** One call per question. Keep the tool list on a token budget. 3. **Secure it.** OAuth, a scope per permission, rate limits per token, and confirmation before any change to data. 4. **Eval and list.** Run agent evals for tool choice, then submit to the Claude and ChatGPT directories. Proof: **1 day** from research to a production MCP server (Enclave · 31 tools · OAuth · 9 scopes · 60 req/min). **What is an MCP server?** MCP (Model Context Protocol) is the open standard AI assistants use to call tools. An MCP server exposes your product's data and actions to Claude, ChatGPT and other agents. **Is it safe to let an AI change data in our product?** Only with the right controls: OAuth so the agent acts as a real user, scopes so it can do only what that user allows, and a confirmation step before any change. **Do we need an MCP server if we already have an API?** Your API is the foundation. The MCP layer adds tool descriptions, auth flows and response shapes that agents use correctly. Without it, agents waste tokens and pick the wrong calls. ## Case studies - **Enclave · Events & membership SaaS**: 10× lower AI cost, same quality. We tested 23 models on the same recorded cases and moved AI suggestions to a model that costs $0.006 instead of $0.065 per call. Method: 23 models · 95% CI · locked holdout. https://enclavehq.com - **Enclave · MCP server**: 1 day from research to a production MCP server. Organisers can run their events from Claude and ChatGPT. 31 tools, OAuth, 9 permission scopes, listed in both directories. Method: 31 tools · OAuth · 60 req/min. https://mcp.enclavehq.com - **EU compliance platform · Document AI**: 100% of test cases pass, at 17× lower cost. Up from 66.7%, with zero hallucinations. Every extracted value must quote its source, so made-up data is caught in code. Method: field accuracy 0.923 → 0.976. https://tiansphere.com/work - **StatsMCP · Public data**: 2× better search than the national statistics office. 15 national statistics databases behind one endpoint for AI agents. Our search ranks the right table twice as well as the agency's own. Method: 138 graded queries · MRR 0.27 → 0.57. https://statsmcp.dev - **Memberhaus · Community platform**: 1 codebase two brands on one AI-ready platform. The Enclave platform, white-labelled for clubs and member communities. Method: Shared platform with Enclave. https://tiansphere.com/work - **Bookseed · Past product**: 1 → book one sentence in, a finished book out. Our AI ebook generator: chapters, cover, and PDF, EPUB and Word files ready for the major stores. Generation ran server-side on a queue, and every line of AI output was sanitised before storage. Method: Past product · no longer online. https://tiansphere.com/work ## 24 Days of Production AI https://tiansphere.com/production-ai: a free track of short lessons for engineers who ship AI, from tokens and evals to RAG, agents, MCP, security and LLMOps. ## AI Engineer Roadmap 2027 https://tiansphere.com/ai-engineer-roadmap: 8 stages and 46 modules for production AI engineering, from tokens to LLMOps. ### 01 · LLM mechanics and model selection Know how a model reads tokens, generates text and fails. - 01.1 Tokenization and unit cost: Why character counts mislead, and how to estimate API spend. - 01.2 Transformers: a practical intuition: Embeddings, attention and context, without the math. - 01.3 Prefill, decode and the KV cache: Why the first token and the next tokens have different speeds. - 01.4 Sampling and non-determinism: Temperature, top-p, and why temperature 0 can still change the result. - 01.5 Reasoning models and test-time compute: When more thinking helps, and when it only adds latency and cost. - 01.6 Failure modes and the model landscape: Hallucination, sycophancy, lost context, and how to choose a model by workload. Ship: Write a model selection memo. Compare three models on one workload: quality, time to first token, speed and cost. ### 02 · LLM APIs and prompting Use the raw SDK, streaming, schemas and tools before a framework. - 02.1 Raw SDKs, conversation state and streaming: Direct provider calls, message arrays, and token streams that the user can cancel. - 02.2 Schema-enforced structured outputs: A schema that the API enforces, and validation in code. - 02.3 Tool calling and tool design: Narrow tools, clear parameters, and errors that help the model correct itself. - 02.4 System prompts and few-shot examples: Stable policy, untrusted input, and rules for when to abstain. - 02.5 Concurrency, retries, timeouts and fallbacks: Parallel calls, backoff on rate limits, and a second model when the first fails. - 02.6 Prompt versions, prefix caching and basic tracing: Version prompts like code, order them for the cache, and log each request. Ship: Ship a streaming assistant with schema-checked output, tools, retries and a cost log for each request. ### 03 · Evaluations first Without an eval, each prompt change is a guess. All later stages report to this one. - 03.1 Golden datasets from real failures: A small test set of normal cases, edge cases and real failures. - 03.2 Code assertions and LLM-as-judge: Fast code checks first. A calibrated model judge for open answers. - 03.3 Offline and online evaluation: Regression runs before release, and samples from production after it. - 03.4 Regression suites and side-by-side diffs: The same inputs, two versions, and a pinned baseline. - 03.5 Quality, latency and cost in one report: Each run reports latency, tokens, errors and cost per query. Ship: Build an eval harness for CI. It runs your golden set on two variants and prints quality, latency and cost side by side. ### 04 · Retrieval and production RAG Retrieval precision decides if a knowledge product works. Prompt wording does not. - 04.1 Document ingestion and dirty data: PDFs, tables and HTML, with deduplication and incremental updates. - 04.2 Structure-aware chunking and metadata: Split on structure, and keep the metadata for filters. - 04.3 Embeddings and vector databases: Choose an embedding model, and know the trade-offs of the index. - 04.4 Hybrid retrieval: BM25 and dense: Keyword search finds exact IDs. Vectors find meaning. Use the two together. - 04.5 Structured data and safe text-to-SQL: Read-only queries, row-level scope, and validation before execution. - 04.6 Reranking, citations and RAG evals: Rerank the top results, cite the source, and measure retrieval and answers separately. Ship: Deploy a hybrid-search RAG service on a messy real corpus, with citations and an eval that compares hybrid with dense-only. ### 05 · AI agents and tool protocols Go from fixed pipelines to loops with limits, real tools and human approval. - 05.1 Manual ReAct and planning loops: Write a tool loop with a step limit before you use a framework. - 05.2 MCP: the Model Context Protocol: Build and use servers that give a model tools, resources and prompts. - 05.3 State graphs and multi-agent patterns: Durable state and checkpoints, and when one agent is better than many. - 05.4 Sandboxes and browser agents: Run generated code in isolation. Use a browser when there is no API. - 05.5 Budgets, agent UX and human approval: Step and cost limits, loop detection, and approval before an action you cannot undo. - 05.6 Trajectory and recovery evals: Score the tool calls and the recovery from failures, not only the answer. Ship: Ship an agent on an MCP server with step and cost budgets, approval for important actions and a trajectory eval. ### 06 · Context and harness engineering The context window is a limited resource. Engineer it. Do not only append to it. - 06.1 Context window budgets: A token budget for policy, history, retrieved text and tool output. - 06.2 Compaction and rolling summaries: Compact before the window fills. Keep decisions, constraints and open tasks. - 06.3 Memory and state offloading: Keep work in files or a database, and load only what the step needs. - 06.4 Tool-context hygiene: Filter long tool results, paginate, and load tool lists only when necessary. - 06.5 Harness engineering and AGENTS.md: Durable instructions, verification hooks, and work that continues across sessions. - 06.6 Deep-research and long-horizon loops: Split the question, search wide and then deep, and know when to stop. Ship: Compare a context-managed agent with a full-history agent on multi-step tasks. Report completion rate and token cost. ### 07 · AI security and guardrails A prompt is not a security boundary. Enforce permissions in code. - 07.1 Threat models and trust boundaries: Map each untrusted input: prompts, documents, web pages and tool output. - 07.2 Direct and indirect prompt injection: Instructions hidden in documents and tool results, and how to contain them. - 07.3 Least-privilege tool authorization: Separate read tools from destructive tools. Check permissions on the server. - 07.4 Tenant isolation for RAG and memory: Apply access rules at retrieval time, so no data crosses tenants. - 07.5 PII redaction and secret hygiene: Redact before the provider call. Keep credentials out of prompts and logs. - 07.6 Adversarial red-teaming: Automated attacks for jailbreaks, injection and secret extraction before launch. Ship: Threat-model and red-team your agent. Close the gaps in application code. Prove it with an automated attack suite. ### 08 · AI system design and LLMOps Make the build fast, visible and cost-controlled, with a safe rollback. - 08.1 Model routing and LLM gateways: Route by task, latency and cost, with failover and spend caps per tenant. - 08.2 Latency and caching architecture: Streaming, parallel calls, prefix caching and safe semantic caching. - 08.3 Evals as CI/CD release gates: Run evals on each change, and block the merge when quality drops. - 08.4 End-to-end tracing and observability: Spans for retrieval, prompts, tool calls and model latency. - 08.5 Incidents, model drift and rollbacks: Detect silent model changes, and roll back a prompt or a model fast. Ship: Run the service live behind a model gateway, with eval gates in CI, full tracing, cost alerts and a tested rollback. ## Field notes ### HTML vs Markdown for AI agents: we measured the cost https://tiansphere.com/blog/html-vs-markdown-ai-agents · Published 2026-11-18 > HTML vs Markdown for AI agent plans: in 80 runs, plain HTML cost 1.9x the tokens and drew no diagrams. Asking for visuals is what makes it pay. Two talks this year made the same claim five months apart: for AI agent output, HTML beats Markdown. We use HTML output every week, so we agree with the idea. But HTML vs Markdown is also a cost question, because every tag is an output token. So we measured it: 80 plans from the same model, in both formats. The result is clear, and it is not the one the talks suggest. **A plain "write it as HTML" costs 1.9 times the tokens and adds nothing that Markdown could not show.** The benefit comes only when you ask for what Markdown cannot do. #### Two talks, one claim In June, at [Code with Claude Tokyo: Extended](https://claude.com/code-with-claude/tokyo-extended), Jason Schwartz of Anthropic gave the workshop [How we Claude Code](https://claude.com/code-with-claude/session/tyo-ext-how-we-claude-code). He named three tools for working with long-running agents, and HTML was one of them. A later slide compared the same plan in two formats. Thariq Shihipar of Anthropic wrote the long form of this argument in [The unreasonable effectiveness of HTML](https://claude.com/blog/using-claude-code-the-unreasonable-effectiveness-of-html). His reasons: HTML holds tables, diagrams and controls; long Markdown files do not get read; and a page with a "copy as prompt" button sends your decision back to the agent. In November, at [AI Engineer Shanghai](https://ai.engineer/shanghai/2026), [Bin Liu](https://ai.engineer/shanghai/2026/speakers/bin-liu), VP of Product Engineering at HeyGen, took the idea further. HeyGen described its videos in its own JSON format. Agents wrote valid JSON, but valid did not mean correct. So HeyGen dropped the JSON. Each video is now an HTML page, rendered to video in a headless browser. They published the renderer as [HyperFrames](https://github.com/heygen-com/hyperframes), under Apache 2.0. His argument: models already know HTML from the whole web. Bet on the formats that models keep getting better at. #### How we use HTML output today We searched our own Claude Code sessions. From July to November 2026, agents made **97 HTML pages for us in 76 sessions**. The number of sessions grew from 9 in July to 30 in October. Almost every page was for a decision: UI options side by side, a mockup before a ticket, a checklist for a directory listing, a gap analysis. In the Tokyo workshop we built the same bill splitter as on the slide. After the interview, the agent wrote a page with the decisions at the top and four design directions below, each with mockups of the core screens. But in the same repositories we keep **2,622 plans and specs in Markdown**. Those are the documents that agents execute, and that git tracks line by line. We never decided on this split. It happened, and the measurement below explains why it works. #### We measured HTML vs Markdown We wrote 10 planning tasks of the kind we give to agents: spend caps for an AI feature, a zero-downtime Postgres migration, an MCP server with OAuth, a choice between three check-in layouts, and six more. Each prompt asked for scope, options with a recommendation, steps, risks and open questions. Only the format line changed. `run.mjs` (benchmark script, shortened): ```js const FORMATS = { md: "Write the plan as a Markdown document.", html: "Write the plan as a single self-contained HTML file (inline CSS, no external assets).", visual: "Write the plan as a single self-contained HTML file (inline CSS and SVG, no external assets). Show the options side by side so they can be compared at a glance, draw the main flow or architecture as an inline SVG diagram, and include a simple mockup if the task has a user interface.", }; ``` We ran each task 3 times in Markdown and in plain HTML, and 2 times in visual HTML, on Claude Sonnet 5.5 with thinking off. So output tokens are the document only. *10 tasks; 30 Markdown, 30 HTML and 20 visual HTML runs. Medians. Sonnet 5.5 list price.* | | Markdown | Plain HTML | Visual HTML | | --- | --- | --- | --- | | Output tokens | 5,400 | 10,254 | **14,934** | | Tokens vs Markdown, same task | 1.0x | **1.9x** | **2.7x** | | Time to finish | 43 s | 69 s | 92 s | | Cost per plan | $0.054 | $0.103 | $0.150 | | Plans with an SVG diagram | 0 of 30 | **0 of 30** | **20 of 20** | #### "Write it as HTML" is not enough Plain HTML cost more on every one of the 30 paired runs, from 1.5 to 2.5 times the tokens. It took 1.6 times as long. And it gave us almost nothing new. The visible text was only 18% longer than the Markdown version. No plan had a diagram or a control. The model wrote the same document in a nicer font, and the extra tokens were tags and CSS. There was one more surprise. All 30 plain HTML answers came wrapped in a Markdown code fence, although the prompt said to reply with the document only. No Markdown answer had this problem. If HTML output goes into a product, strip and check it before you render it. #### Ask for what Markdown cannot show The visual prompt changed the result. Every one of the 20 plans had at least one SVG diagram, 43 in total. For the check-in task, the model drew three phone screens side by side and scored them against weighted criteria. That is the page the talks describe, and a reviewer decides from it in a minute. It costs 2.7 times the tokens of Markdown, about $0.10 more per plan. For a decision that one person reads, that is a small price. For an output that a product generates many thousands of times, it is a real line in the budget. > "The work is setting up the conditions in which the code gets written well." (Jason Schwartz, Anthropic) #### Where each format wins - **HTML for decisions that people make.** Options, mockups, diagrams and reports. Ask for the visual elements by name, or you pay for tags only. - **Markdown for work that agents execute.** Plans, CLAUDE.md files and guides. They are half the size or less, and a diff shows each change line by line. - **A format the model knows, for product output.** HeyGen's lesson applies to any AI feature: a format of your own design is easy to validate and hard to get right. If you can, render a format the model has seen billions of times. - **Measure before you scale.** HTML output in a product feature multiplies your output tokens, and output tokens are the expensive ones. > **What to copy** > > Keep plans that agents execute in Markdown. When you need a human decision, ask for HTML and name the elements: options side by side, a diagram, a mockup. As Thariq puts it, "The trick is always to end with an export": give the page a button that copies the decision back to the agent as a prompt. #### Limits of this test This is one model, with thinking off, on 10 synthetic tasks and one prompt per format. We counted tokens, time and diagrams. We did not score whether the visual plans led to better decisions; that needs real reviewers. Token ratios also differ between tokenizers, so measure your own model before you plan a budget. For the other talks we heard in Shanghai, read [three talks on controlling agents](/blog/ai-engineer-shanghai-2026). If you want to put AI output in front of your users or your team, [see how we integrate AI into products](/services/ai-integration). ### AI Engineer Shanghai 2026: three talks on controlling agents https://tiansphere.com/blog/ai-engineer-shanghai-2026 · Published 2026-11-13 > Notes from AI Engineer Shanghai 2026: MiniMax on leaner harnesses, Liquid AI on decision models, 1Password on agent intent, and what we take from each. On 5 and 6 November, we were at [AI Engineer Shanghai 2026](https://ai.engineer/shanghai/2026), at the Hilton Shanghai Hongqiao. More than 50 speakers from Chinese and international AI teams talked about models, agents and infrastructure. Three talks on the second day answered the same question from three sides: as agents get stronger, what should still be controlled by code, and what can we leave to the model? These are our notes from those talks, and what we take from each one into our own work. Every number below comes from the speakers' slides. #### MiniMax: let go of judgment, keep control of invariants [Ronny He](https://ai.engineer/shanghai/2026/speakers/ronny-he), Head of MiniMax Code R&D, asked a question that every team with an agent should ask after each model upgrade: which parts of the harness just became dead weight? His slides listed signs that harnesses are shrinking where models caught up. One example: Anthropic cut the Claude Code system prompt for newer models by more than 80%, partly by loading Skills and tools on demand. A single main agent with Skills often beats a set of subagents. His rule for what stays is short. **Let go of judgment, keep control of invariants.** Judgment is anything the model now decides better than your if-statements: which tool, what plan, what to summarise. Invariants are things the model cannot see, cannot undo or cannot be trusted to remember: the cache prefix, the clock, process lifetimes, state that must survive. `Ronny He's slide` (per feature, at every model upgrade): ```python # per feature, every model upgrade if hidden(x) or irreversible(x): harness.enforce(x) else: expose(x); model.decide(x) # then: eval before vs. after ``` Two of his case studies were very concrete: - **Tools found at call time keep the cache.** Third-party connector tools used to go into the tool list on every turn. A user who connected or disconnected an app changed that list, and the cached prompt prefix was lost. MiniMax moved discovery inside a tool call. The model takes one extra step, but the prefix stays byte-stable. - **Fewer round trips, not a smarter model.** Past 30 to 50 tool definitions, models get worse at picking the right one. MiniMax gave the model a `run_code` tool that calls the other tools from JavaScript. On 150 code tasks and 63 office-document tasks, scores stayed flat while tokens fell 13% and 35%, and requests fell from 104 to 93 and from 102 to 70. The catch: when `run_code` sat next to every native tool, the model barely used it, and tokens went up 5%. It only worked once most tools were available as code only. A third case explained why time belongs to the harness. Anthropic's default prompt cache lives 5 minutes. An agent that waits 6 minutes for `npm run dev` sends no requests, so its cached tokens probably expire. MiniMax starts every command in the background and waits in the foreground for at most 60 seconds. The model cannot see the cache clock, so the harness owns it. **What we take from it.** We cut our own MCP tool list and protect our cached prompt prefix for the same reasons, and we measured the effect with evals. His fourth question for every harness feature, "did it survive an eval?", is the part we would underline. Look at requests and tokens, not only the score. #### Liquid AI: decision models with a confidence you can use [Leonie Monigatti](https://ai.engineer/shanghai/2026/speakers/leonie-monigatti), Member of Technical Staff at Liquid AI, talked about a model type that many agent builders need but rarely name: the decision model. It takes a state and a question and returns a typed answer with a confidence, in one forward pass, with no text generation. An agent can use that confidence directly as a gate: act above 0.9, ask the user below it. A basic version needs any LLM and about 20 lines of code: label the options A, B and C, read the model's scores for those letters at the last position, and apply softmax. Her slides then showed why that is not enough. - **Option order changes the answer.** The same email, "I was charged twice for my order last week", went to technical support (0.43), fraud (0.80) or billing (0.80), depending only on the order of the options. Her team's answers were fine-tuning with shuffled options, and bidirectional instead of causal attention. - **Raw confidence is too high.** Before calibration, when the model said 90%, it was right 68% of the time. Plain temperature scaling brought that to 88%, so a more complex reinforcement-learning method was not needed. Liquid AI released two open decision models of about 2B parameters, `d1-2B` and `d1-Omni-2B`, small enough for on-device use. **What we take from it.** We use LLMs for routing and triage decisions, and the option-order test belongs in every eval of a step like that: shuffle the options and check that the answer stays the same. A confidence is only useful as a gate if it is calibrated, so measure "says 90%, right how often?" before you set a threshold. #### 1Password: should this agent be allowed to do that? [Grace Li](https://ai.engineer/shanghai/2026/speakers/grace-li), Senior Principal Applied AI Engineer at 1Password, closed the session with the question in her title. Her example: a user asks an agent to find out why checkout fails after a deploy. The agent reads the logs, as asked. Then it proposes `aws ecs update-service ... --desired-count 6`, which scales production. Useful? Maybe. Asked for? No. Permission alone does not catch this. The agent may well have the right to scale the service. The question is whether the call fits the task. In her model, the user's task is trusted and the agent's stated reason is not, because a reason can be wrong or injected through tool output. She set three requirements for a runtime intent judge: it judges the call in the context of the task, it answers fast because every tool call waits on it, and it runs locally because commands, hostnames and logs are sensitive. Then she tested small models against them. *From Grace Li's slides: 65 hand-labelled synthetic cloud-CLI calls, 3 repeats, run offline on one laptop GPU. Questions were tuned on Jev; the open models were not. Not a public benchmark.* | Judge model | Accuracy, forced to pick a label | Accuracy, "unknown" counts as a miss | | --- | --- | --- | | Jev 1.13 (hosted) | 93% | 92% | | Clef-Flash 9B | 92% | 89% | | Liquid d1 (2B) | 91% | 48% | | Laya 421M | 54% | 42% | | Qwen 2.5 7B, prompted | not applicable | 72% | The top three were close. The difference was in how often each model said "unknown". Liquid d1 deferred on 33 calls and got 31 of the other 32 right. The prompted small model reached 72% and gave no confidence to act on. Her most useful example was an error in the dangerous direction. Asked to quiet noisy GuardDuty findings, an agent proposed `aws guardduty delete-detector`, which turns off security monitoring. The correct level is admin. The smallest model labelled it a plain delete, with low confidence. The fix was to defer every call with low confidence to a human. For Clef-Flash, calls labelled safer than they were fell from 2 to 0, and it still decided 52 of 65 calls on its own. For Laya, they fell from 13 to 2, but it deferred 53 of 65 calls: safe, but not useful. Her reference architecture fits on one line from the slide: **only policy, with a current grant, can let a call run.** An approval gateway holds every call. An intent judge with no credentials returns typed answers with probabilities. A deterministic policy gate allows, denies or defers. She tracks two numbers for the whole system: risky calls let through, with a target of 0, and safe calls let through, as high as possible. **What we take from it.** This is the clearest version we have seen of a rule we follow: the model can describe and suggest, but code decides what is allowed. Her tuning order is also worth copying: fix the input, check your labels, choose thresholds, and fine-tune last. > The model describes the call. Policy decides. #### The common thread The three talks came from a model lab, an on-device model company and a security company. They agreed on one design: - **The model decides what it can see.** Tool choice, plans, summaries and labels can move to the model as it improves. - **Code owns what the model cannot see or undo.** Cache lifetimes, clocks, permissions and irreversible actions stay in the harness. - **Confidence connects the two.** A calibrated confidence lets code decide when to act, when to ask and when to stop. - **Evals decide what survives.** Every speaker showed measurements, including the results that did not go their way. > **Three questions for your own agent** > > Which harness rules exist only to correct an older model, and what breaks if you delete them? Which actions are irreversible, and is each one gated in code, not in a prompt? Where your agent uses a model's confidence, have you measured how often "90% sure" is right? We hold the same line in our own builds, from [checking extracted values in code instead of prompts](/blog/stop-llm-hallucinations-with-code) to the rules in [why every SaaS with customers should ship an MCP server](/blog/every-saas-should-ship-an-mcp-server). If you are putting an agent into your product and want it to act safely, [see how we integrate AI](/services/ai-integration). ### Your LLM eval is overfitting. Here is how we caught it https://tiansphere.com/blog/your-eval-is-overfitting · Published 2026-11-11 > One model had 879 recordings, the others 53 or fewer. A fair scorer flipped the ranking and a locked holdout made it a tie. Here are the three rules we use now. We had run many evals with many models, and an older Gemini Flash-Lite model kept winning. That should have been good news. Instead it was a warning: a cheap, older model should not beat newer models on every comparison for weeks. #### The suspicious winner The first thing we checked was how much data each model had. The answer explained a lot: - **879 recordings for Gemini.** Every other model had 53 or fewer. - **17 record runs on Gemini** while the dataset went from v1 to v8 and the MCP instructions went through about nine versions. - **Each other model ran once,** at the end, on a prompt that was tuned for Gemini. We had no true holdout. The golden cases grew while we tuned the prompt against them. Every improvement we measured was partly an improvement in fitting our own test. #### What the scorer actually rewarded Next, we re-scored the saved answers. The scorer checked only the **first tool call**. That rewarded one habit: acting at once. All six of Haiku's "failures" were cases where it read the record first or asked a clarifying question. In one case, Gemini passed by guessing a required field and inventing a description. The other models correctly asked the user. *Discordant pairs 3 vs 2 on all 89 cases: a statistical tie.* | Scoring | Gemini 3.1 Flash-Lite | Claude Haiku 5.5 | | --- | --- | --- | | Old scorer | **92.5%** | 88.7% | | Fair scorer, same cases | 94.3% | **98.1%** | | 36 unseen holdout cases | 91.7% | 88.9% | | All 89 cases, paired | 93.3% | 94.4% | With the fair scorer, the order flips. Most of the gap came from the scorer, not from the models. #### Three rules we use now **1. Fix the scoring rules before you re-score.** We wrote two general rules and applied them to every model: "look up first" and "ask when a required input is missing". A lookup only counts if it reads the exact record that the case is about. A question only counts on cases where an input is really missing. Refusal cases stay strict. `scorers.ts` (the frozen rule set, from the eval suite): ```ts function isLookupFirst(expected: CallExpected, output: McpToolsOutput): boolean { const ids = output.toolName ? LOOKUP_IDS[output.toolName] : undefined; if (!ids || output.toolName === expected.tool || !output.args) return false; const args = output.args; return ids.every( (key) => key in expected.args && deepEqual(expected.args[key], args[key]) ); } function isClarifyingQuestion(expected: CallExpected, output: McpToolsOutput): boolean { return ( expected.clarifyOk === true && output.toolName === null && (output.text ?? '').includes('?') ); } function acceptedAlternative(expected: CallExpected, output: McpToolsOutput): string | null { if (isLookupFirst(expected, output)) return 'lookup-first'; if (isClarifyingQuestion(expected, output)) return 'clarified'; return null; } ``` **2. Write holdout cases before you see any output.** We wrote 36 new cases. A separate reviewer checked them for hints that leak the answer. Then we froze them in a commit. > I did not change that rule after seeing the answers, because doing so would be overfitting again. **3. Compare in pairs, and report each set separately.** Golden, tuning and holdout results each get their own row. A single blended number hides exactly the problem we had. > **Before you trust an eval** > > Count recordings per model. Check what the scorer rewards. Keep a holdout set that nobody tuned on. If one cheap model wins everything, suspect the eval first. #### What we shipped We did not crown a winner. We split the roles. Gemini keeps the classification and generation jobs. Claude Haiku 5.5 runs the assistant agent that can change data, because there "ask before you guess" matters most. The whole fairness study cost about **$1.35** in model calls. Shipping the wrong model would have cost much more. For the full model comparison that came before this study, read [We compared 23 LLMs on our own evals](/blog/23-models-the-cheap-one-won). If you want an eval that you can trust before you choose a model, [see how we run evals](/services/ai-evals). ### We compared 23 LLMs on our own evals. The cheap one won. https://tiansphere.com/blog/23-models-the-cheap-one-won · Published 2026-11-04 > Recorded cases, confidence intervals and $0 replays showed which model to run. AI suggestions went from $0.065 to $0.006 each, with no measurable quality loss. Every AI feature in an events and membership SaaS started on a "safe" default: a large, well-known model. The features worked. The bill was the problem. So we stopped picking models from launch posts and built an eval suite that could answer one question for each feature: what is the cheapest model that still passes? #### The setup Each AI feature got its own suite of synthetic cases: a fact-checker for draft emails, the email writer itself, a plain-English segment builder, a moderation triage step and the MCP tool router. The suites call the real production prompt builders and schemas, never copies. If the evals pass, the code that ships passes. Three design choices made the comparison cheap and honest: - **Record and replay.** Every model call is keyed by a hash of the model, the request and the trial number. About 8,000 saved responses mean that anyone can re-run a past comparison for $0. Re-certifying all five suites, three trials each, cost **$0.97**. - **Confidence intervals on every pass rate.** At 34 cases, even 34 out of 34 passing gives an interval of 89.8–100%. A gate at 95% can only say "inconclusive" there, and the harness says so instead of showing a green tick. - **A judge from a different model family.** The runner refuses a judge from the same family as the model under test. #### The result On the fact-checker suite, 97 cases with three trials each, the cheap model matched the previous default verdict for verdict: *Fact-checker suite, 97 cases × 3 trials. Wilson 95% intervals in brackets.* | Model | Pass rate | Cost per run | | --- | --- | --- | | Gemini 3.1 Flash-Lite (chosen) | **98.6%** [96.5–99.5] | **$0.045** | | Claude Haiku 4.5 (previous) | 98.6% [96.5–99.5] | $0.21 | | GPT-5.6 Luna | 96.9% | $0.05 | | GPT-5.6 Luna Pro | 95.2%, failed the precision gate | $0.34 | | GPT-5.4 Nano | 88.3% | $0.04 | Across the features, the cost of one AI suggestion fell from about **$0.065 to $0.006**, with no measurable quality loss. Moderation triage fell from about $0.02 to $0.0003 per report. The previous "quality" default there also made three wrong dismissals and failed the safety gate, at 25 times the cost. #### The prompt was the problem, not the model The email writer was the surprise. On the old prompt, every model scored between 17% and 44%, including Claude Sonnet 4.6 at $2.15 per run. When every model fails the same cases, the gap is in the prompt, not in the model. So we kept the cheap model and rewrote the prompt against the eval. The pass rate went from 35–41% to 85–100% on the same model. One rewrite made things worse (73.5% down to 41.2%), and the eval caught that regression the same day. > **One trial lies** > > Gemini's own two runs on an identical setup once differed by 15 points. That was wider than the gap between models. Run several trials, and only trust differences that sit outside the noise. #### The price-table bug Months later, an automated prompt search proposed a newer model as "cheaper": $0.035 against $0.056 per run. That looked like an easy win. It was not. The eval's price table held **batch** prices. At live prices, the "cheaper" model cost **22% more**. We reverted the model, kept the shorter prompt the search had found (9% cheaper at the same accuracy), and fixed the price table. Now we compare the table with live provider prices before we trust any eval cost. #### What to copy - Build suites from your own cases. A public benchmark ranked one model above our winner, and it then lost on five of our six suites. - Compare cost per call, not price per token. Some cheaper-per-token models write three to five times more output. - Make re-runs free. If a comparison costs money every time, nobody runs it again after the next model launch. An eval can also lie in a quieter way. In a later study, the same harness ranked a model first only because the scorer was tuned to it: [your LLM eval is overfitting](/blog/your-eval-is-overfitting). If your AI bill grows faster than your usage, [see how we cut LLM cost](/services/llm-cost). ### Why every SaaS with customers should ship an MCP server https://tiansphere.com/blog/every-saas-should-ship-an-mcp-server · Published 2026-10-28 > Your customers already ask AI assistants to do their work. An MCP server lets those assistants use your product, under the user's own permissions. Your customers already ask AI assistants to do their work. They ask Claude to summarise last month's sales, or ChatGPT to set up next week's event. Today, most SaaS products are invisible to those assistants. The assistant cannot reach the product, so it guesses, or the customer copies data across by hand. An MCP server fixes that. MCP, the Model Context Protocol, is the open standard that assistants use to call tools. If your product has an MCP server, any assistant that supports MCP can read and change data in your product, as the signed-in user, with that user's permissions. We think this becomes as normal as having a public API. The difference is who the user is. An API is for developers. An MCP server is for your customers, through the assistant they already use. #### What a good MCP server looks like A wrapper around your REST API is not enough. Agents use tools differently from developers. These are the rules we follow, from building a production server for an events and membership platform: - **One call answers the question.** "What needs my attention this week?" used to need 10 to 20 calls. One `org_overview` tool now answers it. Agents that page through lists to count things are slow, expensive and read data the question did not need. - **The tool list is a token budget.** Every tool description goes into the model's context on every turn. We cut our tool list from 53.4 KB to 39.1 KB (−27%), and a test now fails if it grows past the limit. On a public-statistics server, a similar cut saved 13% with no loss in quality. - **OAuth, not API keys.** The assistant acts as a real user. Scopes limit what it can reach. The user's role decides what each tool returns: if your role cannot see member emails, the assistant cannot either. - **Confirmation lives on the server.** Before any change to data, the server asks the user to confirm. We did not want to rely on a `confirm: true` input, because the model would simply set it. Our evals later showed exactly that, so now the server asks the user directly whenever the client supports it. - **Rate limits per token.** 60 calls per minute per token keeps one runaway agent from hurting everyone else. #### It is less work than you think The protocol is young, but the hard parts are familiar: OAuth, permissions and good API design. For the events platform, the research was done on one day and the first OAuth and server commits landed the next. The server now covers events, members, orders, check-in and campaigns behind 9 permission scopes, and it is listed in the Claude and ChatGPT directories. The server is stateless. Each request gets a fresh server instance, so it scales like any other HTTP endpoint. One tool registry serves both the MCP server and the in-app assistant, so permission checks, metrics and error handling are written once. #### Measure tool choice An MCP server is only as good as the model's choice of tools. Treat that choice as something you test. On a public-statistics server, models kept skipping the search tool and using table ids from memory, and some of those ids were out of date. One sentence in the server instructions, "Always call `search_tables` first", moved the correct first tool call from 93% to 100% over 40 recorded agent runs. Without the eval, we would not have known the problem existed, or that one sentence fixed it. Evals can mislead too, so [check that your eval is not overfitting](/blog/your-eval-is-overfitting). #### Where to start 1. **List the jobs.** Write down the ten questions and actions your customers would bring to an assistant. 2. **Design tools for those jobs,** not for your database tables. Then set a token budget for the tool list. 3. **Ship the boring parts first:** OAuth, scopes, rate limits and confirmation. Then add an eval for tool choice before you add more tools. If you want help designing or reviewing an MCP server for your product, [see how we build them](/services/mcp). ### Stop LLM hallucinations with code, not prompts https://tiansphere.com/blog/stop-llm-hallucinations-with-code · Published 2026-10-21 > An AI feature that fills regulated product data cannot invent values. More prompt rules did not stop it. A code check on verbatim source quotes did. We built an AI feature for an EU platform that manages regulated product data. A user uploads supplier documents: PDFs, spreadsheets, certificates. The model reads them and fills a product checklist. A person reviews the result, and then it is published. In this kind of data, an invented value is worse than an empty field. An empty field gets attention. An invented value looks correct, passes review and goes live. So "no hallucinations" was a hard requirement, not a nice-to-have. #### Values that look right The eval found three kinds of fabrication: - **Placeholders.** The model wrote values such as `` into fields that needed real data. - **Computed values.** A document stated two weights, 390 g and 412 g. The model calculated 94.66% and reported it as a stated fact. No document said that. - **Guesses from context.** The model took a product name from the filename, not from the document. A fourth problem was worse. One document described a different product. Its values spread into the checklist, and about half of that checklist was wrong. #### More prompt rules did not hold The first fix was the usual one: add rules to the prompt. "Do not calculate values." "Do not use the filename." The anti-fabrication text grew to about 80 words. Each rule fixed the case that we had just seen. None of them stopped the next one. A prompt that grows with every bug also costs tokens on every call and spreads the model's attention across more instructions. We call this the ever-growing system prompt, and we now treat it as a warning sign. > The prompt says what you want. Code decides what you accept. #### Every value must quote its source We moved the rule from the prompt into code. The model must return every value with evidence: the shortest quote, of 120 characters or fewer, copied word for word from the document. Code then checks two things. First, every part of the quote must exist in the document text. Second, the value must appear in the quote or in the same part of the document. Fields with units are different: they hold a converted number, so they must be a plain number. `extractor.ts` (the production grounding check): ```ts // Evidence must be quotable from the source (ellipsis-joined fragments allowed). // Empty evidence fails closed. function isEvidenceGrounded(evidence: string, normalisedSource: string): boolean { const fragments = evidence .split(/\s*(?:\.\.\.|…)\s*/) .map(normaliseForGrounding) .filter((f) => f.length >= MIN_EVIDENCE_FRAGMENT_LEN); if (fragments.length === 0) return false; return fragments.every((f) => normalisedSource.includes(f)); } function isValueGrounded( value: string, evidence: string, normalisedSource: string, isUnitField: boolean, ): boolean { if (isUnitField) return PLAIN_NUMBER.test(value.trim()); const v = normaliseForGrounding(value); if (v.length === 0) return false; return normaliseForGrounding(evidence).includes(v) || normalisedSource.includes(v); } ``` The comparison ignores case and extra spaces, and quote fragments shorter than 4 characters do not count. A quote such as "no" or "12" proves nothing. If a check fails, the value is dropped. This blocked all three kinds of fabrication: a placeholder, a calculated percentage or a filename guess cannot be quoted from the document. Then we cut the anti-fabrication prompt text from about 80 words to one clause. The code does the work now. The same idea handles the cases that a quote check cannot cover: - **Confidence caps for review.** A summary of a long text cannot be quoted word for word. It is kept only if its quotes check out, and its confidence is capped at 69%, so a person always reviews it. A value found directly after its own field label, as in "Material: cotton", is raised to 90%. - **Product matching.** Each part of a document reports which product it describes. Values from a document about a different product are capped at 39% and flagged for review. - **Structured output.** The model must answer through a tool call with a fixed schema, so free text never reaches the checklist. #### Make fabrication a hard gate in the eval In the first eval, one invented field cost a case only 1 point out of many fields. A model could invent a value and still get a high score. We changed the rule: **one fabricated field fails the whole case.** The score now matches the real cost of the error. The eval also found errors in our own expected answers. One expected product name came from a filename, which is the same mistake that we had blamed on the model. We marked that field as "missing". Field accuracy on that case went from 79% to 95%. #### The result With the grounding check in place, a smaller and cheaper model became good enough. *Synthetic documents, 4 cases × 3 trials. 12 of 12 passes gives a Wilson 95% interval of 76–100%. Costs use list prices.* | | Before | After | | --- | --- | --- | | Model and pipeline | Claude Sonnet 4.6, prompt rules | **Claude Haiku 5.5, grounding check** | | Cases passed | 66.7% | **100%** | | Field accuracy | 0.923 | **0.976** | | Fabricated fields | 1 | **0** | | Failed files | 3 | **0** | | Cost per eval run | $0.64 | **$0.037** | The change in the pipeline did most of the work. On the same Haiku model, the pass rate went from 58% to 75%, then to 92% and then to 100% as the pipeline improved. The model only became the cheap choice after the system around it was correct. Then it cost about 17 times less per run. > **What to copy** > > Ask the model for a word-for-word source quote with every value. Check the quote in code, and reject the value if the check fails. Cap confidence where a person must review. In your eval, let one invented value fail the whole case. #### Integration is mostly the code around the model The model call was a small part of this feature. Most of the work was in the code around it: grounding checks, confidence rules, product matching and an eval that scores errors by their real cost. That code is what lets a regulated business trust the output. To check whether your own eval tells the truth, read [your LLM eval is overfitting](/blog/your-eval-is-overfitting). If you want to put AI into a product where errors cost money, [see how we integrate AI](/services/ai-integration).