Prepare for technical interviews with questions by technology, clear explanations, step-by-step solutions and code you can run.
It's AI that creates new content, like text, images, code, audio or video, instead of only labeling or predicting from existing data. It learns patterns from huge amounts of data and produces new output that follows them.
A discriminative model separates things, like "spam or not spam". A generative model learns how the data itself looks, so it can produce new examples.
A very large neural network trained on lots of text to predict the next token. That one skill, done at scale, lets it write, summarize, translate, answer questions and write code.
A piece of text the model reads, which can be a word, part of a word or punctuation. Models have token limits, and pricing is usually per token. Roughly, 1,000 tokens is about 750 English words.
The design behind modern LLMs. Its key idea is self-attention, which lets every token look at every other token to understand context. It also processes tokens in parallel, so it trains faster than older RNNs.
For each token, the model works out how much attention to pay to every other token in the sentence. In "The dog chased the cat because it was hungry," attention helps decide what "it" refers to.
Lists of numbers that capture the meaning of text. Similar meanings land close together, so I can search by meaning instead of exact words.
The maximum amount of text, input plus output, that the model can handle in one request. If a conversation is longer, I need to trim, summarize or retrieve only the useful parts.
Pre-training teaches general language ability from a huge dataset, and it's very expensive. Fine-tuning adjusts an existing model on a smaller dataset for a specific task or style.
Reinforcement Learning from Human Feedback. People rank model answers, a reward signal is learned from those rankings, and the model is tuned to give answers people prefer. It's a big reason chat models feel helpful.
It controls randomness. A low value gives focused, repeatable answers, and a higher value gives more varied, creative ones. For facts and code I use low values.
Both limit which tokens the model can pick from. Top-k keeps only the k most likely tokens. Top-p keeps the smallest group of tokens whose probabilities add up to p. They help balance quality and variety.
Writing instructions so the model gives the output I want. Being clear about the role, task, format and constraints, and giving examples, makes a big difference.
Zero-shot gives only the task. Few-shot adds a few examples. Chain-of-thought asks the model to work through the steps before answering, which helps with reasoning problems.
Standing instructions that set the model's role, tone and rules for the whole conversation, before the user says anything.
When the model states something false with confidence. I reduce it with RAG so it answers from real documents, by asking it to say "I don't know," lowering temperature, requiring sources and verifying important facts.
Retrieval-Augmented Generation. I search my own documents for the passages that matter and put them in the prompt, so the model answers from current, specific data without retraining.
RAG is best when knowledge changes or must be traceable to sources. Fine-tuning is best for changing style, format or behavior. Many systems use RAG first because it's cheaper and easier to update.
A database built to store embeddings and find the nearest ones to a query quickly. Examples are Pinecone, Chroma, Weaviate and pgvector.
Splitting documents into smaller pieces before embedding. Chunks that are too big give vague matches, and too small lose context. A few hundred tokens with a small overlap is a common start.
An agent uses the model to decide steps, call tools like search or a database, read the results and continue until the task is done. Tool use means the model returns a structured request, and my code runs the tool.
Hidden instructions inside content the model reads, like a web page saying "ignore your rules." I reduce the risk by treating outside content as data, limiting tool permissions, filtering output and asking for confirmation before risky actions.
With a test set of questions and expected answers, plus checks for accuracy, faithfulness to sources, safety, speed and cost. I also use human review and sometimes another model as a judge, while remembering that judges have biases too.
They start with random noise and remove it step by step, guided by a text prompt, until an image appears. They learned this by training on images with noise gradually added.
Hallucinations, bias from training data, privacy leaks, copyright questions, misuse like deepfakes and scams, and over-trusting outputs. Good practice is human review for important decisions, protecting personal data, being transparent about AI use and testing for harmful output.
Use anthropic SDK or OpenAI API client to invoke model completions.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-sonnet-4-5" # placeholder: use a model available to you
def ask(prompt, system="You are a helpful assistant."):
r = client.messages.create(
model=MODEL, max_tokens=500, system=system,
messages=[{"role": "user", "content": prompt}],
)
return r.content[0].text
print(ask("Explain an API in two lines."))
Configure system prompt for persona and set low temperature for focused response.
r = client.messages.create(
model=MODEL, max_tokens=300, temperature=0.2,
system="You are a teacher. Explain with one simple analogy, max 3 lines.",
messages=[{"role": "user", "content": "What is recursion?"}],
)
print(r.content[0].text)
Use messages.stream context manager and flush text pieces in real time.
with client.messages.stream(
model=MODEL, max_tokens=300,
messages=[{"role": "user", "content": "Write a short story about a robot."}],
) as stream:
for piece in stream.text_stream:
print(piece, end="", flush=True)
Append user and assistant turns to a persistent history list.
history = []
def chat(user_text):
history.append({"role": "user", "content": user_text})
r = client.messages.create(model=MODEL, max_tokens=400, messages=history)
reply = r.content[0].text
history.append({"role": "assistant", "content": reply})
return reply
while True:
text = input("You: ")
if text.lower() in {"quit", "exit"}:
break
print("Bot:", chat(text))
Provide input-output demonstrations in the prompt to condition the model output.
prompt = """Classify the review as Positive, Negative or Neutral.
Review: "Loved the battery life!" -> Positive
Review: "Stopped working after two days." -> Negative
Review: "It arrived on Tuesday." -> Neutral
Review: "The screen is gorgeous but the speaker is weak." ->"""
print(ask(prompt, system="Reply with one word only."))
Request JSON schema formatting and wrap json.loads in a try-except block.
import json
raw = ask(
"Extract name, city and age from: 'Ravi, 27, lives in Pune.' "
"Reply with JSON only, using keys name, city, age."
)
try:
data = json.loads(raw)
except json.JSONDecodeError:
data = None # in real code, retry or repair the output
print(data)
Catch exceptions in a loop and sleep with 2 ** attempt intervals.
import time
def safe_ask(prompt, tries=3):
for attempt in range(tries):
try:
return ask(prompt)
except Exception as e:
print("Error, retrying:", e)
time.sleep(2 ** attempt)
raise RuntimeError("API failed after retries")
Inspect usage attribute on response and apply token rate formula.
r = client.messages.create(
model=MODEL, max_tokens=200,
messages=[{"role": "user", "content": "Hello!"}],
)
inp, out = r.usage.input_tokens, r.usage.output_tokens
PRICE_IN, PRICE_OUT = 3.00, 15.00 # example dollars per million tokens
cost = inp / 1e6 * PRICE_IN + out / 1e6 * PRICE_OUT
print(inp, out, f"${cost:.6f}")
Compute dot product divided by product of vector magnitudes.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb)
print(cosine([1, 2, 3], [1, 2, 4]))
Use sentence-transformers model to compute cosine similarity between query and documents.
# pip install sentence-transformers
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer("all-MiniLM-L6-v2")
docs = ["How to reset my password", "Best pasta recipes", "Change account login details"]
doc_vecs = model.encode(docs)
query_vec = model.encode("I forgot my password")
scores = util.cos_sim(query_vec, doc_vecs)[0]
best = int(scores.argmax())
print(docs[best], float(scores[best]))
Step through text with window size and step increment of size minus overlap.
def chunk_text(text, size=500, overlap=50):
chunks, start = [], 0
while start < len(text):
chunks.append(text[start:start + size])
start += size - overlap
return chunks
Store embeddings in numpy array and rank results using dot product similarity.
import numpy as np
class TinyStore:
def __init__(self, embedder):
self.embedder = embedder
self.texts, self.vecs = [], []
def add(self, texts):
self.texts += texts
self.vecs += list(self.embedder.encode(texts))
def search(self, query, k=3):
q = self.embedder.encode(query)
sims = [float(np.dot(q, v) / (np.linalg.norm(q) * np.linalg.norm(v))) for v in self.vecs]
top = np.argsort(sims)[::-1][:k]
return [(self.texts[i], sims[i]) for i in top]
Embed retrieved context chunks directly into prompt template.
def rag_answer(question, store):
hits = store.search(question, k=3)
context = "\n---\n".join(text for text, _ in hits)
prompt = (
"Answer using only the context below. "
"If the answer is not there, say you don't know.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
return ask(prompt)
Read file, chunk with overlap and index into vector store.
text = open("policy.txt", encoding="utf-8").read()
store = TinyStore(model)
store.add(chunk_text(text, size=500, overlap=50))
print(rag_answer("How many leave days do employees get?", store))
Instantiate PersistentClient and query collection with query_texts.
# pip install chromadb
import chromadb
db = chromadb.PersistentClient(path="./chroma_data")
col = db.get_or_create_collection("notes")
col.add(ids=["1", "2"],
documents=["Refunds take 5 working days.", "We ship across India."])
result = col.query(query_texts=["How long do refunds take?"], n_results=1)
print(result["documents"][0][0])
Number context chunks and instruct model to reference bracketed indexes like [1].
def rag_with_sources(question, store):
hits = store.search(question, k=3)
numbered = "\n".join(f"[{i+1}] {t}" for i, (t, _) in enumerate(hits))
prompt = (
"Answer from the numbered passages only, and cite them like [1].\n\n"
f"{numbered}\n\nQuestion: {question}"
)
return ask(prompt)
Test dataset questions and calculate retrieval hit rate percentage.
tests = [
{"q": "How long do refunds take?", "expect": "5 working days"},
{"q": "Do you ship across India?", "expect": "ship across India"},
]
hits_ok = 0
for t in tests:
results = store.search(t["q"], k=3)
if any(t["expect"] in text for text, _ in results):
hits_ok += 1
print(f"Retrieval hit rate: {hits_ok}/{len(tests)}")
Provide tool schema in API call and handle stop_reason == 'tool_use'.
tools = [{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]},
}]
def get_weather(city):
return f"32C and sunny in {city}"
messages = [{"role": "user", "content": "What's the weather in Delhi?"}]
r = client.messages.create(model=MODEL, max_tokens=400, tools=tools, messages=messages)
if r.stop_reason == "tool_use":
call = next(b for b in r.content if b.type == "tool_use")
messages.append({"role": "assistant", "content": r.content})
messages.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": call.id,
"content": get_weather(**call.input)}]})
final = client.messages.create(model=MODEL, max_tokens=400, tools=tools, messages=messages)
print(final.content[0].text)
Loop through tool calls with max_steps safety boundary.
TOOL_FUNCS = {"get_weather": get_weather}
def run_agent(goal, max_steps=6):
messages = [{"role": "user", "content": goal}]
for _ in range(max_steps):
r = client.messages.create(model=MODEL, max_tokens=600, tools=tools, messages=messages)
if r.stop_reason != "tool_use":
return r.content[0].text
messages.append({"role": "assistant", "content": r.content})
results = []
for b in r.content:
if b.type == "tool_use":
out = TOOL_FUNCS[b.name](**b.input)
results.append({"type": "tool_result", "tool_use_id": b.id, "content": str(out)})
messages.append({"role": "user", "content": results})
return "Stopped: too many steps."
Parse mathematical expressions safely using ast and operator mappings.
import ast, operator as op
OPS = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv}
def calc(expr):
def ev(node):
if isinstance(node, ast.Constant):
return node.value
if isinstance(node, ast.BinOp):
return OPS[type(node.op)](ev(node.left), ev(node.right))
raise ValueError("Not allowed")
return ev(ast.parse(expr, mode="eval").body)
print(calc("12 * (3 + 4)"))
Check blocked keywords and prompt for confirmation before executing external side-effects.
BLOCKED = ["ignore previous instructions", "reveal your system prompt"]
def is_safe(text):
return not any(b in text.lower() for b in BLOCKED)
def send_email(to, body):
ok = input(f"Send email to {to}? (y/n): ").lower() == "y"
return "Sent" if ok else "Cancelled by user"
Map-reduce pattern: chunk document, summarize pieces, and synthesize overall summary.
def summarize_long(text):
parts = chunk_text(text, size=3000, overlap=200)
mini = [ask(f"Summarize in 3 lines:\n{p}") for p in parts]
return ask("Combine these into one short summary:\n" + "\n".join(mini))
Use st.session_state, st.chat_message, and st.chat_input to render conversational UI.
# pip install streamlit | run with: streamlit run app.py
import streamlit as st
st.title("My Chatbot")
if "msgs" not in st.session_state:
st.session_state.msgs = []
for m in st.session_state.msgs:
st.chat_message(m["role"]).write(m["content"])
if text := st.chat_input("Ask something"):
st.session_state.msgs.append({"role": "user", "content": text})
r = client.messages.create(model=MODEL, max_tokens=400, messages=st.session_state.msgs)
reply = r.content[0].text
st.session_state.msgs.append({"role": "assistant", "content": reply})
st.rerun()
Expose POST route with Pydantic BaseModel for request body validation.
# pip install fastapi uvicorn | run with: uvicorn main:app --reload
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Question(BaseModel):
text: str
@app.post("/ask")
def ask_endpoint(q: Question):
return {"answer": ask(q.text)}
Run assertion loop comparing model output substrings with ground truth keywords.
tests = [
{"q": "What is 2+2? Answer with the number only.", "expected": "4"},
{"q": "Capital of France? One word.", "expected": "paris"},
]
passed = sum(1 for t in tests if t["expected"] in ask(t["q"]).lower())
print(f"{passed}/{len(tests)} passed")
Try searching for keywords like "JWT", "Express", "useEffect", "PDO", "GIL", or "schema".
Connect with DigitalXNode expert interviewers for technical mock interviews, domain assessment, and enterprise job placement.