How to Build a Conversational AI Assistant
Build a chat assistant step by step: conversation history, system prompts, streaming, tools, memory across sessions, guardrails, evals and a chat UI.
A chat assistant looks simple: a text box, a reply that types itself out, a bot that remembers what you said two messages ago. Each of those behaviours is something your code does on purpose. This guide covers the parts in build order, from conversation history to testing whole dialogues. The examples use the Claude API, Streamlit for the interface and NVIDIA NeMo Guardrails as an optional safety layer, with API details taken from the vendors’ documentation.
Conversation state is your job
The Claude Messages API keeps no session for you. Each call must carry the full list of prior user and assistant turns. A side benefit: the assistant turns you send do not have to be ones the model wrote, so you can seed a conversation with a sample exchange. There is also a beta called message threads that stores the conversation server-side so later requests only carry new messages, but a thread lapses five minutes after its last request, so plan on owning the history anyway.
History has a cost. Everything in the request counts against the context window: the system prompt, every message including tool results and documents, and the tool definitions themselves. Current models, including Claude Haiku 5.5, Claude Sonnet 5.5 and Claude Opus 5.5, accept up to 1M tokens, but Anthropic warns that a bigger context is not automatically better, because accuracy and recall fall off as the token count climbs. If the input alone is larger than the window, the API rejects the request with a 400 “prompt is too long” error. For long-running chats, Anthropic offers server-side compaction (in beta for Claude 4.6 and later models), which summarises older turns so the conversation can keep going, and context editing for finer control.
Write a system prompt with a role
Put the assistant’s role in the system parameter. Anthropic’s prompting guide says even one sentence of role sets tone and focus. Its customer support guide adds that most of the rest, such as reference documents and worked examples, tends to work better inside the first user turn than in the system prompt.
Three habits from the prompting guide pay off in chat:
- Explain the reason behind a rule. Instead of a bare “never use ellipses”, say the text will be read by a text-to-speech engine. The model can then apply the idea to cases you did not list.
- Show, don’t only tell. Three to five example exchanges, wrapped in
<example>tags, are one of the most dependable ways to fix tone, format and length. - Separate content with XML tags such as
<instructions>and<context>so policy text, documents and user input do not blur together.
A streaming multi-turn loop
Users notice latency in chat, so stream the reply. The Python SDK’s messages.stream() helper exposes a text_stream iterator, and get_final_message() gives you the assembled message object once the stream ends. The loop below keeps history, streams each answer to the terminal and checks the stop reason before saving the turn.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
SYSTEM = "You are the help assistant for Acme's invoicing app. Answer briefly."
history = []
while True:
user_text = input("\nyou> ").strip()
if user_text in ("", "quit"):
break
history.append({"role": "user", "content": user_text})
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=1024,
system=SYSTEM,
messages=history,
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
reply = stream.get_final_message()
if reply.stop_reason == "refusal":
history.pop() # our choice: drop the declined turn and hand off
print("\n[Passing you to a member of the team.]")
continue
history.append({"role": "assistant", "content": reply.content})
Claude Sonnet 5.5 is a reasonable default here: Anthropic’s model overview pitches it as the best mix of speed and intelligence, with Claude Haiku 5.5 aimed at high-volume, latency-sensitive work. If you parse the raw event stream yourself, expect ping events, possible error events (a mid-stream overloaded_error is the streaming form of an HTTP 529), and new event types in future, which your parser should skip rather than crash on.
Let the assistant act through tools
With tool use, you describe functions and Claude decides whether to call one based on the user’s message and each tool’s description. For your own (client) tools, the response ends with stop_reason: "tool_use" and one or more tool_use blocks; your code runs the function and sends the output back in a tool_result block on the next request. Server tools such as web_search run on Anthropic’s side and need no round trip from you.
When streaming, tool arguments arrive as input_json_delta events holding fragments of JSON. Collect them and parse once the block’s content_block_stop arrives, or let the SDK’s streaming helpers do it.
Memory that outlasts the session
For facts worth keeping, such as a user’s preferences or the state of an open case, Anthropic’s memory tool gives Claude a directory of files it can view, create and edit across conversations. You enable it with a single entry, {"type": "memory_20250818", "name": "memory"}, and implement the commands yourself, because the tool is client-side: Claude only requests the operation, and your handler maps the /memories prefix onto real storage like a per-user folder or database keys.
Two cautions from the docs. Your handler must refuse any path outside /memories, since a crafted path could otherwise reach other files. And while Claude usually declines to store sensitive data, Anthropic recommends adding your own filter that strips it before anything is written, plus caps on file size.
Guardrails, refusals and escalation
Anthropic’s jailbreak guide describes layered defences:
- Screen input cheaply. Send the user’s message to a light model such as Claude Haiku 5.5 with structured outputs constraining the answer to a boolean like
is_harmful. If that screening call returnsstop_reason: "refusal", count it as harmful. - Tell the model how to refuse. Spell out the boundaries in the system prompt along with the exact wording to use when a request crosses them.
- Keep untrusted text in tool results. Web pages, emails and file contents belong in
tool_resultblocks, labelled with their source, and your system prompt should say such content can never override instructions. - Act on repeat offenders. Users who keep triggering the same refusal can be warned, throttled or banned.
Refusals from the main model are visible in the response: stop_reason is "refusal", with a stop_details object naming the policy category. That is the natural trigger for escalating to a person, as in the loop above. Anthropic’s support guide treats escalation as something to measure, tracking conversations that were correctly passed to a human against those that should have been and were not.
If you want rules outside the prompt, NeMo Guardrails is NVIDIA’s open-source toolkit for exactly this. It runs on Python 3.11 to 3.13 (pip install nemoguardrails) and sits between your code and the model. Its README lists five rail types: input rails that can reject or rewrite user input, dialog rails that steer the flow, retrieval rails that filter RAG chunks, execution rails around tool calls, and output rails that can block or edit a reply before the user sees it. You load a config folder into an LLMRails object and call generate with a messages list shaped like the OpenAI Chat Completions format.
Test whole conversations, not single replies
Anthropic’s eval guide gives a checklist of criteria that matter for chat: consistency across similar questions, relevance, tone, privacy handling, latency, cost and context utilization, meaning how well the model builds on earlier turns. Its worked example for a conversation assistant uses 100 multi-turn conversations whose final question only makes sense with the history, graded by a model on a 1 to 5 scale.
The guide’s other advice translates directly:
- Mirror real traffic, and deliberately include bad, harmful or off-topic user input, overly long messages and ambiguous cases.
- Prefer automated grading: exact or string match where possible, LLM grading where judgment is needed. Many slightly noisy automated cases beat a few hand-graded ones.
- Give an LLM grader a precise rubric, ask for a fixed output such as “correct”/“incorrect” or a 1 to 5 score, and let it think before scoring.
Add your escalation and refusal cases to the same test set so a prompt change cannot quietly break them. Our LLM evaluation metrics guide covers scoring methods in more depth, and the support reply drafting walkthrough shows a full grading loop for one use case.
Put a chat UI on it
Streamlit has purpose-built chat elements. st.chat_message("user") or st.chat_message("assistant") opens a styled message container that can hold any element, and st.chat_input draws the input box, returning None until the user sends something. The official tutorial keeps the history in st.session_state.messages and redraws it at the top of the script, so earlier messages survive each app rerun. For the reply, st.write_stream takes a generator or stream, prints it with a typewriter effect and returns the full text, so you can pass it stream.text_stream from the loop above and append the result to history. Our Streamlit AI app guide covers deployment.
If you would rather not build the front end at all, self-hosted interfaces exist. LibreChat describes itself as a self-hosted platform that brings many AI providers into one interface, and Open WebUI is a self-hosted platform that can run offline with local models through Ollama or with OpenAI-compatible APIs. You can browse more in our chat interfaces category.
What to build first
Start with the streaming loop and a short system prompt, then write a few dozen test conversations. Tools, memory and an external guardrail layer each add a failure mode, so add them one at a time and rerun the tests after each.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.