CONTENTS
The AI Engineer’s Toolkit
Time to build. This chapter covers the practical stack: language choices, model APIs, structured outputs, tool calling, streaming, and the economics of tokens. Code samples are deliberately close to provider-neutral. Every major provider’s API has the same core shapes, but parameter names and model IDs change, so always check current docs for the exact syntax.
4.1 Python vs. TypeScript: use both
TypeScript is a first-class citizen for applied AI: official SDKs from every major provider, the Vercel AI SDK, Mastra, LangChain.js, MCP SDKs, and a natural fit for full-stack products. You can ship serious AI features without leaving TS.
Python is where you need to be for evals and data analysis (pandas, Jupyter), fine-tuning and training (PyTorch, Hugging Face), running open models locally, research code, and most notebooks and tutorials.
Recommendation: Build product features in TypeScript, where you’re fast. Do evals, data work, and model experimentation in Python. Learn Python now; it’s an easy language for a TS developer.
Python for TypeScript developers: the cheat sheet
| TypeScript | Python |
|---|---|
npm / pnpm |
uv (fast, modern; use it), pip |
package.json |
pyproject.toml |
node_modules |
virtual env (.venv) |
interface User { name: string } |
class User(BaseModel): name: str (Pydantic) |
zod |
pydantic |
async/await + Promise.all |
async/await + asyncio.gather |
arr.map(x => x * 2) |
[x * 2 for x in arr] |
obj?.a ?? 'default' |
obj.get('a', 'default') (dicts) |
tsc --noEmit |
mypy / pyright |
eslint + prettier |
ruff |
| Jest / Vitest | pytest |
| Storybook / playground | Jupyter notebook |
uv init my-ai-project && cd my-ai-project
uv add anthropic openai pydantic pandas jupyter
uv run jupyter lab
Pydantic deserves special mention. It is to Python AI what Zod is to TS AI: you define a schema once and use it to validate model outputs, generate JSON Schemas for tool definitions, and type your code.
4.2 The anatomy of a model API call
Every chat-model API reduces to this shape:
response = client.messages.create(
model="<model-id>", # which model
system="You are a precise assistant for a fitness app.", # instructions
messages=[ # the conversation
{"role": "user", "content": "Summarize my week: ..."},
],
max_tokens=1024, # output cap
temperature=0.2, # sampling
tools=[...], # optional: functions the model may call
)
Key concepts:
- Statelessness. The API remembers nothing. Every call sends the entire conversation. “Memory” is something you build by deciding what to put in
messages. - Roles.
system(instructions),user(input),assistant(model output, including previous turns you send back), plus tool-result content. - Stop reasons. Check why generation ended: natural end, hit
max_tokens(truncated!), or the model wants to call a tool. Not checking this is a classic bug. - Usage. Every response reports input and output tokens. Log them; they’re your cost.
4.3 Structured outputs: making LLMs talk to code
Free text is for humans. Your code needs structured data. Approaches, from weakest to strongest:
- Ask nicely (“Respond in JSON”). Works most of the time, which in production means it fails regularly.
- Prefill or format examples. Better, but still unenforced.
- Tool calling / function calling. Define a schema; the model emits arguments matching it. Reliable.
- Native structured outputs / constrained decoding. The provider constrains token sampling so the output must conform to your JSON Schema. Only tokens that keep the output schema-valid are allowed at each step. This is the strongest guarantee where available.
Always validate on your side anyway:
import { z } from "zod";
const WorkoutSummary = z.object({
totalSessions: z.number().int(),
highlights: z.array(z.string()).max(3),
sentiment: z.enum(["great", "ok", "rough"]),
suggestion: z.string(),
});
// After getting model output:
const parsed = WorkoutSummary.safeParse(JSON.parse(raw));
if (!parsed.success) {
// retry with the validation error fed back, or fall back
}
Design tip: Schema design affects output quality. Put a reasoning field before the answer field when the task requires thought; the model generates in order, so it “thinks” before committing. Use enums instead of free strings wherever possible. Keep schemas flat and well-described; field descriptions are prompts.
4.4 Tool use: giving models hands
Tool use (function calling) is the foundation of agents. The flow:
1. You send: messages + tool definitions (name, description, JSON schema)
2. Model responds: "I want to call get_weather({city: 'Lisbon'})" [stop_reason = tool_use]
3. YOUR CODE executes get_weather("Lisbon") → {"temp": 21, ...}
4. You send: previous messages + the tool call + the tool result
5. Model responds: "It's 21°C in Lisbon..." (or calls another tool)
Crucially, the model never executes anything. It emits a structured request; your code decides whether and how to run it. This is your security boundary.
tools = [{
"name": "search_orders",
"description": (
"Search a customer's orders. Use when the user asks about order status, "
"delivery, or purchase history. Returns at most 10 orders, newest first."
),
"input_schema": {
"type": "object",
"properties": {
"customer_id": {"type": "string"},
"status": {"type": "string", "enum": ["pending", "shipped", "delivered", "cancelled"]},
},
"required": ["customer_id"],
},
}]
The tool description is a prompt. The model decides when and how to use a tool based almost entirely on its name, description, and schema. Chapter 7 goes deep on tool design.
4.5 Streaming: your home turf
LLMs generate slowly: tens to a couple hundred tokens per second. A 500-token response can take several seconds. Streaming sends tokens as they’re generated, typically over Server-Sent Events (SSE).
What arrives is a sequence of events: message start, content-block start, text deltas, tool-input JSON deltas, content-block stop, message stop, plus usage. Your job:
- Render text deltas incrementally (and handle markdown that’s partially complete, like an unclosed code fence).
- Accumulate partial JSON for tool calls and parse only when complete (or use a partial-JSON parser for progressive UI).
- Show tool activity (“Searching your orders…”) as it happens.
- Handle mid-stream errors and cancellation (an
AbortControlleron the client, and propagating cancellation to the server so you stop paying for tokens nobody will see).
On React Native specifically: fetch streaming support has historically been inconsistent across RN versions and platforms, so many teams use a streaming-capable fetch polyfill or a native SSE module, or proxy through their backend over WebSockets. Never ship provider API keys in a mobile app. Always proxy through your backend, which also gives you a place for auth, rate limiting, logging, and model routing.
This is a genuine area of expertise. Great streaming UX (smooth token rendering without layout thrash, interruptibility, optimistic states, showing an agent’s progress) is a skill many backend-oriented AI engineers lack.
4.6 The economics: tokens, latency, and model choice
Every LLM decision is a trade-off among quality, latency, and cost.
Cost model: price per million input tokens + price per million output tokens. Output typically costs several times more than input. Cached input is much cheaper. Batch APIs (asynchronous, results within hours) typically offer large discounts for non-urgent work.
Back-of-envelope habit: Before building, estimate.
Feature: summarize each user's daily journal entries
Users: 50,000 DAU
Input per call: ~3,000 tokens (entries + instructions)
Output per call: ~300 tokens
Daily: 150M input tokens, 15M output tokens
→ Multiply by your chosen model's per-million prices.
→ Then ask: does a smaller model suffice? Can I batch overnight? Can I cache the instructions?
The price difference between a frontier model and a small, fast model is often 10–50×. Model choice is an architectural decision.
Model tiers (stable pattern, changing names):
- Frontier / largest models: best reasoning, coding, agentic reliability. Slowest and priciest. Use for complex, high-value tasks, and as the “teacher” or judge.
- Mid-tier: the workhorse. Often 80–95% of frontier quality on many tasks at a fraction of the cost.
- Small / fast models: classification, extraction, routing, simple summarization, high-volume or latency-critical paths.
- Open-weights models: self-hostable (Llama, Qwen, Mistral, Gemma, DeepSeek families, and others). Data stays in your infrastructure, you can fine-tune, and there’s no per-token vendor fee, but you pay in ops complexity and GPU cost.
- On-device models: small models running on phones and laptops. Private, offline, zero marginal cost, limited capability (Chapter 10).
Routing: Production systems often use several models, e.g., a small model classifies intent and routes to a large model only for hard cases.
4.7 Frameworks: when to use them
There’s a large ecosystem of frameworks (LangChain/LangGraph, LlamaIndex, the Vercel AI SDK, Mastra, the OpenAI Agents SDK, the Claude Agent SDK, Pydantic AI, DSPy, CrewAI, and more).
My recommendation is opinionated but widely shared among experienced practitioners:
- Learn with the raw provider SDKs first. Build a tool-calling loop by hand. It’s about 50 lines. You need to understand exactly what goes into the context window, and heavy abstractions hide that.
- Adopt thin frameworks for genuine leverage: the Vercel AI SDK for streaming UI in React (with excellent provider abstraction), and an agent SDK when you need its built-in harness (tool execution, context management, sandboxing, sub-agents).
- Be wary of deep abstraction stacks. When something breaks, you need to see the exact prompt and the exact tool payloads. If a framework makes that hard, it’s costing you.
The test: Can I easily print exactly what tokens the model received on every call? If not, reconsider.
4.8 Your local lab setup
Editor: VS Code / Cursor / your choice + a coding agent (Claude Code, etc.)
Python: uv, ruff, pytest, Jupyter
Notebooks: Jupyter for exploration and error analysis
Local models: Ollama or LM Studio (run open models on your laptop);
MLX on Apple Silicon; llama.cpp for the deep end
Observability: Langfuse, Braintrust, LangSmith, Arize Phoenix, or plain logs to a DB
Vector DB: pgvector (Postgres) to start — you probably already know Postgres
Keys: API keys in .env, never committed; separate dev/prod keys with spend limits
Use AI coding agents heavily while learning. Ask them to explain code, generate test data, scaffold experiments. But type the core loops yourself the first time. Understanding comes from building.
Key takeaways
- Use TypeScript for product, Python for evals, data, and models. Learn Python with
uvand Pydantic. - APIs are stateless; you own the context.
- Use structured outputs and tool calling for anything code consumes, and validate everything.
- Models request tool calls; your code executes them. That’s your security boundary.
- Streaming UX is a real differentiator, and it’s your specialty.
- Every design decision trades quality, latency, and cost. Estimate before you build.
- Start with raw SDKs, then add thin frameworks for real leverage.
Exercises
- Build a CLI in Python that sends a conversation to a model API, prints the streamed response, and logs token usage and cost per call.
- Write a structured extraction: give the model a messy App Store review and extract
{rating_sentiment, bugs_mentioned[], feature_requests[], device_info}with Pydantic validation. Run it on 30 real reviews. - Implement a two-tool loop by hand (e.g.,
get_weatherandget_calendar) without any framework. Print the full message array after each turn so you can see exactly how tool calls and results are threaded. - Build a minimal React (or React Native) chat UI that streams from your backend proxy, supports cancel, and renders partial markdown cleanly.