How do large language models actually work?
An LLM is trained on huge amounts of text to predict the next piece of text. Doing this well forces it to learn grammar, facts, reasoning patterns and styles. When you give it instructions, it continues the text in the way that best fits them. It does not look things up unless you give it a way to.
A large language model starts as a neural network with billions of adjustable values. During training it reads enormous amounts of text and repeatedly tries to predict the next word, adjusting its values whenever it is wrong. After enough training, it has absorbed a great deal about how language works and about the world described in that text.
A second stage of training teaches the model to follow instructions and to respond helpfully and safely, using examples of good answers and feedback from people. This is what turns a text predictor into an assistant that answers questions, writes in a given style and follows rules.
What this means in practice
- It knows a lot, but not your business. The model has never seen your internal documents, prices or customers unless you provide them.
- Its knowledge has a cut off date. Anything after training is unknown unless you supply it.
- It aims to sound right. If it lacks the facts, it may produce a confident, plausible answer anyway. This is called hallucination.
- It follows patterns well. Show it examples of the output you want and it will usually copy the format and tone.
Every good generative AI application is built around these facts: supply the knowledge it lacks, give it clear patterns to follow, and check what it produces.
What are tokens and context windows, and why do they matter?
Models read and write text in small pieces called tokens. The context window is how many tokens a model can consider at once. Both drive cost and speed: you pay per token, and longer inputs take longer to process.
A token is roughly a short word or part of a longer word. Model providers charge by the number of tokens sent in and the number generated. Output tokens usually cost more than input tokens, and more capable models cost more per token than smaller ones.
The context window
The context window is the maximum amount of text, including instructions, documents, conversation history and the answer, that the model can handle in one request. Modern windows are large enough to hold long reports or many documents. That does not mean you should fill them.
Why less context is often better
- Cost. Every token sent is billed, on every request.
- Speed. Longer inputs take longer before the first word appears.
- Accuracy. When the relevant fact is buried in a huge input, models can miss it. Focused context usually gives better answers.
Good systems select exactly what each request needs, summarise long histories and drop what is no longer relevant. Chapter 15 covers the cost side in more detail.
How do you write prompts that work in production?
Production prompts are versioned, tested assets. They state the role and task clearly, give rules and the required output format, include a few strong examples, separate instructions from untrusted content, and are checked against a test set after every change.
Prompting in a chat window and prompting inside an application are different jobs. In an application, the same prompt runs thousands of times on inputs nobody has seen yet. It must be reliable, not just clever.
Parts of a strong prompt
- Role and goal. Who the model is acting as and what it must achieve.
- Rules. What it must always do, what it must never do, and what to do when unsure.
- Context. The documents, records or data it should use, clearly marked.
- Examples. Two or three examples of excellent inputs and outputs.
- Output format. The exact structure required, such as headings, bullets or a data schema.
Habits that prevent problems
- Keep untrusted content, such as emails or web pages, clearly separated and labelled, so it cannot be mistaken for instructions.
- Tell the model what to do when information is missing, such as "say you do not have enough information".
- Store prompts in version control, never only in someone's notes.
- Run the test set before releasing any prompt change.
- Keep prompts as short as they can be while still passing tests.
"Use only the policy text provided below. If the policy does not answer the question, reply exactly: I could not find this in the policy, and suggest contacting the HR team." A single rule like this removes a large share of made up answers.
How does retrieval make generative AI accurate?
Retrieval augmented generation, or RAG, searches your own content for the passages relevant to each request and gives them to the model to answer from. Facts stay current because you update documents, not the model, and every answer can show its sources.
Most business uses of generative AI need company specific knowledge: policies, product details, contracts, records. Putting that knowledge into the model itself through training is slow, expensive and hard to update. Retrieval solves this by looking things up at the moment of each question.
The basic flow
- Your documents are split into sections and indexed for search, using both meaning based and keyword methods.
- When a question arrives, the system finds the most relevant sections, often reranking them for precision.
- The best sections are added to the prompt with instructions to answer only from them.
- The model writes the answer and cites the sections it used.
Where RAG projects go wrong
The model is rarely the weak link. Problems usually come from content that is outdated or contradictory, documents split badly, search that misses exact terms such as product codes, or missing permission checks. Fixing retrieval quality is most of the work. For large and complex document collections, see AI search and knowledge extraction.
When should you fine tune a language model?
Fine tune when you need very consistent style or format at high volume, a specialised task that prompting does not handle well, or a smaller, cheaper model that performs like a larger one on a narrow job. Do not fine tune to add facts. Use retrieval for facts.
Fine tuning means continuing to train an existing model on your own examples, so it learns your preferred behaviour. Modern methods such as LoRA adjust only a small part of the model, which keeps cost and time manageable.
Good reasons to fine tune
- Consistency. Thousands of outputs a day must follow the same structure and tone exactly.
- Specialised tasks. Classifying documents into your own categories or extracting fields from unusual formats.
- Efficiency. A small fine tuned model can match a large general model on one narrow task at a fraction of the cost and with faster responses.
- Domain language. Fields with heavy jargon where general models struggle.
Poor reasons to fine tune
- To teach the model your latest prices or policies, which change and are better served by retrieval.
- Because it sounds more advanced than prompting.
- Without a few hundred high quality examples, which fine tuning depends on.
We always compare a fine tuned model against strong prompting and retrieval on the same test set. Fine tuning is only worth its upkeep if it clearly wins.
Should you self host an open weight model?
Self hosting an open weight model such as Llama or Mistral gives full data control and can be cheaper at steady high volume, but you take on the work of running, scaling and updating the infrastructure. It suits strict data rules, very high volume or specialised fine tuned models.
Open weight models can be downloaded and run on your own servers or cloud account. Their quality has improved quickly, and for many business tasks a well chosen open model, especially when fine tuned, performs very well.
Reasons to self host
- Data must never leave your environment, for legal or contractual reasons.
- Volume is high and steady enough that running your own servers costs less than paying per request.
- You need a fine tuned model that you fully control.
- You want to avoid dependence on a single model provider.
What you take on
- Choosing and paying for suitable hardware, usually GPUs.
- Serving software, such as vLLM, that handles many requests efficiently.
- Scaling for peaks and keeping costs down in quiet periods.
- Security patches, monitoring and model upgrades.
- Checking the model's licence terms for commercial use.
A hybrid is common: a closed model through an enterprise cloud service for hard tasks, and a self hosted open model for high volume or sensitive steps. Our cloud engineering team builds and runs the infrastructure.
How do you get reliable structured output from an LLM?
Ask for a defined schema, use the provider's structured output or tool calling features, validate every response against the schema and business rules, and retry or route to a person when validation fails.
Many business applications do not need prose. They need data: fields extracted from a contract, a category for an email, a set of parameters for a system call. Free text is hard for software to use. Structured output solves this.
Techniques that work
- Schemas. Define exactly which fields, types and allowed values are expected.
- Native features. Most major models support structured output modes or tool calling that make the model return data in the defined shape.
- Validation. Check every response: required fields present, numbers in range, dates valid, values from allowed lists.
- Cross checks. Compare extracted values with your systems, such as checking a customer number exists.
- Retries and fallbacks. If validation fails, retry with the error explained, then send to a person if it fails again.
Tool calling
Tool calling lets the model request that your code run a function, such as looking up an order, with structured parameters. Your code runs it and returns the result. This is how generative AI connects safely to business systems, and it is the foundation of AI agents.
How do you reduce hallucinations?
Give the model the facts it needs, tell it to answer only from them, let it say when it does not know, ask for sources, validate outputs, use the right model for the task, and keep people reviewing high stakes outputs.
Hallucination is when a model produces something that sounds right but is not true or not supported by any source. It cannot be removed completely, but it can be reduced to a level that is safe for the use case.
Layers of defence
- Grounding. Supply relevant facts through retrieval or direct data, so the model is not guessing.
- Permission to not know. Instruct the model clearly to say when the information is missing.
- Citations. Require a source for each claim, and check that cited sources contain the claim.
- Narrow tasks. Smaller, well defined tasks hallucinate less than open ended ones.
- Validation. Check numbers, names and references against your systems.
- Tools for maths. Let a calculator or your system do calculations, never the model alone.
- Human review. Keep a person in the loop where an error would be costly.
We measure hallucination directly during testing by asking questions that are not answered in the content and checking that the system declines, and by checking a sample of answers against their sources.
How do you test generative AI output?
Build a test set of real inputs with examples of good outputs, score results with a mix of automatic checks, model based judges and human review, and run the tests after every change to prompts, models or data.
Generative output is harder to test than normal software because there are many acceptable answers. That does not mean it cannot be tested. It means tests measure qualities rather than exact matches.
What to measure
| Quality | How it is checked |
|---|---|
| Correctness | Facts match the source or known answer |
| Faithfulness | Every claim is supported by the provided context |
| Completeness | Key points are covered |
| Format | Output follows the required structure, checked automatically |
| Tone and style | Matches the brand guide, checked by reviewers or a judge model |
| Safety | No personal data leaks, harmful content or policy breaches |
Judges and humans
A second model can score outputs against a checklist quickly and cheaply. Judges have blind spots, so we calibrate them against human reviews and keep people reviewing a sample over time. Our AI evaluation and LLMOps page goes deeper into this discipline.
Can generative AI work with documents, images and audio?
Yes. Many current models are multimodal, meaning they can read images, scanned documents, charts and screenshots as well as text, and speech models handle audio. This opens up uses such as reading forms, describing photos and summarising calls.
Documents and images
Multimodal models can look at a scanned invoice, a photo of damage, a chart or a screenshot and describe or extract what they see. For high volume document processing, dedicated document AI services are often combined with LLMs, so layout and text are captured reliably before the model reasons about them. Our AI automation work uses this heavily.
Audio and speech
Speech to text models transcribe calls and meetings accurately in many languages. LLMs then summarise, extract actions or check calls against scripts. Text to speech models produce natural voices for phone systems and accessibility. See voice AI development.
Video
Video understanding and generation are advancing quickly. Practical business uses today include summarising training videos, searching recorded meetings and creating short marketing variations, each with careful review.
How can businesses use AI image generation responsibly?
Use image generation for concepts, variations and product visuals with brand review, choose tools with clear commercial terms, avoid imitating real people, artists or brands, and label AI generated imagery where your policies or local rules require it.
Image generation can produce product shots in new settings, concept art, background variations and marketing visuals in minutes. Used well, it speeds up creative work. Used carelessly, it creates legal and brand risk.
Good uses
- Concept exploration before a photo shoot or design project.
- Background and setting variations for existing product photos.
- Many ad variations for testing, with brand review.
- Illustrations for internal training and documentation.
Rules we follow
- Use tools whose terms allow commercial use and explain how they handle training data.
- Never generate images designed to look like real people without consent, or to imitate a specific living artist's style or another company's brand.
- Keep human designers in control of final assets.
- Record which assets are AI generated, and label them where required.
Our AI assisted design page covers how designers use these tools in real projects.
What copyright, privacy and policy issues come with generative AI?
Protect personal and confidential data, use model services under terms that suit your obligations, review outputs that will be published for originality and accuracy, follow transparency rules for AI generated content, and give staff a clear AI use policy.
Privacy
Personal data sent to a model is still personal data. Use enterprise services with appropriate data processing terms and regions, send only what each task needs, mask data in logs and set retention periods. Laws such as GDPR and India's DPDP Act apply as they would to any processing.
Confidentiality
Staff pasting confidential material into consumer AI tools is one of the most common risks. Approved enterprise tools and a clear policy reduce it more than bans do.
Copyright and originality
The legal position on AI training and outputs is still developing in many countries. Practical steps: review published content for originality, avoid prompts that ask for copies of existing works, keep records of how important content was made, and take legal advice for high value creative work.
Transparency
Regulations such as the EU AI Act include transparency duties, for example around AI systems that interact with people and certain AI generated content. We build disclosure into products where it applies. For a wider governance plan, see AI consulting.
How do you make generative AI feel fast and trustworthy to users?
Stream answers as they are written, show what the system is doing, keep outputs short and scannable, show sources, make editing easy and never take important actions without the user's confirmation.
Users judge AI features on how they feel as much as on accuracy. A correct answer that takes too long, or arrives as a wall of text with no sources, still feels unreliable.
Design choices that matter
- Streaming. Showing words as they are generated makes waiting feel much shorter.
- Progress cues. "Searching policies" or "Reading 3 documents" reassures users during longer steps.
- Smaller models for quick steps. Use fast models for classification and routing, and stronger models only where needed.
- Sources and confidence. Links to sources and clear statements when information is missing build trust.
- Editable outputs. Present drafts as drafts, easy to change.
- Confirmation for actions. Sending, saving or changing anything needs a click from the user.
- Feedback buttons. A quick thumbs up or down feeds improvement and shows users their view counts.
What does it take to run LLM applications in production?
Version control for prompts and configurations, tracing of every request, quality and cost monitoring, alerts, safe release processes, fallback models and a plan for model updates. This discipline is often called LLMOps.
A demo runs on a laptop. A production system serves real users every day, through model updates, traffic spikes and changing data. Keeping it healthy needs operational habits.
The essentials
- Tracing. Every request logged with inputs, retrieved context, model, prompt version, output, time and cost.
- Versioning. Prompts, retrieval settings and model choices versioned together, so any result can be reproduced.
- Release process. Changes tested against the test set, then released to a small share of users before everyone.
- Monitoring. Dashboards for quality signals, user feedback, latency, errors and spend.
- Fallbacks. A second model or simpler mode when a provider has problems.
- Model lifecycle. Providers update and retire models. Pin versions, test replacements and switch deliberately.
Our AIOps team extends this to wider infrastructure monitoring and incident response.
How do you control generative AI costs?
Measure cost per task early, route simple steps to cheaper models, send less context, cache repeated work, limit output length, batch work that is not urgent and set budgets with alerts.
Generative AI costs scale with use. A feature that costs very little in a pilot can become a large bill when thousands of users adopt it. Cost needs designing, not just watching.
Practical levers
- Model routing. Use a small, fast model for classification, extraction and simple replies, and a larger one only for hard cases.
- Lean context. Send only the passages and history each request needs.
- Caching. Reuse answers for repeated questions and reuse the fixed part of prompts where providers support it.
- Output limits. Ask for the length you need. Shorter outputs cost less and read better.
- Batching. Run non urgent work, such as overnight summaries, through cheaper batch options where available.
- Budgets. Track spend by feature and team, with alerts before limits are reached.
For products sold to customers, unit costs also shape pricing. We model cost per user and per action during prototyping, so pricing decisions are based on measurements.
How is generative AI used in different industries?
The core abilities are the same, reading, writing and answering, but each industry applies them to its own documents and rules. Regulated industries lean on grounding, review and audit. Product and content heavy industries lean on drafting and variation at scale.
Financial services
Summaries of research and filings, drafting client communications for review, extracting data from statements and contracts, and answering staff questions from policy libraries. Advice to clients stays with qualified people.
Healthcare
Drafting referral letters and discharge summaries for clinician review, summarising long records, answering staff questions from protocols and handling administrative correspondence. Patient data stays in approved environments.
Retail and ecommerce
Product descriptions at scale, search that understands natural questions, review summaries, campaign variations and support answers grounded in order and policy data.
Manufacturing
Tender and proposal drafts, technical documentation, maintenance knowledge search and summaries of quality reports and supplier documents.
Legal
Contract summaries, clause comparisons, first pass reviews against playbooks and research support, always with lawyers reviewing output and strict confidentiality.
Insurance
Claim file summaries, policy wording questions, broker correspondence drafts and extraction from loss reports, with explainability for anything affecting a customer decision.
How should a business start with generative AI?
Give staff safe, approved tools and a clear policy, pick one or two focused use cases with real value and good data, prove them with a prototype on your own examples, and build shared foundations such as model access, logging and retrieval as you go.
Many businesses feel pressure to "do something with generative AI" and either freeze or launch too many disconnected experiments. A simple sequence avoids both.
- Safe everyday tools. Provide an approved enterprise AI assistant for staff, with a short policy on what data may be used. This stops risky use of consumer tools and builds familiarity.
- One focused use case. Choose a task with clear value, real volume and content you already have, such as drafting replies from policies or summarising long documents.
- Prototype on your examples. Test approaches and models on real inputs and compare against what good looks like.
- Build properly. Add retrieval, guardrails, testing, monitoring and a good interface for the chosen use case.
- Reuse foundations. The second use case reuses the model gateway, logging, retrieval and security built for the first.
If you have many ideas and need help choosing, our AI consulting team runs a short discovery to rank them by value and effort.
How does generative AI relate to AI agents and automation?
Generative AI is the engine. Automation uses it for specific steps inside fixed workflows. Agents use it to plan and take several steps toward a goal. Copilots use it to help a person in their tools. The same models power all of them.
People often use generative AI, agents, copilots and automation as if they meant the same thing. They are related but different ways of putting the same technology to work.
| Pattern | Who is in control | Typical use |
|---|---|---|
| Generative feature | The user asks, the model answers | Summarise, draft, translate, answer |
| Copilot | The user, with suggestions in context | Help inside a CRM, helpdesk or document |
| Automation | A designed workflow | Read invoices and post them to an ERP |
| Agent | The agent, within set limits | Investigate and resolve an exception |
Choosing the right pattern for each problem matters more than the model. A task that needs a person's judgement every time suits a copilot. A high volume task with a clear normal path suits automation. An open ended task with several systems and decisions may suit an agent, with approvals for risky steps.
Most organisations end up using several patterns on shared foundations: one model gateway, one retrieval layer over company content, one approach to logging and security. Building those foundations well once makes every later project faster.
What does a generative AI project look like in practice?
Frame a sharp use case, gather real examples, compare approaches and models, build with guardrails and testing, launch to a small group, then scale while watching quality and cost.
This manufacturer is an invented composite based on typical generative AI projects. It is not a real client.
An industrial equipment maker receives detailed tender requests from large customers. Each response takes a bid team many days, mostly spent finding and adapting text from past bids, product manuals and certification documents.
Framing and examples
The goal is a first draft of each tender section, grounded in approved content, that the bid team edits. The team supplies past tenders, their winning responses and the current product library. Bid managers mark which past answers were excellent.
Comparing approaches
Prompting alone produces fluent but generic text with wrong specifications. Retrieval over the product library and past bids fixes accuracy. A light fine tune on excellent past answers improves structure and tone. The combination wins clearly on the test set.
Building
The tool reads each tender question, retrieves matching content, drafts a response with sources for every specification, and flags questions where no approved content exists. Numbers come only from the product database. Everything is reviewed by the bid team before submission.
Launch and scale
One bid team uses it first. Their edits feed back into examples and content fixes. The flagged gaps list shows which product documents need updating. Once quality and cost are steady, the tool rolls out to other regions, with spend tracked per bid.
What are the most common generative AI mistakes?
Expecting the model to know your business, skipping testing, fine tuning for facts, ignoring running costs, letting it calculate, and launching without monitoring or a way for users to give feedback.
What should you ask a generative AI development company?
Ask how they will ground answers, test quality, choose models, control cost, protect data and handle model changes, and who owns the result.
- How will the system get our company knowledge, and how will it stay current?
- How will you measure quality before launch, using what examples?
- How will you reduce and detect made up answers?
- Which models will you compare, and how will you choose?
- Can we switch models later without rebuilding?
- Will fine tuning be needed, and how will you prove it helps?
- Where will our data be processed and stored?
- What will each request or user cost to run?
- How will you monitor quality and cost after launch?
- Who owns the code, prompts, test sets and any tuned models?
We answer all of these in writing before a project begins. To grow your own team instead, you can hire AI/ML engineers for as long as you need.