We have shipped internal assistants that answer policy questions, pull metrics from Snowflake, and file Jira issues. The fastest path to value was rarely a single technique. The right answer depended on volatility of the knowledge, who owns the ground truth, the latency and cost budget, and how much maintenance the team can absorb this quarter.
Below is the decision framework we actually use, the numbers we see in production, and a small reference implementation you can copy and adapt.
What we optimize for
These are the levers that have consistently determined the architecture.
- Knowledge volatility. If the answer changes weekly, you probably need retrieval. If it changes quarterly or slower, fine-tuning has a shot. If it changes hourly or is user specific, a tool or API is the source of truth.
- Source of truth. If a system of record exists, call it. If the truth is spread across docs and email, retrieve then reason. If neither exists and you need consistent behavior, fine-tune.
- Latency budget. Sub 400 ms end to end is hard with cloud LLMs and RAG. If you must hit that, favor a small local model or short tool paths. 700 to 1500 ms is comfortable for RAG with a single LLM call.
- Accuracy expectations. Zero hallucination is a tool problem with idempotent actions and confirmations. High but not perfect can be RAG with citations. Style or taxonomy consistency is a fine-tune.
- Data risk. If data cannot leave your VPC, you will host the vector store and likely the model. If some data can egress, managed embeddings are fine. If you handle PHI or PII, add masking and access checks.
- Maintenance. RAG has an ingestion pipeline you will own. Fine-tuning has a labeling pipeline and versioning burden. Tools have integration sprawl and change management.
If you want a structured way to pick vendors for each box, a short vendor stack decisions run pays for itself when you are mixing vector stores, model APIs, and workflow engines.
When RAG wins
RAG wins when the content changes faster than you can label, and when auditability with citations matters. Typical internal examples: HR or policy Q&A, architecture docs, on-call runbooks, sales playbooks.
What has worked reliably for us:
- Chunk size 300 to 800 tokens with 50 to 120 token overlap. If your docs have code or tables, bias smaller and keep structure in the chunk metadata.
- Embeddings. text-embedding-3-small is $0.02 per million tokens, fast, and good enough for most internal corpora. For niche terms, re-try with the large variant then keep whichever gives better top-10 recall on a 100 question test set.
- Retrieval. Top-k of 6 to 10 with MMR re-ranking, cap context at 3000 tokens. Use metadata filters to enforce team or repo boundaries.
- Latency. Vector lookup 20 to 80 ms in memory on pgvector or FAISS, 100 to 200 ms if you cross AZ or use a managed service. LLM 300 to 1200 ms depending on model and output length. End to end 600 to 1700 ms.
- Costs. Embedding a 200 MB wiki, about 30 million tokens, is roughly $0.60 with the small model. Storing vectors in Postgres adds cents per GB per month. Most cost sits in LLM inference per query.
Failure modes to plan for:
- Stale answers. Add a commit hook to re-embed on merge, and TTL any Slack exports. Track doc last_modified in metadata and show it in the answer.
- Irrelevant retrieval. Audit top-k per query on a weekly golden set. If precision slips, re-chunk or adjust k. Usually k was too high or chunking lost table context.
- Permissions leaks. Apply ACLs at retrieval time. Do not try to post filter in the LLM, you will leak.
If you have not done the inventory of what to index and who owns it, start with an AI readiness assessment so you do not ship a fast hallucination engine.
When fine-tuning is the lever
We fine-tune when the task is stable and repetitive, where consistency beats novelty.
Good candidates:
- Response style normalization for support answers, if product surface is stable.
- Classification and routing, like mapping internal intents to 40 workflows, or tagging tickets with a 120 label taxonomy.
- Thin knowledge domains that do not change weekly, like policy boilerplate or product SKUs updated quarterly.
Numbers we see in practice:
- Data volume. 1k to 5k examples is enough for style and short-form tasks. 10k to 50k for behavior changes. Expect about 10 to 20 hours of labeling per 1k examples at good quality if engineers help write seeds.
- Latency. A 7B model on a single T4 can respond in 150 to 350 ms for 100 token outputs. On CPU, budget 600 to 1200 ms.
- Costs. Cloud fine-tuning jobs run tens to hundreds of dollars. Inference of a 7B open-weight model is cents per thousand tokens if you run it yourself, more if managed.
Trade-offs:
- You freeze knowledge into weights. Anything that changes weekly will drift and require re-training, which is why we almost never use fine-tuning alone for Q&A.
- You gain determinism and can compress prompts. That saves latency and tokens on hot paths.
We also fine-tune tiny models to serve as local routers or safety filters that must run inside the VPC.
When tool use is the only correct answer
If the question is about live data or the output is an action, call a tool. Examples: “What are open Sev1s for ACME this week,” “Create a Jira for this bug,” “Reset this user’s password,” “Book me a room at 2 pm.”
Design patterns that stuck:
- System of record first. Do not guess a number that exists in Snowflake or Grafana.
- Idempotency and confirmations. Any destructive action needs an explicit confirmation turn. Non destructive reads can be single turn.
- Narrow tools. One tool that calls a giant internal API is harder to secure and debug than five tools with exact schemas.
- Observability. Log tool inputs and outputs with redaction. Attach them to the session so an auditor can replay.
Failure modes:
- Tool loops. Put a max tool depth of 3 and short circuit with a helpful error.
- Wrong parameters. Validate required fields before calling. On 4xx, echo the validation error back to the model and retry once.
- Access control. Enforce user scoping at the tool boundary, not through prompt instructions.
If you are building multi tool agents, our AI agents work lays out more robust patterns for parallel tools and long running tasks.
Latency, cost, and footprint you can plan around
These are representative 50th percentile numbers from recent builds.
- Cloud LLM call, 600 input, 200 output tokens. Cheap model 300 to 600 ms, mid tier 700 to 1200 ms, high end 1200 to 2500 ms.
- On prem 7B model, 16 bit, single T4, 200 token output. 150 to 350 ms decode after prompt in cache.
- Retrieval round trip to in VPC pgvector. 20 to 80 ms. Cross AZ add 30 to 60 ms.
- Embeddings throughput. 2k to 10k tokens per second per process for OpenAI style APIs. Index a 200 MB wiki in a few minutes with parallel workers.
- Cost per 1 million tokens. Embeddings small $0.02. Cheap LLM input $0.15 to $0.50, output $0.60 to $1.50. Mid tier input $3, output $15. Self hosted open weights are hardware bound, think dollars per hour per GPU.
If you must hit a 400 ms P95 and still ground in internal docs, consider a two pass design. First a small local model routes to either a tool or a pre-baked answer. Only escalate to the big model when needed.
Data risk and governance
Internal assistants touch sensitive data. We treat risk as part of the design, not an afterthought.
- Redaction. Mask emails, phone numbers, employee IDs, and secrets in logs. Do the same in prompts if you call external APIs.
- Egress control. Keep embeddings and vector stores inside the VPC if policy requires it. If you use SaaS embeddings, only send non sensitive text.
- Row level security. Enforce ACLs in retrieval queries. If someone loses access to a Confluence space, they lose access in the assistant instantly.
- Audit trail. Store user, prompt, retrieval IDs, tool calls, and outputs per turn. Make it queryable.
We pair this with an architecture review to make sure auth, audit, and data flow diagrams match the code paths, not the slide deck.
A pragmatic decision recipe you can automate
Here is a minimal router that:
- Uses FAISS and OpenAI embeddings for local RAG.
- Calls tools for live data or actions via function calling.
- Falls back to RAG for Q&A and to a short direct answer otherwise.
You can run this as a proof of concept. Replace tool stubs with your systems and add auth.
# pip install openai faiss-cpu tiktoken
import os
import json
import faiss
import numpy as np
from dataclasses import dataclass
from typing import List, Tuple
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
EMBED_MODEL = "text-embedding-3-small"
CHAT_MODEL = "gpt-4o-mini"
@dataclass
class Doc:
id: str
text: str
meta: dict
class RAGIndex:
def __init__(self):
self.index = None
self.docs: List[Doc] = []
self.emb_dim = 1536 # embedding-3 dims
def build(self, docs: List[Doc]):
self.docs = docs
vectors = self._embed([d.text for d in docs])
self.index = faiss.IndexFlatIP(self.emb_dim)
faiss.normalize_L2(vectors)
self.index.add(vectors)
def _embed(self, texts: List[str]) -> np.ndarray:
out = client.embeddings.create(model=EMBED_MODEL, input=texts)
vecs = np.array([e.embedding for e in out.data], dtype=np.float32)
return vecs
def search(self, query: str, k: int = 6, filters: dict | None = None) -> List[Doc]:
q = self._embed([query])
faiss.normalize_L2(q)
scores, idxs = self.index.search(q, k)
results = []
for i in idxs[0]:
d = self.docs[i]
if not filters:
results.append(d)
else:
ok = all(d.meta.get(k) == v for k, v in filters.items())
if ok:
results.append(d)
return results
# Example tool stubs
def query_snowflake(sql: str) -> dict:
# Replace with real query and credentials
return {"rows": [["sev1_open", 4]], "columns": ["metric", "value"]}
def create_jira(summary: str, description: str, project: str) -> dict:
# Replace with real API call
return {"key": "ENG-1234", "url": "https://jira.example.com/browse/ENG-1234"}
TOOLS = [
{
"type": "function",
"function": {
"name": "query_snowflake",
"description": "Fetch live metrics from the warehouse using SQL.",
"parameters": {
"type": "object",
"properties": {"sql": {"type": "string"}},
"required": ["sql"],
},
},
},
{
"type": "function",
"function": {
"name": "create_jira",
"description": "Create a Jira issue with the given details.",
"parameters": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"description": {"type": "string"},
"project": {"type": "string"},
},
"required": ["summary", "project"],
},
},
},
]
SYSTEM = (
"You are an internal assistant. "
"If user asks for live data or to perform an action, call a tool. "
"If it is a question about internal docs, ask for retrieval context from the host app and answer with citations. "
)
def chat_with_tools(user_msg: str, rag_docs: List[Doc] | None = None) -> str:
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": user_msg},
]
if rag_docs:
context = "\n\n".join([f"[{d.id}]\n{d.text}" for d in rag_docs])
messages.append({"role": "system", "content": f"RAG_CONTEXT:\n{context}"})
resp = client.chat.completions.create(
model=CHAT_MODEL, messages=messages, tools=TOOLS, tool_choice="auto"
)
msg = resp.choices[0].message
if msg.tool_calls:
tool = msg.tool_calls[0]
name = tool.function.name
args = json.loads(tool.function.arguments)
if name == "query_snowflake":
result = query_snowflake(**args)
elif name == "create_jira":
result = create_jira(**args)
else:
result = {"error": "unknown tool"}
messages.append(
{
"role": "tool",
"tool_call_id": tool.id,
"name": name,
"content": json.dumps(result),
}
)
# Final answer after tool
final = client.chat.completions.create(model=CHAT_MODEL, messages=messages)
return final.choices[0].message.content
else:
return msg.content
# Example wiring
if __name__ == "__main__":
# Build a tiny RAG index from local snippets
docs = [
Doc(id="HR-pto", text="PTO policy: Employees have 20 days per year. Carryover up to 5 days.", meta={"space": "HR"}),
Doc(id="RUN-sev1", text="Sev1 is user visible outage. Page on-call immediately. Create Jira in ENG.", meta={"space": "RUN"}),
]
rag = RAGIndex()
rag.build(docs)
query = "How many Sev1s are open this week for ACME?"
# Live data question, no RAG context needed
print(chat_with_tools(query))
query2 = "What is our PTO policy?"
ctx = rag.search(query2, k=4, filters={"space": "HR"})
print(chat_with_tools(query2, rag_docs=ctx))
This is intentionally simple. In production we separate routing from answering. A small local model or a rules engine labels the intent as Q&A versus workflow. We only fetch retrieval context when the intent is Q&A. We enforce user permissions in the retrieval query and in tool adapters.
Maintenance, monitoring, and what we would do differently
Regardless of approach, you will own three loops.
- Data loop. For RAG, keep the index fresh with CI or change data capture. For tools, track API version drift. For fine-tuning, accumulate new examples and plan monthly refreshes if behavior drifts.
- Quality loop. Maintain a golden set of 50 to 200 real questions with expected answers or actions. Track groundedness, citation validity, tool success, and time to first token. We use LLM judges sparingly, and we always spot check.
- Incident loop. Instrument per turn with retrieval hit rates, tool error codes, and token counts. Alert on spikes in 4xx or 5xx from tools and on retrieval k that returns empty.
If we could rewind a few projects, we would start with the router and the evaluation set on day one. It is tempting to build the ingestion pipeline first. The router clarifies which paths you actually need and keeps your latency budget real.
If you want a team to push this from POC to production, we usually pair the app crew with our AI product engineering group rather than a one off throw over the wall. That speeds up the boring parts like observability and rollout.
TLDR rules of thumb
- Q&A on changing docs. RAG first. Add a cheap router and a minimal ingestion job tied to your doc sources. Fine-tune later for routing if needed.
- Deterministic behavior or strict format. Fine-tune a small model, or write a narrow tool and validate inputs.
- Live data or actions. Tools first, with confirmations and idempotency. Add a small safety model for policy and parameter checks.
- Mixed workload. Router in front. Budget 600 to 1500 ms P95. Expect to iterate on chunking and intent labels.
If you have to lock a plan this quarter with known budget and constraints, a short vendor stack decisions sprint combined with an AI agents oriented design will reduce rework when you add the second and third tool later.



