Q67. How do you call an LLM API from Python?
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Answer only from the context."},
{"role": "user", "content": "What is RAG?"},
],
temperature=0.2,
)
print(resp.choices[0].message.content)The pattern is the same for Anthropic and Gemini SDKs: a client, a model name, a list of messages, and sampling parameters.
Q68. How do you stream tokens?
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Explain embeddings."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)Q69. What are embeddings and how do you generate them?
Fixed-length vectors that place semantically similar text close together. Batch your inputs to reduce latency and cost.
res = client.embeddings.create(model="text-embedding-3-small", input=["cat", "kitten"])
vectors = [d.embedding for d in res.data]Q70. Explain a RAG pipeline end to end.
Ingest: load documents, split into chunks, embed, store in a vector DB. Query: embed the question, retrieve top-k chunks, build a prompt with that context, call the LLM, return the answer with sources. Evaluate retrieval and generation separately.
def answer(question: str, k: int = 4) -> str:
q_vec = embed([question])[0]
chunks = store.search(q_vec, k=k)
context = "\n\n".join(c.text for c in chunks)
prompt = f"Context:\n{context}\n\nQuestion: {question}\nAnswer using only the context."
return llm(prompt)Q71. How do you chunk text? What trade-offs matter?
Small chunks improve retrieval precision but lose context; large chunks keep context but dilute relevance and cost more tokens. Overlap avoids cutting an idea in half. Prefer splitting on structure (paragraphs, headings) over fixed characters.
def chunk(text: str, size: int = 800, overlap: int = 100) -> list[str]:
step = size - overlap
return [text[i:i + size] for i in range(0, max(len(text) - overlap, 1), step)]Q72. How does a vector database search work? Show a minimal FAISS example.
It finds nearest neighbors of the query vector by similarity (cosine, dot product, L2). Large stores use approximate indexes (HNSW, IVF) to trade a little recall for big speed gains.
import faiss, numpy as np
vecs = np.random.rand(1000, 384).astype("float32")
faiss.normalize_L2(vecs) # cosine via inner product
index = faiss.IndexFlatIP(384)
index.add(vecs)
q = vecs[:1].copy()
scores, ids = index.search(q, 5)Q73. How do you get reliable structured output from an LLM?
Prefer the provider's structured output or JSON-schema mode, validate with Pydantic, and retry with the validation error fed back to the model if parsing fails.
def get_structured(prompt: str, retries: int = 2) -> Answer:
for _ in range(retries + 1):
raw = llm(prompt + "\nReturn JSON only.")
try:
return Answer.model_validate_json(raw)
except ValidationError as e:
prompt += f"\nPrevious output was invalid: {e}. Fix it."
raise RuntimeError("no valid output")Q74. How does tool calling (function calling) work?
You describe functions with a JSON schema. The model returns a request to call one with arguments; your code runs it and sends the result back; the model then writes the final answer. An agent is this loop repeated until the model stops asking for tools.
import json
TOOLS = {"get_weather": lambda city: f"28C in {city}"}
def agent_loop(messages, max_steps=5):
for _ in range(max_steps): # always cap the loop
msg = call_llm_with_tools(messages)
if not msg.tool_calls:
return msg.content
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = TOOLS[call.function.name](**args)
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(result)})
return "stopped: max steps reached"Q75. How do you count tokens and control cost?
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
n_tokens = len(enc.encode("some prompt text"))Cap max_tokens, trim or summarize history, cache repeated calls, batch embeddings, and use a smaller model for easy steps.
Q76. How do you evaluate a RAG system?
Evaluate retrieval and generation separately. Retrieval: recall@k, precision@k, MRR. Generation: faithfulness (is the answer supported by the context), answer relevance, and correctness against a labeled set. LLM-as-judge works at scale but must be calibrated against human labels.
def recall_at_k(retrieved: list[str], relevant: set[str], k: int) -> float:
return len(set(retrieved[:k]) & relevant) / len(relevant)
def mrr(retrieved: list[str], relevant: set[str]) -> float:
for rank, doc in enumerate(retrieved, start=1):
if doc in relevant:
return 1 / rank
return 0.0Q77. How do you reduce hallucinations in a RAG app?
Better retrieval (hybrid search, reranking), an instruction to answer only from context and say "I don't know", low temperature, citations of source chunks, and a faithfulness check. Add guardrails against prompt injection in retrieved text.
Q78. What is hybrid search and reranking?
Hybrid search combines keyword (BM25) and vector search, merging scores (for example reciprocal rank fusion). A reranker (cross-encoder) rescoring the top 20-50 results improves precision at extra latency.
def rrf(rank_lists: list[list[str]], k: int = 60) -> list[str]:
scores: dict[str, float] = {}
for ranks in rank_lists:
for pos, doc in enumerate(ranks, start=1):
scores[doc] = scores.get(doc, 0) + 1 / (k + pos)
return sorted(scores, key=scores.get, reverse=True)