Q31RAG Retrieval Quality
What is hybrid search?
Hybrid search combines lexical search, which matches terms, with vector search, which matches semantic similarity.
Answer
Hybrid search combines lexical search, which matches terms, with vector search, which matches semantic similarity. It can improve retrieval for domain-specific names, IDs, and paraphrased questions. Normalize or fuse rankings carefully and evaluate the combination against representative queries rather than assuming hybrid search always wins.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q32RAG Retrieval Quality
What is reranking?
Reranking scores an initial candidate set with a more precise model or cross-encoder to improve ordering.
Answer
Reranking scores an initial candidate set with a more precise model or cross-encoder to improve ordering. It can reduce irrelevant context reaching the LLM but adds latency and cost. Retrieve a reasonably broad candidate pool, rerank it, then select a context budget that preserves complementary evidence.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q33RAG Retrieval Quality
What are precision and recall in retrieval?
Precision measures how much of the retrieved material is relevant, while recall measures how much of the relevant material was retrieved.
Answer
Precision measures how much of the retrieved material is relevant, while recall measures how much of the relevant material was retrieved. High precision reduces distracting context; high recall helps avoid missing required facts. Use labeled queries and inspect both metrics because optimizing only one can harm answer quality.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q34RAG Retrieval Quality
What is query rewriting?
Query rewriting transforms a user's request into a search-friendly query, possibly resolving references from conversation history or expanding synonyms.
Answer
Query rewriting transforms a user's request into a search-friendly query, possibly resolving references from conversation history or expanding synonyms. It can improve retrieval for vague questions but may distort the user's intent. Keep the original query, log the rewritten form, and evaluate rewrites on ambiguous and adversarial examples.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q35RAG Retrieval Quality
How do you reduce irrelevant context in RAG?
Use metadata filters, query rewriting, hybrid retrieval, reranking, deduplication, and context-budget selection to reduce irrelevant passages.
Answer
Use metadata filters, query rewriting, hybrid retrieval, reranking, deduplication, and context-budget selection to reduce irrelevant passages. Preserve source diversity when several documents support different parts of an answer. Measure retrieval quality and answer faithfulness rather than judging only by the number of chunks returned.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q36RAG Ingestion and Indexing
How do you build a document ingestion pipeline?
A robust ingestion pipeline discovers sources, extracts text, normalizes content, removes duplicates, chunks documents, attaches metadata, embeds chunks, and writes them to an index.
Answer
A robust ingestion pipeline discovers sources, extracts text, normalizes content, removes duplicates, chunks documents, attaches metadata, embeds chunks, and writes them to an index. Make each stage restartable and observable, and track source versions so changed or deleted documents can be reconciled. Handle extraction errors explicitly.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q37RAG Ingestion and Indexing
How should PDFs be processed for RAG?
PDF ingestion should extract text and structure where possible, use OCR for scanned pages, and preserve page numbers and headings for citations.
Answer
PDF ingestion should extract text and structure where possible, use OCR for scanned pages, and preserve page numbers and headings for citations. Tables and multi-column layouts can be corrupted by plain text extraction, so test against representative files. Keep a path to the original page or file for verification.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q38RAG Ingestion and Indexing
How do you update a vector index when a document changes?
Assign stable source and chunk identifiers, detect document version changes, and upsert new chunks while removing stale chunks from the previous version.
Answer
Assign stable source and chunk identifiers, detect document version changes, and upsert new chunks while removing stale chunks from the previous version. Make the update idempotent and avoid a window where both versions appear as equally current. Track indexing status and support retrying failed documents.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q39RAG Ingestion and Indexing
How do you delete a user's data from a RAG index?
Maintain mappings from source records to indexed chunks and embeddings so deletion can remove all derived representations.
Answer
Maintain mappings from source records to indexed chunks and embeddings so deletion can remove all derived representations. Include caches, replicas, backups, and logs in the deletion policy where applicable. Verify completion and ensure stale retrieval results cannot reappear from an asynchronous ingestion job.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q40RAG Ingestion and Indexing
What is incremental indexing?
Incremental indexing processes only new or changed content instead of rebuilding the entire corpus.
Answer
Incremental indexing processes only new or changed content instead of rebuilding the entire corpus. It reduces cost and refresh time but requires reliable change detection, deletion handling, and idempotent writes. Periodic reconciliation can detect missed updates and drift between source systems and the index.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q46Semantic Kernel Planning and Filters
How does function calling work in Semantic Kernel?
Function calling lets a model select a registered function and provide arguments based on the conversation and available function descriptions.
Answer
Function calling lets a model select a registered function and provide arguments based on the conversation and available function descriptions. The application or SDK validates and executes the call, then returns the result for the model to continue. Function selection is probabilistic, so permissions and business rules must remain in application code.
Syntax
Semantic Kernel prompt function:
```csharp
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
```
Diagram: App -> Kernel -> Prompt/Plugin function -> AI service or native code -> Result
Example
// C#-style Semantic Kernel pattern (API names can vary by SDK version)
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
Console.WriteLine(result);
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q47Semantic Kernel Planning and Filters
What are invocation filters in Semantic Kernel?
Invocation filters let applications inspect or modify function and prompt invocation behavior around execution.
Answer
Invocation filters let applications inspect or modify function and prompt invocation behavior around execution. They can support logging, validation, policy checks, and telemetry. Filters should be carefully ordered, tested, and kept deterministic where possible because they may affect every invocation path.
Syntax
Semantic Kernel prompt function:
```csharp
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
```
Diagram: App -> Kernel -> Prompt/Plugin function -> AI service or native code -> Result
Example
// C#-style Semantic Kernel pattern (API names can vary by SDK version)
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
Console.WriteLine(result);
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q48Semantic Kernel Planning and Filters
How should Semantic Kernel functions be described?
Function names and descriptions should communicate when a function is appropriate, what each parameter means, and what it returns.
Answer
Function names and descriptions should communicate when a function is appropriate, what each parameter means, and what it returns. Ambiguous descriptions can cause incorrect tool selection. Do not place secrets or broad instructions in descriptions, and never rely on the description to enforce authorization.
Syntax
Semantic Kernel prompt function:
```csharp
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
```
Diagram: App -> Kernel -> Prompt/Plugin function -> AI service or native code -> Result
Example
// C#-style Semantic Kernel pattern (API names can vary by SDK version)
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
Console.WriteLine(result);
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q49Semantic Kernel Planning and Filters
How do you register a plugin in Semantic Kernel?
A plugin is registered with a configured Kernel so its functions can be discovered and invoked through the application's selected flow.
Answer
A plugin is registered with a configured Kernel so its functions can be discovered and invoked through the application's selected flow. Registration should be explicit and environment-aware. Expose only the plugins required for the current user or workflow and test that unauthorized functions cannot be invoked.
Syntax
Semantic Kernel prompt function:
```csharp
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
```
Diagram: App -> Kernel -> Prompt/Plugin function -> AI service or native code -> Result
Example
// C#-style Semantic Kernel pattern (API names can vary by SDK version)
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
Console.WriteLine(result);
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q50Semantic Kernel Planning and Filters
How do you test a Semantic Kernel plugin?
Test plugin functions as ordinary application methods, then add integration tests for registration, parameter binding, model selection, and error propagation.
Answer
Test plugin functions as ordinary application methods, then add integration tests for registration, parameter binding, model selection, and error propagation. Include invalid arguments and authorization failures. Use a fake model or deterministic invocation path for unit tests so tests do not depend on live model output.
Syntax
Semantic Kernel prompt function:
```csharp
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
```
Diagram: App -> Kernel -> Prompt/Plugin function -> AI service or native code -> Result
Example
// C#-style Semantic Kernel pattern (API names can vary by SDK version)
var result = await kernel.InvokePromptAsync(
"Summarize this text in three sentences: {{$input}}",
new KernelArguments { ["input"] = documentText });
Console.WriteLine(result);
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q56LangGraph and Stateful Workflows
What is LangGraph?
LangGraph is a framework for building stateful, graph-shaped workflows for LLM applications, including loops, branching, tool use, and human review.
Answer
LangGraph is a framework for building stateful, graph-shaped workflows for LLM applications, including loops, branching, tool use, and human review. Nodes perform work and edges control transitions. Explicit state and checkpoints can make complex workflows easier to resume, but developers must define termination and failure behavior.
Syntax
State graph example:
```python
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
```
Diagram: START -> Node -> Conditional edge / tool node -> END (checkpoint state between steps)
Example
# Python-style LangGraph pattern
from typing import TypedDict
from langgraph.graph import StateGraph, END
class State(TypedDict):
question: str
answer: str
def answer_node(state: State):
return {"answer": llm.invoke(state["question"]).content}
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q57LangGraph and Stateful Workflows
What is a node in LangGraph?
A node is a function or runnable that reads workflow state and returns updates to it.
Answer
A node is a function or runnable that reads workflow state and returns updates to it. Nodes can call models, retrieve documents, execute tools, or apply deterministic logic. Keep node side effects idempotent where possible because retries or resumed workflows may execute work again.
Syntax
State graph example:
```python
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
```
Diagram: START -> Node -> Conditional edge / tool node -> END (checkpoint state between steps)
Example
# Python-style LangGraph pattern
from typing import TypedDict
from langgraph.graph import StateGraph, END
class State(TypedDict):
question: str
answer: str
def answer_node(state: State):
return {"answer": llm.invoke(state["question"]).content}
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q58LangGraph and Stateful Workflows
What is an edge in LangGraph?
An edge determines which node executes after another node, while conditional edges select the next step based on state or a routing decision.
Answer
An edge determines which node executes after another node, while conditional edges select the next step based on state or a routing decision. Explicit edges make workflow control visible and testable. Validate routing values and provide a fallback for unexpected states to prevent dead ends.
Syntax
State graph example:
```python
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
```
Diagram: START -> Node -> Conditional edge / tool node -> END (checkpoint state between steps)
Example
# Python-style LangGraph pattern
from typing import TypedDict
from langgraph.graph import StateGraph, END
class State(TypedDict):
question: str
answer: str
def answer_node(state: State):
return {"answer": llm.invoke(state["question"]).content}
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q59LangGraph and Stateful Workflows
What is checkpointing in LangGraph?
Checkpointing persists graph state at defined points so a workflow can resume after interruption and support inspection or human-in-the-loop flows.
Answer
Checkpointing persists graph state at defined points so a workflow can resume after interruption and support inspection or human-in-the-loop flows. Persistence does not automatically make external side effects exactly once. Store only appropriate data, manage checkpoint retention, and design resumed nodes for idempotency.
Syntax
State graph example:
```python
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
```
Diagram: START -> Node -> Conditional edge / tool node -> END (checkpoint state between steps)
Example
# Python-style LangGraph pattern
from typing import TypedDict
from langgraph.graph import StateGraph, END
class State(TypedDict):
question: str
answer: str
def answer_node(state: State):
return {"answer": llm.invoke(state["question"]).content}
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q60LangGraph and Stateful Workflows
How do you prevent infinite loops in an agent graph?
Set maximum step counts, define explicit stop conditions, validate tool results, and route repeated failures to a terminal or human-review state.
Answer
Set maximum step counts, define explicit stop conditions, validate tool results, and route repeated failures to a terminal or human-review state. Track loop iterations and repeated tool calls. A graph should have a safe fallback when the model cannot decide or required information is missing.
Syntax
State graph example:
```python
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
```
Diagram: START -> Node -> Conditional edge / tool node -> END (checkpoint state between steps)
Example
# Python-style LangGraph pattern
from typing import TypedDict
from langgraph.graph import StateGraph, END
class State(TypedDict):
question: str
answer: str
def answer_node(state: State):
return {"answer": llm.invoke(state["question"]).content}
graph = StateGraph(State)
graph.add_node("answer", answer_node)
graph.set_entry_point("answer")
graph.add_edge("answer", END)
app = graph.compile()
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q61Tool Calling and Agent Design
What is tool calling?
Tool calling allows a model to request a defined function with structured arguments, such as searching a catalog or calculating a total.
Answer
Tool calling allows a model to request a defined function with structured arguments, such as searching a catalog or calculating a total. The model proposes a call; application code decides whether and how to execute it. Validate arguments, authorize the action, handle failures, and return only the result needed for the next step.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q62Tool Calling and Agent Design
How is tool calling different from ordinary text generation?
Ordinary generation returns content for a user or another component, while tool calling returns a structured request to invoke a named function.
Answer
Ordinary generation returns content for a user or another component, while tool calling returns a structured request to invoke a named function. The request is not itself proof that the operation occurred. The application executes the tool and feeds the result back to the model or workflow.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q63Tool Calling and Agent Design
What makes a good tool schema?
A good tool schema uses a clear name, concise description, typed parameters, required fields, enums or bounds where appropriate, and a small scope.
Answer
A good tool schema uses a clear name, concise description, typed parameters, required fields, enums or bounds where appropriate, and a small scope. Avoid ambiguous parameters and tools that combine unrelated side effects. Validate again at runtime because model-produced arguments can still be invalid or malicious.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q64Tool Calling and Agent Design
When should an agent ask for human approval?
Human approval is appropriate for consequential, irreversible, high-cost, privacy-sensitive, or externally visible actions.
Answer
Human approval is appropriate for consequential, irreversible, high-cost, privacy-sensitive, or externally visible actions. Show the proposed action and relevant inputs before execution, then verify the approval applies to that exact operation. Do not let a model bypass approval by changing tool arguments after the user confirms.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q65Tool Calling and Agent Design
How do you stop an agent from calling tools indefinitely?
Set a maximum tool-call count or wall-clock budget, detect repeated identical calls, and provide clear stop and escalation conditions.
Answer
Set a maximum tool-call count or wall-clock budget, detect repeated identical calls, and provide clear stop and escalation conditions. Bound retries and avoid returning tool errors as if they were successful results. Log each tool call with its purpose, duration, and outcome.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q81LLM Evaluation and Testing
What is an LLM evaluation dataset?
An evaluation dataset contains representative inputs, expected outcomes or grading criteria, and metadata needed to measure application behavior.
Answer
An evaluation dataset contains representative inputs, expected outcomes or grading criteria, and metadata needed to measure application behavior. It should include common cases, edge cases, adversarial prompts, and known failure examples. Keep a held-out set where possible and version datasets with prompts and model configurations.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q82LLM Evaluation and Testing
What is a golden test set?
A golden test set is a curated set of inputs and expected answers or rubric judgments used to detect regressions.
Answer
A golden test set is a curated set of inputs and expected answers or rubric judgments used to detect regressions. It provides repeatable comparisons across prompts, models, retrieval settings, and code changes. Avoid overfitting to the exact examples and supplement automated scoring with targeted human review.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q83LLM Evaluation and Testing
How do you evaluate RAG faithfulness?
Faithfulness evaluation checks whether claims in the generated answer are supported by the retrieved context.
Answer
Faithfulness evaluation checks whether claims in the generated answer are supported by the retrieved context. It can use human annotation, rule-based citation checks, or a separate judge model, but judge scores are imperfect. Inspect unsupported claims and missing evidence, and evaluate retrieval relevance separately from generation.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q84LLM Evaluation and Testing
What is pairwise evaluation?
Pairwise evaluation compares two candidate outputs for the same input and asks a human or judge model which better satisfies a rubric.
Answer
Pairwise evaluation compares two candidate outputs for the same input and asks a human or judge model which better satisfies a rubric. It can be more reliable than assigning absolute scores when criteria are subjective. Randomize candidate order, define tie handling, and validate judge preferences against human labels.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q85LLM Evaluation and Testing
How do you test non-deterministic model outputs?
Use semantic rubrics, structural assertions, bounded numeric tolerances, and repeated trials rather than requiring exact string matches for every task.
Answer
Use semantic rubrics, structural assertions, bounded numeric tolerances, and repeated trials rather than requiring exact string matches for every task. Keep deterministic checks for schemas and business invariants. Track distributions across runs so occasional failures and regressions are visible.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q86LLM Observability and Tracing
What should be logged for an LLM request?
Useful telemetry includes request ID, model and prompt version, latency, token counts, retrieval sources, tool names, outcome, and error category.
Answer
Useful telemetry includes request ID, model and prompt version, latency, token counts, retrieval sources, tool names, outcome, and error category. Minimize or redact user content and secrets, apply retention controls, and restrict access to traces. Consistent metadata helps diagnose quality, cost, and reliability changes.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q87LLM Observability and Tracing
What is a trace in an AI application?
A trace represents one end-to-end operation and its nested steps, such as retrieval, model calls, tool execution, and validation.
Answer
A trace represents one end-to-end operation and its nested steps, such as retrieval, model calls, tool execution, and validation. Spans reveal which stage caused latency or failure. Propagate correlation IDs across services and ensure retries are distinguishable from independent user requests.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q88LLM Observability and Tracing
How do you monitor hallucination risk?
No single metric directly detects all hallucinations.
Answer
No single metric directly detects all hallucinations. Combine citation coverage, retrieval quality, faithfulness checks, user feedback, sampled human review, and domain-specific validators. Set thresholds for abstention or escalation in high-risk workflows and monitor changes by model, prompt version, and query category.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q89LLM Observability and Tracing
How do you track LLM costs?
Track input and output tokens, model prices, retries, embedding calls, reranking, and background ingestion by feature or tenant.
Answer
Track input and output tokens, model prices, retries, embedding calls, reranking, and background ingestion by feature or tenant. Cost dashboards should distinguish successful work from waste caused by retries or oversized context. Add budgets, caching, context trimming, and model routing where quality remains acceptable.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q90LLM Observability and Tracing
How do you debug a bad AI answer?
Inspect the full trace: user input, prompt version, retrieval candidates, context assembly, tool calls, model response, and validation.
Answer
Inspect the full trace: user input, prompt version, retrieval candidates, context assembly, tool calls, model response, and validation. Determine whether the issue came from missing data, irrelevant retrieval, ambiguous instructions, tool failure, or generation. Turn reproducible failures into evaluation cases.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q96Streaming and User Experience
What is token streaming?
Token streaming sends partial model output to the client as it is generated, reducing perceived waiting time.
Answer
Token streaming sends partial model output to the client as it is generated, reducing perceived waiting time. It complicates cancellation, moderation, error reporting, and partial-response handling. Design the UI to distinguish completed answers from interrupted streams and do not execute actions based on incomplete text.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q97Streaming and User Experience
How should a streaming API be designed?
A streaming endpoint commonly emits typed events for text deltas, tool status, citations, errors, and completion.
Answer
A streaming endpoint commonly emits typed events for text deltas, tool status, citations, errors, and completion. Include request IDs and an explicit terminal event so clients can detect interruption. Apply backpressure and cancellation, and ensure server resources are cleaned up when a client disconnects.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q98Streaming and User Experience
How do you handle cancellation?
Propagate cancellation from the client to model requests, retrieval, and tools wherever supported.
Answer
Propagate cancellation from the client to model requests, retrieval, and tools wherever supported. Stop expensive work when the user leaves, but account for operations that have already caused side effects. Use timeouts and cleanup handlers and record whether a request completed, failed, or was cancelled.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q99Streaming and User Experience
How should tool activity be shown to users?
Show clear status such as searching documents or checking an order without exposing secrets or internal implementation details.
Answer
Show clear status such as searching documents or checking an order without exposing secrets or internal implementation details. Distinguish a proposed action from an executed action and display confirmation requests before consequential changes. Report tool failures honestly instead of presenting a fabricated successful result.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q100Streaming and User Experience
How do you handle partial model output errors?
If a stream fails after partial text, mark the response as incomplete and offer a safe retry or continuation path.
Answer
If a stream fails after partial text, mark the response as incomplete and offer a safe retry or continuation path. Do not silently treat partial JSON or unfinished instructions as complete. For structured outputs, buffer and validate the final payload before performing downstream actions.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q101Human-in-the-Loop Workflows
What is human-in-the-loop AI?
Human-in-the-loop AI inserts review or approval into a workflow where model output is uncertain or the action is consequential.
Answer
Human-in-the-loop AI inserts review or approval into a workflow where model output is uncertain or the action is consequential. The system should present the evidence, proposed action, and relevant risks so the reviewer can make an informed decision. Track review outcomes to improve prompts, policies, and evaluations.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q102Human-in-the-Loop Workflows
How do you implement approval before a tool call?
Represent the proposed action as a typed request, show its parameters and consequences to the user, and execute only after a server-verified approval token authorizes that exact request.
Answer
Represent the proposed action as a typed request, show its parameters and consequences to the user, and execute only after a server-verified approval token authorizes that exact request. Bind approval to the request hash and expiration time so changed arguments cannot reuse the approval.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q103Human-in-the-Loop Workflows
How do you support reviewer feedback?
Store reviewer corrections with appropriate access controls and use them to refine evaluation datasets, rules, and prompts.
Answer
Store reviewer corrections with appropriate access controls and use them to refine evaluation datasets, rules, and prompts. Do not automatically treat every correction as high-quality training data. Track disagreement and review patterns to identify ambiguous policies or systematic model errors.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q104Human-in-the-Loop Workflows
When should an AI workflow escalate to a human?
Escalate when evidence is insufficient, confidence signals fall below a validated threshold, policy requires approval, repeated tool failures occur, or the request is outside the supported domain.
Answer
Escalate when evidence is insufficient, confidence signals fall below a validated threshold, policy requires approval, repeated tool failures occur, or the request is outside the supported domain. Explain what is missing and provide the trace or evidence needed for review. Avoid presenting uncalibrated model self-confidence as a reliable probability.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q105Human-in-the-Loop Workflows
How do you make human approval auditable?
Record who approved, what exact action and parameters were approved, when approval occurred, and the outcome of execution.
Answer
Record who approved, what exact action and parameters were approved, when approval occurred, and the outcome of execution. Protect the audit trail from unauthorized changes and avoid storing unnecessary sensitive content. Make approval records searchable for incident response and compliance review.
Syntax
Safe tool execution:
```ts
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
const result = await tool.execute(request.arguments);
```
Diagram: User request -> Model proposes tool -> Schema validation -> Authorization/approval -> Execute -> Result
Example
type ToolRequest = { name: string; arguments: Record<string, unknown> };
async function executeSafely(request: ToolRequest, userId: string) {
const tool = approvedTools.get(request.name);
if (!tool) throw new Error("Tool is not allowed");
validateToolArguments(tool.schema, request.arguments);
await authorize(userId, tool.permission, request.arguments);
if (tool.requiresApproval) await requireApproval(userId, request);
return tool.execute(request.arguments);
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q106Multimodal and Document AI
What is multimodal LLM input?
Multimodal input combines text with content such as images, audio, or video, depending on the model's capabilities.
Answer
Multimodal input combines text with content such as images, audio, or video, depending on the model's capabilities. The application must handle file validation, size limits, privacy, and unsupported formats. Model interpretation can be uncertain, so verify critical extracted facts against authoritative sources where possible.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q107Multimodal and Document AI
How do you extract information from invoices with AI?
An invoice workflow can combine OCR or multimodal extraction with a structured schema for vendor, invoice number, dates, totals, and line items.
Answer
An invoice workflow can combine OCR or multimodal extraction with a structured schema for vendor, invoice number, dates, totals, and line items. Validate arithmetic, vendor identity, duplicate invoices, and required fields against business systems. Route low-quality scans or high-value payments to human review.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q108Multimodal and Document AI
How should document citations be preserved?
Preserve document IDs, page numbers, section headings, and character or chunk offsets during ingestion.
Answer
Preserve document IDs, page numbers, section headings, and character or chunk offsets during ingestion. When answering, map retrieved chunks back to stable source locations and verify citations refer to evidence supporting the claim. Avoid fabricating page numbers from model-generated text.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q109Multimodal and Document AI
How do you handle OCR uncertainty?
Retain OCR confidence or extraction warnings where available, validate fields using domain constraints, and ask for confirmation when uncertainty affects an important decision.
Answer
Retain OCR confidence or extraction warnings where available, validate fields using domain constraints, and ask for confirmation when uncertainty affects an important decision. Test with scans, skewed pages, handwriting, and unusual layouts. Do not convert low-quality OCR into authoritative data without checks.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q110Multimodal and Document AI
How do you protect uploaded documents?
Validate file type and size, scan where appropriate, store files with least-privilege access, and enforce tenant-level authorization.
Answer
Validate file type and size, scan where appropriate, store files with least-privilege access, and enforce tenant-level authorization. Treat embedded text and metadata as untrusted, including prompt-injection attempts. Define retention and deletion behavior for originals, extracted text, embeddings, and generated outputs.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q121AI Governance and Responsible Use
What is a model card?
A model card documents a model's intended uses, limitations, evaluation results, and relevant risk considerations.
Answer
A model card documents a model's intended uses, limitations, evaluation results, and relevant risk considerations. It helps teams understand where a model is suitable and where extra safeguards are required. Keep documentation aligned with the deployed version and the actual application context.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q122AI Governance and Responsible Use
How should AI-generated content be disclosed?
Disclosure should match the product context, user expectations, and applicable policy or law.
Answer
Disclosure should match the product context, user expectations, and applicable policy or law. Make clear when content is generated or materially transformed by AI where that information affects user understanding. Do not use disclosure as a substitute for accuracy checks or accountability.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q123AI Governance and Responsible Use
What is bias evaluation in AI applications?
Bias evaluation checks whether a system's outputs or error rates differ unfairly across relevant groups or use cases.
Answer
Bias evaluation checks whether a system's outputs or error rates differ unfairly across relevant groups or use cases. Define measurable criteria with domain experts, use representative test data, and investigate differences before deployment. Aggregate metrics can hide subgroup failures, so inspect examples and impacts as well.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q124AI Governance and Responsible Use
How do you govern third-party AI services?
Governance should cover data handling, retention, model training use, residency, security, availability, and contractual commitments.
Answer
Governance should cover data handling, retention, model training use, residency, security, availability, and contractual commitments. Review provider changes and maintain a plan for outages or policy changes. Send only the minimum data needed and ensure the service's terms fit the application's obligations.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q125AI Governance and Responsible Use
How do you manage AI feature rollout?
Roll out AI features behind feature flags, start with internal or limited cohorts, and define quality, safety, latency, and cost guardrails.
Answer
Roll out AI features behind feature flags, start with internal or limited cohorts, and define quality, safety, latency, and cost guardrails. Monitor real usage and provide a rollback path. Increase exposure only when evaluation and production evidence support the change.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q126Memory and Conversation State
What is conversation memory in an AI application?
Conversation memory is the selected state from prior turns made available to later model calls.
Answer
Conversation memory is the selected state from prior turns made available to later model calls. It may include recent messages, summaries, user preferences, or task state. Store only what is necessary, provide controls for correction and deletion, and avoid assuming all prior conversation is accurate or relevant.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q127Memory and Conversation State
How should long conversations be summarized?
Summarize older turns into compact, task-relevant facts while preserving important decisions, constraints, unresolved questions, and source references.
Answer
Summarize older turns into compact, task-relevant facts while preserving important decisions, constraints, unresolved questions, and source references. Keep recent turns separately when exact wording matters. Evaluate summary drift and allow the system to retrieve original messages when precision is required.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q128Memory and Conversation State
What is the difference between short-term and long-term memory?
Short-term memory supports the current conversation or workflow, while long-term memory persists selected information across sessions.
Answer
Short-term memory supports the current conversation or workflow, while long-term memory persists selected information across sessions. Long-term memory needs stronger consent, retention, access control, and deletion behavior. Both should be scoped to the user and task, not treated as unrestricted truth.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q129Memory and Conversation State
How do you prevent memory poisoning?
Validate the provenance of remembered facts, distinguish user-stated facts from model inferences, and avoid automatically saving arbitrary instructions from retrieved content.
Answer
Validate the provenance of remembered facts, distinguish user-stated facts from model inferences, and avoid automatically saving arbitrary instructions from retrieved content. Allow users to inspect and correct persistent information. Do not let memory override authorization or system safety rules.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q130Memory and Conversation State
How do you retrieve relevant memories?
Retrieve memory using explicit metadata and relevance criteria, then apply user and task scope before including it in the prompt.
Answer
Retrieve memory using explicit metadata and relevance criteria, then apply user and task scope before including it in the prompt. Avoid stuffing all stored memory into every request. Track when memory helped or harmed the response and provide a fallback when no relevant memory is found.
Syntax
Application boundary:
```ts
const result = await aiService.run<ExpectedShape>(input);
validateSchema(result.value);
validateBusinessRules(result.value);
return result;
```
Diagram: Client -> Backend -> Retrieval/tools -> Model -> Validation -> Response
Example
type AIResult<T> = {
value: T;
model: string;
promptVersion: string;
requestId: string;
};
const result = await aiService.run<ExpectedShape>(input);
validateBusinessRules(result.value);
return result;
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q136Embeddings Model Lifecycle
How do you migrate to a new embedding model?
Build a new index or versioned vector field using the new model rather than mixing incompatible vector spaces.
Answer
Build a new index or versioned vector field using the new model rather than mixing incompatible vector spaces. Re-embed a representative corpus, compare retrieval quality and latency, then switch traffic with a rollback path. Keep source IDs stable so old and new indexes can be reconciled.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q137Embeddings Model Lifecycle
Why must query and document embeddings be compatible?
Vector similarity assumes the query and documents are represented in a compatible embedding space and dimension.
Answer
Vector similarity assumes the query and documents are represented in a compatible embedding space and dimension. Using mismatched models can produce meaningless rankings even if the vectors have the same length. Record model identity and preprocessing version with each indexed representation.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q138Embeddings Model Lifecycle
What is embedding drift?
Embedding drift occurs when model or preprocessing changes alter vector representations and retrieval behavior over time.
Answer
Embedding drift occurs when model or preprocessing changes alter vector representations and retrieval behavior over time. It can arise from model upgrades, normalization changes, or source distribution shifts. Track index versions and retrieval evaluations and rebuild when compatibility or quality is no longer acceptable.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q139Embeddings Model Lifecycle
How should multilingual RAG be evaluated?
Use queries and source documents across the languages, scripts, and translation patterns the product supports.
Answer
Use queries and source documents across the languages, scripts, and translation patterns the product supports. Measure retrieval and answer quality separately by language and domain. Do not assume cross-lingual embeddings perform equally for every language, especially on technical terms and named entities.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.
Q140Embeddings Model Lifecycle
How do you choose an embedding model?
Compare semantic retrieval quality, language coverage, vector dimensions, latency, cost, deployment constraints, and data governance requirements on representative queries.
Answer
Compare semantic retrieval quality, language coverage, vector dimensions, latency, cost, deployment constraints, and data governance requirements on representative queries. Test exact identifiers and domain terminology as well as paraphrases. Select based on measured end-to-end answer quality, not benchmark rankings alone.
Syntax
RAG retrieval pattern:
```ts
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const answer = await llm.invoke({ question, context: passages, requireCitations: true });
```
Diagram: Documents -> Parse/chunk -> Embed/index -> Query -> Retrieve/rerank -> LLM -> Answer + citations
Example
async function answerWithRag(question: string) {
const queryVector = await embed(question);
const candidates = await vectorStore.search(queryVector, { topK: 20 });
const passages = await rerank(question, candidates);
const context = passages.slice(0, 5).map(p => p.text).join("\n\n");
return llm.invoke({ question, context, requireCitations: true });
}
Key Points
- Validate model output and tool arguments in application code.
- Treat user input and retrieved content as untrusted.
- Measure quality, latency, token usage, and failures in production.