TechSchool
Home / Interview questions / AI engineering / OpenAI

OpenAI AI Engineer Interview Questions

Short answers to 31 AI engineering questions asked at OpenAI.

Questions and answers (31)

Answers are written in plain English and reviewed for technical accuracy. Each answer states the point first, then the reason.

1. Design and implement an in-memory key-value store supporting set, transactional begin, commit and abort.

Use a dictionary from key to a stack of values. A transaction keeps a log of old values. Commit clears the log. Abort replays the log in reverse order.

def begin(self): self.log = []
def set(self, k, v):
    self.log.append((k, self.data.get(k)))
    self.data[k] = v
def abort(self):
    for k, old in reversed(self.log):
        if old is None: self.data.pop(k, None)
        else: self.data[k] = old

2. Create a database ORM, step by step.

Start with a table class that maps one Python class to one table. Add a session that tracks objects and flushes changes. Add a query builder last. Keep the mapping layer separate from the SQL strings.

class Session:
    def add(self, obj): self.new.append(obj)
    def flush(self):
        for obj in self.new:
            cols = obj.__table__.columns
            sql = build_insert(obj.__table__, obj)
            self.conn.execute(sql)

3. Code a trivial web crawler using Go.

Use a queue of URLs and a set of visited URLs. Fetch each page and extract links with a simple parser. Stop at a fixed depth or page count.

func crawl(start string, max int) {
    queue := []string{start}
    seen := map[string]bool{start: true}
    for len(queue) > 0 && len(seen) < max {
        u := queue[0]; queue = queue[1:]
        for _, l := range links(fetch(u)) {
            if !seen[l] { seen[l] = true; queue = append(queue, l) }
        }
    }
}

4. Implement a UI from a mockup with provided CSS and API.

Build the page from the mockup in small static pieces first. Match the provided CSS class names exactly. Then wire each element to the API call it needs. Test one component at a time against the real API.

5. Refactor bad code: here are ~120 lines of working but messy code with passing tests. Improve the architecture without breaking them. What do you change first?

Add a test run to a safety net before any edit. Then extract the largest repeated block into one function. Keep each change small and run the tests after each step. Do not mix refactoring with new features.

6. Write a Python function that displays the first n Fibonacci numbers.

Use a loop that keeps the last two values. Print each value as you compute it. This uses constant memory and O(n) time.

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        print(a)
        a, b = b, a + b

7. Infection-spread simulation.

Model each person as a state in a grid or graph. At each step, infect a neighbor with probability p. Repeat for T steps and count the infected. The result depends on p and on the contact graph.

for step in range(T):
    new = set()
    for node in infected:
        for nb in graph[node]:
            if random() < p: new.add(nb)
    infected |= new

8. Compute the KL divergence given different random variables.

KL divergence is the expected log ratio of two distributions. For discrete variables P and Q it is sum over x of P(x) times log(P(x) / Q(x)). The value is zero only when P equals Q. It is not symmetric, so KL(P||Q) differs from KL(Q||P).

import math
def kl(p, q):
    return sum(pi * math.log(pi / qi)
               for pi, qi in zip(p, q) if pi > 0)

9. If the accuracy of a classifier is 1, what is the lower/upper bound on the loss function for a single training example?

Accuracy 1 means every prediction is correct. The cross-entropy loss is then 0 for that example. The lower bound is 0 and the upper bound is 0. A loss above 0 means at least one prediction is wrong.

10. We have two models, 85% and 82% accuracy. Which do you pick?

I do not pick from accuracy alone. I check the class balance, the cost of each error type, and the confidence of the model. A 82% model can win if it is better on the classes that matter. I also check the variance of the score on a held-out set.

11. How do you handle missing data in Pandas?

I first measure how much data is missing and why. I drop rows or columns only when the missing rate is small or the column is useless. Otherwise I fill values with a constant, the mean, or a model-based estimate. I add a missing indicator column when the fact of missingness can carry signal.

df.isna().mean()
df = df.drop(columns=['mostly_empty'])
df['age'] = df['age'].fillna(df['age'].median())
df['age_was_missing'] = df['age'].isna().astype(int)

12. Explain self-attention. What is its computational complexity, and what are your options when contexts get long?

Self-attention lets each token build a weighted sum over all other tokens. The weights come from query-key dot products, scaled and passed through softmax. The cost is O(n^2 * d) time and O(n^2) memory for a context of n tokens. For long contexts I use sliding windows, sparse patterns, or paged attention with a KV cache.

scores = Q @ K.T / sqrt(d)
weights = softmax(scores)
out = weights @ V

13. What is the relationship between cross-entropy, KL divergence and perplexity, and why is cross-entropy the training loss for language models?

Cross-entropy equals KL divergence plus the entropy of the true distribution. Perplexity is the exponential of cross-entropy. The true entropy is constant for a fixed dataset, so minimizing cross-entropy minimizes KL divergence. This is why cross-entropy is the training loss for language models.

H(p, q) = H(p) + KL(p || q)
perplexity = exp(H(p, q))

14. What is the effect of adjusting an LLM's context window size?

A larger context window lets the model read more tokens at once. This helps tasks that need long documents or long dialogues. The tradeoff is cost and speed, because attention cost grows with the square of the length. A KV cache also grows with the length, so memory use rises.

