1/101
Looks like no tags are added yet.
Four layers of the AI ecosystem
Models, Access, Tooling, Products. The categories overlap: one platform can provide models, tools and a user-facing app
Closed weights
API only; top of the leaderboards; the lab sets a per-token price; versions retire on the lab's schedule; you control only the knobs the API exposes
Open weights
Downloadable; you can fine-tune, quantise, inspect and pin a version forever; a few places behind on quality, but the gap is small on many tasks
Open vs closed: licence vs server
The licence sets what you may do; the server sets who sees your data
Are hosted open weights private?
Not by default. A provider or router is still a data recipient; private only when self-hosted (OpenRouter can exclude providers that store prompts with data_collection: deny)
Closed weights: privacy
Data goes to the lab, or stays inside your cloud account on an enterprise route (Azure, Bedrock) with a no-retention agreement
Cost structure: closed vs open
Closed: per token, lab sets the price. Open: per token from a provider, or your own GPUs (a fixed cost that needs utilisation)
Operations: closed vs open
Closed: keys, rate limits, a bill. Open: serving, GPUs, updates, security, or a provider paid to do it
How to choose a model
Leaderboards (Artificial Analysis Intelligence Index, LMArena votes) shortlist; a measurement on your own task decides
What to compare when choosing a model
Quality on your task, cost per task, speed, context length needed, reasoning or not (and at what effort), tier and provider
Price per token vs cost per task
Cost per task is what matters; long prompts, reasoning tokens and retries change the bill
Speed metrics
Time to first token and tokens per second
Same model, several prices
Closed model: tiers (flex = slower queue and cheapest, standard, fast = priority and most expensive). Open model: providers differ in precision (fp4, fp8, bf16), price and features for the same weights
Three ways to reach a model
Chat app (subscription per seat, few settings), API (pay per token; you control system prompt, history, parameters, version, schema, tools), self-host (pay for GPUs busy or idle; you control everything including weights, quantisation, hardware)
Self-host: good for / tools
Privacy, volume, custom models, research. Tools: vLLM, SGLang, LM Studio, Ollama
Through the API, your code owns…
The prompt, the history and the bill
Who can sit between you and the weights
Lab API (bills you, sets data policy, exposes every feature); cloud platform such as Azure, Bedrock, Vertex (same models inside your cloud account and contracts); hosted provider such as Together, DeepInfra (hosts open weights, sets precision, price, features); router such as OpenRouter (one key, many providers, picks the endpoint)
Self-hosted server vs local machine
Self-hosted server (vLLM / SGLang): your team runs the model on rented or owned hardware. Local machine (LM Studio / Ollama): an open-weight model on your own computer
Can the model's creator differ from who runs it?
Yes. Roles can also overlap (one company may host and route). OpenAI-compatible APIs use a similar request format, but supported features vary
Tooling jobs and examples
Load/run/fine-tune models: Hugging Face Transformers. Prepare/retrieve data: LlamaIndex / LlamaParse. Coordinate workflows and agents: LangChain / LangGraph, agent SDKs. Connect to external systems: APIs / MCP. Trace and evaluate: LangSmith / W&B Weave
MCP (Model Context Protocol)
Standardizes how AI applications connect to tools and data
Where to start with tooling
A model API and its client library (SDK); add other tooling only when the application needs it
Product categories
General work (ChatGPT, Claude, Gemini); software development (Cursor, GitHub Copilot, Claude Code, Codex); workflow automation (n8n: repeatable processes connecting apps, data and AI, with optional human review)
OpenAI Chat vs Work vs Codex
Chat: collaborate through conversation. Work: delegate a task through to completion (sustained execution across steps and tools). Codex: developer tools and technical detail
Two kinds of gap
Information gaps and behavior gaps need two kinds of fix
Information gap
Facts that change or must be checkable (policy, price list, customer record, events after the training cutoff, anything traceable to a source). Fix: put it in the context (retrieval, tools, the prompt)
Behavior gap
A required format or schema, tone, length, style, or a narrow task done consistently. Fix: prompt first; fine-tune when prompting plateaus
Why not fine-tune facts into the weights?
They go stale with the weights and are hard to audit
Facts vs behaviour (summary)
Facts go in the context; behaviour is taught, by prompt or by weights
The usual order of adaptation
1) Clear prompt, 2) examples and structure (few-shot, schema), 3) retrieval and tools, 4) fine-tune
When to fine-tune
When steps 1-3 plateau, or when cost, latency or privacy need a small model
Principle behind the order
Start with what is quickest to change, measure before moving on, go only as far as the measurement requires
Development set vs test set
Compare revisions on a development set; reserve an untouched test set for final evaluation
How production systems combine approaches
A large model is prompted for the hard cases; a small fine-tuned model handles the volume
Prompting vs fine-tuning: setup, data, updating
Prompting: minutes, no or few examples, edit the prompt and redeploy in seconds. Fine-tuning: hours to days, thousands of labelled examples, retrain (old behaviour can regress)
Prompting vs fine-tuning: cost, control, risk
Prompting: paid per request forever, data leaves, risk is the provider changing the model or price. Fine-tuning: train once then serve a small model, weights and data stay with you, risk is overfitting to dataset quirks and keeping labelling errors
One-line summary: prompting vs fine-tuning
Prompting buys speed of change; fine-tuning buys a small model you control
Can a closed lab withdraw fine-tuning?
Yes. OpenAI closed self-serve fine-tuning to new organizations (May 7, 2026); existing fine-tuned models keep running until their base model retires. Open-weight fine-tuning is unaffected
StackExchange tagging: baseline vs enhanced prompt
Baseline: label list only. Enhanced: adds a system message with the convention (one tag per post, rules for confusable pairs like jquery vs javascript, ten labelled examples)
Why the baseline prompt can fail
It assumes the model knows the labelling convention (the tag word appears in only 660 of 1,000 test posts; the QR code post is tagged android though the text never says so)
Effect of the enhanced prompt
Raised Qwen 2.4T from 0.842 to 0.955 F1; for the other three models F1 fell slightly. Rules and examples changed together, so their effects are not isolated
Ten posts wrong under every model and prompt
On inspection they are mislabelled; the prompt carries the convention and your mistakes
Fine-tuned small model vs prompted large model
Fine-tuned Qwen3-1.7B scored 94.9 macro-F1 vs 97.1 (GPT-6.1 Sol) and 95.7 (GPT-6 Luna) with baseline prompts; not a definitive ranking because the test sets differ. Also compare cost, latency and deployment needs
Possible issue with public Stack Overflow data
Every model may have seen the posts in pretraining, to an unknown extent
Token
A piece of text from a fixed vocabulary of about 100,000 to 200,000 entries; about four characters of English; code, numbers and other languages cost more
Tokenizers and counts
Each model family has its own tokenizer, so counts differ; the chat template adds tokens you never typed. Prices, context windows and output limits are all counted in tokens
Context window
What the model can see in one request: instructions, conversation so far, retrieved documents, tool results
In the weights vs in the request
Weights: what was learned in training; fixed; the model cannot look anything up by itself. Request: everything the model knows about your case
Stateless by default
Chat Completions keeps nothing between calls; your code re-sends the history. The model remembers nothing between calls; your code does
Why input tokens grow every turn
The history is re-sent each time; replies are billed as output and the re-sent history as input
Server-side conversation state
OpenAI's Responses API offers it; OpenRouter's /responses endpoint is stateless
Sampling fields: temperature and top_p
temperature 0: always the top token. temperature 1: sample in proportion to the distribution. top_p 0.9: sample from the top few tokens
Does seed or temperature 0 guarantee identical output?
No. A fixed seed helps reproducibility on supporting endpoints, but batching and hardware differ between calls
Sampling settings are…
Endpoint features, not universal knobs (e.g., GPT-6 does not expose temperature, top_p or logprobs, but accepts reasoning effort)
Reasoning tokens
Output tokens you pay for; some providers do not report them
Probability of a whole answer
Multiply the per-token probabilities; longer answers have smaller probabilities however good each token looks
Number of possible 5-token sequences with V tokens
V to the 5th power (about 7.6 x 10^25 for V = 150,000); almost all are nonsense, which is why you constrain the form with a schema and test the content
Base vs instruct model
A base model continues text; an instruct model answers
Prompting loop
Design (say what you want and what a good answer contains), test (against criteria written first), refine (change the prompt, test again on the same inputs)
Clear prompt vs correct answer
A clear prompt is checkable; it is still not a correct answer. Write the success criteria before the prompt
Five components of a prompt
Task; background context (who uses the answer and for what); input data (delimited); reasoning guidance and constraints (rules, steps, limits); output format and requirements
Are the five components a required template?
No. It is a checklist of what the model may need; each answers a question the model would otherwise guess at
Metadata prompting
State the task using names and define each name in its own delimited block, so you can swap data and keep rules, or change format and keep the task
Name with no block, or block no task uses
A missing requirement, or a dead requirement. Backticks and tags are a convention for people, not variables
Few-shot and chain-of-thought for reasoning models
Reasoning models have an effort setting (billed as output tokens) instead of "think step by step"; visible reasoning is not guaranteed to be the real computation, so check the answer, not the story; explicit rules still help
Stepwise prompt vs prompt chaining
Stepwise: all stages in one prompt (fewer calls, but an early slip flows through unseen). Chaining: one prompt per stage, inspect and correct between stages (more calls)
When to chain
When an early mistake would spoil the rest, and for long inputs processed in parts
Good practice: task, purpose, behaviour
Say who will use the answer and for what; say what to do, not only what to avoid; a role helps when you say what that person cares about
Good practice: separate instructions and data
Label or delimit every part. A review saying "ignore the other reviews" is data, not an instruction; delimiters help but do not stop prompt injection
Good practice: output requirements and examples
Checkable requirements ("two bullets, each under 20 words") beat vague ones ("keep it short"); examples must obey the same rules as the task, including hard cases
Refining a prompt with the model
1) Ask how it reads the prompt (what is ambiguous or missing), 2) decide what to keep, 3) rewrite with constraints, 4) test on the same inputs
Prompt has grown too long
Ask the model to reorganise, not to add new rules; then diff the two versions
Is the model the judge of your prompt?
No. It is a good reader of your prompt, not the judge of it
Success criteria
Decide how you will recognise a useful answer before you write the prompt; cover content and presentation; each criterion names the evidence that settles it ("a good summary" is not a criterion)
Neat formatting vs content
A neatly formatted table meets the presentation criterion and none of the content ones; write content checks first
Prompt as code: testing
Give it test cases: the same inputs for every prompt version, same model, a fresh chat per version, one change at a time
Order of checks
Code checks first (exact match, schema validation, counts, regexes: cheap, deterministic, run on every change), then a judge for what code cannot read, then a person checks the judge
LLM-as-a-judge
A model scores a response against explicit criteria, evidence first. Forms: one response one criterion, one response several criteria, or pairwise (Tie and Neither allowed)
What a judge needs
The task and source material, responses in labelled blocks apart from instructions, a rubric with defined levels and decision rules, evidence and explanation first and verdict last
Position bias
A judge may prefer a response because of its position; check by swapping A and B in a fresh chat
Does judge agreement show the judge is correct?
No. Agreement between runs, or with the rubric, does not show correctness; validate the judge against human ratings before trusting it at scale. A judge is a prompt too
Evaluation tools
LangSmith (course tool: traces calls, datasets, prompt versions, evaluators, comparisons), Promptfoo (open-source prompt test runner), W&B Weave (tracing and evaluation). The OpenAI prompt optimizer can make some inputs worse, so test before and after
Tools vs method
Tools change every semester; the method does not. Keep prompts and tests in versioned code; use a tracing tool to see what ran
LangSmith workflow
Dataset of test inputs, two stored prompt versions, an experiment (each version run over the dataset, evaluators score every row), then compare side by side
What a trace records
Every call: exact messages sent, model, tokens, latency, cost and the evaluator's verdict
Chat app vs API
System prompt: custom instructions vs a message you write and version. History: kept invisibly vs a list your code re-sends every turn. Model version: changes under you vs pinned. Cost: subscription per seat vs per token. Errors: a retry button vs status codes your code handles
Multi-turn in code
Append the reply and the next question to the list, then send the whole list again
Anatomy of an API call
base_url and key pick the server; model picks the weights; messages carry everything the model sees; max_tokens caps reasoning plus visible output; reasoning effort can be set
Reading the response
The text is in choices[0].message.content; finish_reason says why generation ended; usage reports prompt, completion, reasoning and cached tokens (and cost on OpenRouter). Finish_reason and usage are the receipt
Streaming
With stream=True the reply arrives in chunks; the final chunk carries usage (and cost on OpenRouter)
finish_reason values
stop = normal end. length = max_tokens or the context window reached (raise the limit or shorten input; check for an empty answer). content_filter = provider refused or cut output (log it, do not retry blindly). error mid-stream = a failure after streaming began, arrives as a chunk, not an HTTP status
Why a small max_tokens can give an empty answer
On reasoning endpoints max_tokens covers reasoning plus output; the budget goes to thinking, finish_reason is length, and reasoning tokens are still billed
Four meters on every call
Input (system prompt, tool definitions, re-sent history, new message), cached input, output, reasoning (billed as output)
Cached input
A repeated prefix the provider recognises, billed at a much lower read price; OpenAI needs at least 1,024 tokens and cache writes cost 1.25x. Stable prefixes, including unchanged history, can reduce cost
Cost per task
The sum of every attempt's actual charge, retries and failures included
Retry or fix?
Retry temporary failures; fix invalid requests and exhausted budgets
429 error
Too many requests or tokens per minute or day; back off with jitter, honour Retry-After, cap concurrency
402, 403, 400 and 5xx
402: out of credits, key limit or in-flight budget (OpenRouter holds each running request's estimated cost; wait or add credits). 403: a budget, permission, guardrail or moderation (read the message). 400: bad request, fix it. 5xx: server error, retry with backoff
Batch APIs
OpenAI and OpenRouter batch APIs trade latency for a lower price, for work that can wait
API key safety
A key is money and identity. Store it in Colab Secrets or an environment variable (or an uncommitted .env file); never print it or put it in a cell or screenshot; use separate keys per project