The short answer#
A direct model API call is enough for a chatbot with a clear request-and-response path. Add LangChain when reusable prompts, messages and model integrations make the application easier to maintain; consider LangGraph when you need explicit state, branching or pause-and-resume behaviour. The choice follows the work your application owns.
Start by seeing the whole request#
Imagine a Learning Companion that explains a topic, then answers a follow-up question. Before adding a framework, inspect what reaches the model: stable instructions, the current question and any earlier messages the answer depends on.
Here is an original, small Python example using the standard library. It deliberately uses the chat-completions contract compared in Session 1 of the LangChain & LangGraph workshop. The xAI chat-completions guide now labels that endpoint legacy; evaluate its Responses API for a new xAI integration. The example keeps the course's contract visible so you can inspect the responsibilities around a direct call.
Use Python 3.10 or later with XAI_API_KEY set privately in your shell and XAI_MODEL set to a model identifier your account supports on this endpoint. Save the following as direct_chat.py and run python3 direct_chat.py. No extra package is needed. It makes two model requests using your provider account.
import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
def ask(messages):
payload = {
"model": os.environ["XAI_MODEL"],
"messages": messages,
"stream": False,
}
request = Request(
"https://api.x.ai/v1/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={
"Authorization": "Bearer " + os.environ["XAI_API_KEY"],
"Content-Type": "application/json",
},
method="POST",
)
with urlopen(request, timeout=120) as response:
result = json.load(response)
choice = result["choices"][0]
text = choice["message"].get("content")
if choice.get("finish_reason") != "stop":
raise ValueError("The model did not finish a plain text answer")
if not isinstance(text, str) or not text.strip():
raise ValueError("Expected a non-empty text answer")
return text
messages = [
{"role": "system", "content": "Explain software concepts briefly."},
{"role": "user", "content": "My practice topic is reducers. Explain it."},
]
try:
answer = ask(messages)
print(answer)
messages.append({"role": "assistant", "content": answer})
messages.append({"role": "user", "content": "What topic did I choose?"})
print(ask(messages))
except HTTPError as error:
raise SystemExit(f"Model endpoint returned HTTP {error.code}")
except (URLError, TimeoutError, ValueError, KeyError, IndexError, TypeError):
raise SystemExit("Check configuration, connection and response shape")
The first answer should explain reducers. The second should identify the chosen topic. Wording varies: those are expected behaviours, not promised output strings.
The ask function sends the entire messages value each time. The second request contains the original instructions, the first question, its answer and the follow-up. That is the history this example supplies; the first successful response does not itself give the next request that context. The xAI REST reference describes this endpoint as stateless.
The example accepts only a completed text answer. It has no streaming, tools, automatic retries or durable history. The timeout covers blocking network operations, as described in the Python HTTP library documentation; it is not a deadline for a whole chatbot workflow.
The model call stays small; the application grows#
Suppose the companion must now explain a topic, remember a learner's chosen exercise and answer from course notes. The HTTP request remains recognisable. The decisions around it multiply.
| Responsibility | What the application must decide | A concrete failure to inspect |
|---|---|---|
| Instructions | Which stable behaviour belongs in each request? | A follow-up omits the teaching instructions |
| Conversation history | Which messages belong to this conversation, and which fit? | Another learner's transcript is included |
| Retrieved context | Which permitted passages support the answer? | A source is unrelated or inaccessible to the reader |
| Output validation | What result can the next step safely accept? | A response ends early or lacks a required field |
| Tool execution | Which proposed action may run, with which arguments? | A model suggestion becomes an unauthorised action |
| Failure handling | What can be retried, and what may have already happened? | Retrying an action creates a duplicate |
| Streaming | How are partial output, completion and failure represented? | A disconnected stream appears to be a finished answer |
This table is a design exercise, not a claim that a framework automatically handles each row. For every row your chatbot needs, point to the code and the person who owns it.
For the two-turn example, a local list is understandable. For several users, choose conversation identifiers, storage and access checks before sharing history. For long conversations, choose what to keep in model context. Keeping a transcript and deciding what to send from it are separate jobs.
Add LangChain when the same model-facing work repeats#
LangChain gives you common interfaces for model integrations and conversation messages. Its model documentation covers direct model use as well as tool-calling and structured-output capabilities; its message documentation describes the role, content and metadata carried through a conversation.
Those components become useful when several features keep rebuilding the same prompt assembly, provider calls or response handling. For the Learning Companion, a general explanation and a study-helper response may share configuration and history handling while using different instructions.
Here is the same two-turn exchange through LangChain's xAI integration. In a virtual environment, install it with python3 -m pip install langchain-xai. Keep the same XAI_API_KEY and XAI_MODEL settings. Save this separately as langchain_chat.py and run python3 langchain_chat.py.
import os
from langchain_xai import ChatXAI
model = ChatXAI(
model=os.environ["XAI_MODEL"],
timeout=120,
max_retries=0,
)
def ask(messages):
response = model.invoke(messages)
text = response.content
if response.response_metadata.get("finish_reason") != "stop":
raise ValueError("The model did not finish a plain text answer")
if not isinstance(text, str) or not text.strip():
raise ValueError("Expected a non-empty text answer")
return text
messages = [
{"role": "system", "content": "Explain software concepts briefly."},
{"role": "user", "content": "My practice topic is reducers. Explain it."},
]
answer = ask(messages)
print(answer)
messages.append({"role": "assistant", "content": answer})
messages.append({"role": "user", "content": "What topic did I choose?"})
print(ask(messages))
LangChain now handles the provider request and returns a message object. Your code still supplies history and checks for a completed text answer. Automatic retries are disabled here to keep the comparison with the direct call simple. Connection and configuration errors propagate to the caller; a service needs an error handler around this boundary.
Compare the instructions and questions in both examples: they are the same. The answers may differ between calls. Inspect the outgoing messages and accepted results before and after any further refactor. Keep those checks when you share the prompt and history code across features.
Provider support still differs. A common interface helps organise integrations; check the selected model's supported inputs and outputs when changing providers. Application permissions, data selection and the definition of a correct answer remain your team's decisions.
LangChain also supplies agent helpers. Start with the components your chatbot needs. Evaluate a workflow separately when controlling its route becomes difficult.
Consider LangGraph when the route becomes part of the problem#
Now let the companion choose between explaining a concept and looking up course notes, ask a reviewer to check the answer, and allow one improvement before returning it. You need to explain which path ran, which state each step received and why the work stopped.
LangGraph's overview describes explicit shared state and control flow, mixing ordinary code with model-driven steps. LangGraph can be used without LangChain. It is useful to evaluate when branches, bounded loops, interruptions or recovery are central to the application.
Persistence still needs a storage choice. A checkpointer saves a thread's graph state; an in-memory saver loses those checkpoints when the process restarts. The persistence guide distinguishes that from a persistent backend. Installing a graph library alone does not establish restart recovery.
For a fixed sequence such as validate input → call model → validate answer, ordinary functions can remain clear. For a branching flow, compare how easily a colleague can trace the route in ordinary code and in a graph. There is no universal number of steps that requires a framework.
What this means for you#
Choose the smallest abstraction that makes your next change easier to explain and verify.
| Your current problem | A reasonable starting point | Evidence it helps |
|---|---|---|
| One model call with a small, explicit transcript | Direct HTTP or the provider's SDK | You can inspect each request and handle its result |
| Repeated prompts, message assembly and model integration code | Selected LangChain components | Shared code becomes clearer without hiding inputs |
| Branching, bounded loops or work that pauses and resumes | Evaluate LangGraph | State, route and stopping conditions are inspectable |
Try three exercises with the example:
- Inspect history. Before each call, print only the message roles and count. Expect two messages, then four. Inspect the content locally with synthetic data; keep keys and real learner data out of logs.
- Remove context. In the second call, send only the system instruction and the final question. The chosen topic is absent from that request. A plausible guess is not evidence that the model remembered it.
- Name the next responsibility. Choose one change: persist the transcript, validate a structured answer, or route to course notes. Sketch where it belongs before introducing a library.
The exercise succeeds when you can explain the request, the retained state and the failure path. Answer quality needs its own checks; getting the HTTP shape right is only the start.
Questions developers ask#
Can I build a maintainable chatbot without LangChain?#
Yes. A provider SDK and ordinary functions may be enough. Use a framework when its abstractions improve the work you actually need to maintain. A short direct call is a useful baseline for comparing that benefit.
Does a second conversation turn mean I need LangGraph?#
No. The example carries a short transcript explicitly. Evaluate a graph when state transitions and routes need clearer control, or when interruption and recovery are part of the required behaviour.
Must I replace the chat interface when I change the implementation?#
Keep the client-facing request and response contract stable where practical, and change the implementation behind it. That lets you compare behaviour through the same interface. The Open WebUI endpoint explainer covers that boundary in more detail.
Where can my team practise this progression?#
In the LangChain & LangGraph workshop, Session 1 establishes the chatbot contract and direct-call comparison, Session 2 composes prompts and history, and Session 6 makes the assistant's route explicit. The same Learning Companion grows through those steps. Enquire about the Course Offering for your developer team.