15. You are building a production agent that calls tools (function calling). What makes the loop reliable enough to ship?

The loop needs strict schemas, timeouts, retries, and a hard step limit. Each tool call must be validated before it runs. The agent must log every step and stop on repeated failures. A human approval gate helps for tools that change state.

for step in range(MAX_STEPS):
    call = model.next_tool_call()
    if not valid(call): break
    result = run_with_timeout(call)
    history.append(result)

16. How would you build an LLM-powered enterprise search system?

I split the work into ingest, retrieval, and answer steps. Ingest parses documents and chunks them with the tokenizer. Retrieval uses hybrid search with embeddings and keyword match, then a reranker. The answer step sends the top chunks to the LLM and cites them.

17. Design the serving stack for a ChatGPT-scale consumer assistant: hundreds of millions of weekly users, streaming chat, multiple model tiers.

Use a stateless gateway, a router, and separate model tiers behind a shared KV cache layer. The gateway handles auth and rate limits, and the router sends simple requests to small models. Keep the KV cache and paged attention close to the GPUs to cut cost per token. Measure capacity in FLOPs per request and set per-tier token budgets.

18. Design and build a webhook delivery system that reliably delivers events to customer-registered URLs.

Store each event in a durable queue and retry delivery with exponential backoff. Sign each request with an HMAC so the customer can verify the sender. Keep an idempotency key per event so retries do not create duplicates. After a fixed number of failures, move the event to a dead-letter queue and alert the customer.

19. Design a system to schedule jobs in a distributed environment.

Use a central scheduler that assigns jobs to workers with a lease and a heartbeat. The lease expires if a worker stops sending heartbeats, so another worker can take the job. Store job state in a durable database and make each job idempotent. This design gives at-least-once delivery, so duplicate runs are possible.

20. Design an in-memory database. / Design Slack.

Build the store as a hash map in memory with a write-ahead log for durability and a snapshot for fast restart. Shard keys across nodes and use consistent hashing to move shards when the cluster grows. For a chat product, keep recent messages in memory and persist history to disk. Accept that a node loss can drop the latest writes unless you replicate each shard.

21. A customer says “the model got worse” after you upgraded model versions in their deployment. How do you verify and respond?

Run the old and new model side by side on a fixed eval set and on a sample of the customer traffic. Compare win rate, task success, and refusal rate with the same tokenizer and prompts. If the new model loses, roll back the deployment and share the numbers with the customer. Pin the model version per customer so upgrades are explicit.

22. An enterprise customer reports that responses from your deployed system have gotten slow. Walk me through the diagnosis.

Check latency at each layer: gateway, queue wait, prefill, decode, and network. Compare p50 and p99 against the baseline and look for a rise in prompt length or output tokens. A common cause is a full KV cache that forces request queuing. Report the measured bottleneck and the fix timeline to the customer.

23. How do you approach GenAI safety in consumer products?

Apply layered controls: input filters, model-level policy training, output checks, and human review for high-risk cases. Publish clear usage policies and give users a fast way to report harm. Measure false positive and false negative rates on a labeled safety set. Accept that stricter filters reduce helpfulness, so tune thresholds per product surface.

24. How would you design safeguards for an AI system that can take actions on behalf of a user?

Require explicit user consent, least-privilege scopes, and a confirmation step before any irreversible action. Log every action with the input, the tool call, and the result so you can audit it. Add hard limits on spend and rate, and a kill switch per user and per tool. Test the guardrails with red-team cases before launch.

25. An enterprise customer says: “We want AI to automate our claims processing.” You're the engineer in the room. What do the first two weeks look like?

The first two weeks map the claims process and measure the baseline. I shadow claims staff and collect real documents with labels. I then build a small test set and check if a model can pass it. The goal is a clear go or no-go decision, not a demo.

26. Do you have experience working with APIs? Are you used to working with C-suite executives?

Yes, I have built and maintained production APIs for several years. I also present results to C-suite executives in short, decision-focused reviews. I keep the technical detail in an appendix and lead with cost and risk.

27. What is your favourite product and why?

My favourite product is the plain text editor because it does one job well. It starts fast and never hides my data in a closed format. I use it to draft designs and to store notes in version control.

28. Tell me about a time you made a mistake.

I once shipped a model update without a full regression test. It raised latency for one customer segment by about 40 percent. I added a fixed evaluation set to the release gate. I now treat every release as a change to a shared system.

29. Tell me about a time you had a conflict with someone. How did you resolve it and what did you learn?

A teammate and I disagreed about the launch date for a data pipeline. I asked for a short meeting and we listed our constraints on a shared board. We found that a partial launch met both needs. I learned to separate the position from the underlying need.

30. Tell me about a time you had conflicting priorities with stakeholders and how you secured alignment.

Two stakeholders wanted different features in the same sprint. I wrote a one-page tradeoff table with cost, risk, and delay for each option. I asked both to rank the options in one meeting. We agreed on a split release and I shared the decision in writing.

31. What is the project you are most proud of?

I am most proud of a document search system that cut review time for a legal team. The system used a tokenizer tuned for legal terms and a small reranker. Review time fell from 30 minutes to 8 minutes per document. I value it because we measured the gain with the users.

Related lessons
Ai agent intro Ai agent function calling Agent architecture Ai rag Retrieval augmented generation Vector database