Design a keyword-routed chatbot with registered tools, reply templates and per-session memory

Quick Overview

Implement a chatbot that routes each message to the registered tool with the most case-insensitive keyword matches, fills that tool's reply template, and keeps per-session history. It tests tie-breaking by registration order, single-pass placeholder substitution and careful handling of session state.

Design a keyword-routed chatbot with registered tools, reply templates and per-session memory

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design an agentic chatbot that routes user messages to registered tools and keeps per-session conversation memory. Each tool has a name, a list of keywords and a reply template. The template may contain `{query}` (the current message) and `{last}` (the previous user message in the same session, or an empty string if there is none). When a message arrives, the bot scores every tool by the number of words in the message that match one of its keywords, ignoring case. The tool with the highest positive score wins, and ties go to the tool registered earliest. If no keyword matches, the bot replies `"I don't know how to help with that."`. Both the user message and the reply are appended to that session's history as `"user: <text>"` and `"bot: <text>"`. Implement an `AgentChatbot` class with these methods: - `registerTool(name: str, keywords: List[str], template: str)` registers a tool with its keywords and reply template, or replaces an existing tool with the same name. - `sendMessage(sessionId: str, text: str) -> str` routes the message to the best matching tool, returns its filled template (or the fallback reply), and appends both the message and the reply to the session history. - `getHistory(sessionId: str, k: int) -> List[str]` returns the last `k` history entries of the session, oldest first, each formatted as `user: <text>` or `bot: <text>`. - `clearSession(sessionId: str)` wipes the history of the session, and with it the remembered last user message. In the examples, each operation is called with the argument list at the same position, and the output lists the return value of each call (`null` for the constructor and for methods that return nothing). Example 1: ```text Input: operations = ["AgentChatbot","registerTool","registerTool","sendMessage","sendMessage","sendMessage","getHistory"] arguments = [[],["weather",["rain","weather"],"Weather report for: {query}"],["music",["play","song","rain"],"Now playing ({last})"],["s1","Rain today"],["s1","Play that song"],["s1","Tell me a joke"],["s1",3]] Output: [null,null,null,"Weather report for: Rain today","Now playing (Rain today)","I don't know how to help with that.",["bot: Now playing (Rain today)","user: Tell me a joke","bot: I don't know how to help with that."]] ``` `Rain today` scores 1 for both tools (case does not matter), so `weather` wins the tie as the earlier tool. `Play that song` scores 2 for `music`, whose template inserts the previous user message, and `Tell me a joke` matches nothing. The session now holds six entries, and the last three start with a `bot:` entry. Example 2: ```text Input: operations = ["AgentChatbot","registerTool","registerTool","registerTool","sendMessage","sendMessage","clearSession","sendMessage","getHistory","getHistory"] arguments = [[],["echo",["say"],"You said {query}"],["greet",["hi","hello"],"Hello! Previous message: [{last}]"],["echo",["hi"],"Echo: {query} (before: {last})"],["a","hi {last}"],["a","Hello there"],["a"],["a","hello again"],["a",10],["b",5]] Output: [null,null,null,null,"Echo: hi {last} (before: )","Hello! Previous message: [hi {last}]",null,"Hello! Previous message: []",["user: hello again","bot: Hello! Previous message: []"],[]] ``` Registering `echo` again replaces its keywords with `["hi"]` but keeps its first position, so it wins the tie with `greet` on the word `hi`. The `{last}` the user typed is copied into replies as plain text and never expanded. After `clearSession`, the session has no previous message and only the two newest entries, and session `b` was never used, so its history is empty. ```hint Keeping the tie-break stable Ties depend on registration order, and registering an existing name must not change that order. Pick a structure for the tools that lets you overwrite one in place. ``` ```hint Watch the placeholder filling Check what your fill produces when the user's message itself contains `{last}` or `{query}`. Also check which message `{last}` refers to at the moment you build the reply. ``` ### Constraints & Assumptions - Words in a message are maximal runs of alphanumeric characters. Every word occurrence that equals a tool keyword (ignoring case) adds 1 to that tool's score. - Keywords are non-empty alphanumeric strings. - Re-registering an existing tool name replaces its keywords and template but keeps its original registration order. - Placeholders are substituted in a single pass: text inserted for `{query}` or `{last}` is never expanded again. - `getHistory` on an unknown or cleared session returns an empty list. If `k` exceeds the history length, the whole history is returned. - `0 <= k <= 1000` - At most 10,000 calls in total. ### Clarifying Questions to Ask - Does "alphanumeric" mean ASCII letters and digits only, or any Unicode letter or digit (so that `café` is one word)? - Is a placeholder matched exactly, or should variants such as `{Query}` also be filled? - Sessions are only removed by `clearSession`. Should history be capped or expire, or is unbounded growth acceptable here? - Can two messages for the same session arrive at the same time, or are calls strictly sequential? ### What a Strong Answer Covers - How tools are stored so that the tie-break follows registration order and survives re-registration. - Tokenizing the message and counting case-insensitive keyword matches per word occurrence, with the fallback when no score is positive. - Template filling that never re-expands inserted text, and the right value of `{last}` on a session's first message and after a clear. - Per-session history with the exact entry format, correct handling of `k` (including 0 and values past the end), and a full reset on `clearSession`. - The time and space cost of each method. ### Follow-up Questions - With thousands of registered tools, how would you avoid scoring every tool on every message? - History grows without limit for sessions that are never cleared. How would you bound memory, and what would that change for `{last}`? - How would you swap keyword scoring for a model-based router while keeping the same interface and deterministic tests? - How would you let a tool call an external service (a weather API, say) and handle its timeouts and errors?

Overview: Implement a chatbot that routes each message to the registered tool with the most case-insensitive keyword matches, fills that tool's reply template, and keeps per-session history. It tests tie-breaking by registration order, single-pass placeholder substitution and careful handling of session state.

General logo
General
Nov 24, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design an agentic chatbot that routes user messages to registered tools and keeps per-session conversation memory.

Each tool has a name, a list of keywords and a reply template. The template may contain {query} (the current message) and {last} (the previous user message in the same session, or an empty string if there is none).

When a message arrives, the bot scores every tool by the number of words in the message that match one of its keywords, ignoring case. The tool with the highest positive score wins, and ties go to the tool registered earliest. If no keyword matches, the bot replies "I don't know how to help with that.". Both the user message and the reply are appended to that session's history as "user: <text>" and "bot: <text>".

Implement an AgentChatbot class with these methods:

  • registerTool(name: str, keywords: List[str], template: str) registers a tool with its keywords and reply template, or replaces an existing tool with the same name.
  • sendMessage(sessionId: str, text: str) -> str routes the message to the best matching tool, returns its filled template (or the fallback reply), and appends both the message and the reply to the session history.
  • getHistory(sessionId: str, k: int) -> List[str] returns the last k history entries of the session, oldest first, each formatted as user: <text> or bot: <text> .
  • clearSession(sessionId: str) wipes the history of the session, and with it the remembered last user message.

In the examples, each operation is called with the argument list at the same position, and the output lists the return value of each call (null for the constructor and for methods that return nothing).

Example 1:

Input:
operations = ["AgentChatbot","registerTool","registerTool","sendMessage","sendMessage","sendMessage","getHistory"]
arguments = [[],["weather",["rain","weather"],"Weather report for: {query}"],["music",["play","song","rain"],"Now playing ({last})"],["s1","Rain today"],["s1","Play that song"],["s1","Tell me a joke"],["s1",3]]
Output: [null,null,null,"Weather report for: Rain today","Now playing (Rain today)","I don't know how to help with that.",["bot: Now playing (Rain today)","user: Tell me a joke","bot: I don't know how to help with that."]]

Rain today scores 1 for both tools (case does not matter), so weather wins the tie as the earlier tool. Play that song scores 2 for music, whose template inserts the previous user message, and Tell me a joke matches nothing. The session now holds six entries, and the last three start with a bot: entry.

Example 2:

Input:
operations = ["AgentChatbot","registerTool","registerTool","registerTool","sendMessage","sendMessage","clearSession","sendMessage","getHistory","getHistory"]
arguments = [[],["echo",["say"],"You said {query}"],["greet",["hi","hello"],"Hello! Previous message: [{last}]"],["echo",["hi"],"Echo: {query} (before: {last})"],["a","hi {last}"],["a","Hello there"],["a"],["a","hello again"],["a",10],["b",5]]
Output: [null,null,null,null,"Echo: hi {last} (before: )","Hello! Previous message: [hi {last}]",null,"Hello! Previous message: []",["user: hello again","bot: Hello! Previous message: []"],[]]

Registering echo again replaces its keywords with ["hi"] but keeps its first position, so it wins the tie with greet on the word hi. The {last} the user typed is copied into replies as plain text and never expanded. After clearSession, the session has no previous message and only the two newest entries, and session b was never used, so its history is empty.

Constraints & Assumptions

  • Words in a message are maximal runs of alphanumeric characters. Every word occurrence that equals a tool keyword (ignoring case) adds 1 to that tool's score.
  • Keywords are non-empty alphanumeric strings.
  • Re-registering an existing tool name replaces its keywords and template but keeps its original registration order.
  • Placeholders are substituted in a single pass: text inserted for {query} or {last} is never expanded again.
  • getHistory on an unknown or cleared session returns an empty list. If k exceeds the history length, the whole history is returned.
  • 0 <= k <= 1000
  • At most 10,000 calls in total.

Clarifying Questions to Ask Guidance

  • Does "alphanumeric" mean ASCII letters and digits only, or any Unicode letter or digit (so that café is one word)?
  • Is a placeholder matched exactly, or should variants such as {Query} also be filled?
  • Sessions are only removed by clearSession . Should history be capped or expire, or is unbounded growth acceptable here?
  • Can two messages for the same session arrive at the same time, or are calls strictly sequential?

What a Strong Answer Covers Guidance

  • How tools are stored so that the tie-break follows registration order and survives re-registration.
  • Tokenizing the message and counting case-insensitive keyword matches per word occurrence, with the fallback when no score is positive.
  • Template filling that never re-expands inserted text, and the right value of {last} on a session's first message and after a clear.
  • Per-session history with the exact entry format, correct handling of k (including 0 and values past the end), and a full reset on clearSession .
  • The time and space cost of each method.

Follow-up Questions Guidance

  • With thousands of registered tools, how would you avoid scoring every tool on every message?
  • History grows without limit for sessions that are never cleared. How would you bound memory, and what would that change for {last} ?
  • How would you swap keyword scoring for a model-based router while keeping the same interface and deterministic tests?
  • How would you let a tool call an external service (a weather API, say) and handle its timeouts and errors?