EN ▾

How to Create a Chatbot Using LangChain, Step by Step

This is how to create a chatbot using LangChain that has a persona, remembers the conversation and streams its replies. The model behind it is an OpenAI-compatible uncensored API, so a short Python file is enough.

Updated

Speech bubble assembled from linked building blocks, illustrating a chatbot built from LangChain components

What you are building

By the end you will have a command-line chatbot with four properties: a persona defined in a system prompt, memory of the conversation, token-by-token streaming and a saved history file. Once that works, moving it behind a web framework is mostly plumbing. If you are wondering how to create a chatbot using LangChain without pulling in agents, vector stores and a pile of abstractions, the answer is that you need very little. A chatbot is three things: a model object, a prompt template and a list of messages that you own.

You need Python 3.9 or newer, an API key from the key page, and about ten minutes. New accounts can claim $0.50 of trial credit with one click after sign-up, valid for 7 days and without payment details, which covers far more chat turns than this tutorial needs.

Steps 1 and 2: the model and the persona

python -m venv .venv
source .venv/bin/activate
pip install -U langchain-openai langchain-core
export NSFWCHATBOT_API_KEY="paste-your-key-here"

Create bot.py and start with the model. LangChain's ChatOpenAI class talks to any OpenAI-compatible server. You override the base URL, pass your key and choose the model name uncensored.

import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.nsfwchatbot.cc/v1",
    api_key=os.environ["NSFWCHATBOT_API_KEY"],
    temperature=0.85,
    max_tokens=500,
    max_retries=2,
    timeout=120,
)

max_tokens is optional on this API, but a cap of a few hundred keeps replies chat-sized and keeps cost predictable. The client retries twice on network trouble and on HTTP 429 responses.

The persona prompt

A prompt template with a MessagesPlaceholder gives the history a fixed place after the system message. Put the persona in the system slot. Describe who the bot is, how it talks and what it should avoid, in plain sentences.

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

prompt = ChatPromptTemplate.from_messages([
    ("system",
     "You are Juno, a sharp-tongued ship's AI in a space opera for adult readers. "
     "You speak in short, wry sentences and you stay in character. "
     "You are not an assistant and you never mention being a language model."),
    MessagesPlaceholder("history"),
    ("human", "{input}"),
])

chain = prompt | llm

The pipe operator joins the template and the model into one runnable. Calling chain.invoke({"history": [...], "input": "Hello"}) fills the template, sends the messages and returns an AIMessage. Because the model is tuned to answer without content refusals for lawful adult use, personas for fiction and companion apps work as described. The one hard limit is that sexual content involving minors is not allowed.

Step 3: add memory you control

LangChain offers several memory wrappers, but a plain list is easier to understand and debug. Keep a list of human and AI messages, append after each turn and pass it into the chain.

from langchain_core.messages import HumanMessage, AIMessage

history = []

def chat_once(user_text):
    reply = chain.invoke({"history": history, "input": user_text})
    history.append(HumanMessage(content=user_text))
    history.append(AIMessage(content=reply.content))
    return reply.content

if __name__ == "__main__":
    while True:
        text = input("you> ").strip()
        if text in {"quit", "exit"}:
            break
        print("juno>", chat_once(text))

Run python bot.py and talk to it. Ask it something at the start, then refer back to it ten messages later. If it remembers, memory works. Nothing is stored on the server between calls; your list is the only memory there is.

Step 4: stop history from growing forever

The context window is 100,000 tokens, which is large, but you pay for the full history on every call, at $0.15 per 1M input tokens. A 60-turn chat that adds 400 tokens per turn resends close to 24,000 tokens by the end. Trim before that becomes a habit. LangChain ships trim_messages, which cuts a message list to a size limit.

from langchain_core.messages import trim_messages

trimmer = trim_messages(
    max_tokens=24,          # keep the last 24 messages
    strategy="last",
    token_counter=len,      # count messages, not tokens
    start_on="human",
)

def chat_once(user_text):
    window = trimmer.invoke(history)
    reply = chain.invoke({"history": window, "input": user_text})
    history.append(HumanMessage(content=user_text))
    history.append(AIMessage(content=reply.content))
    return reply.content

Passing len as the counter makes the limit a message count, which is crude but predictable. Since the persona lives in the template and not in history, it is never trimmed away. For stories where early facts matter, add a rolling summary: every 20 turns, ask the model to summarize the oldest messages in 150 words and replace them with that single message.

Two small improvements are worth making early. Store messages in the order they happened and never edit past entries, because the model treats them as the real record of what was said. And when the bot gets something wrong, fix the prompt instead of patching the history; a clean history plus a clearer persona fixes the whole class of mistake, while a hand-edited history only fixes one instance of it.

Step 5: stream and save

Streaming makes replies appear as they are written. Swap invoke for stream and collect the pieces so you can store the full text.

import json
from langchain_core.messages import messages_to_dict, messages_from_dict

def chat_stream(user_text):
    window = trimmer.invoke(history)
    parts = []
    for chunk in chain.stream({"history": window, "input": user_text}):
        print(chunk.content, end="", flush=True)
        parts.append(chunk.content)
    print()
    history.append(HumanMessage(content=user_text))
    history.append(AIMessage(content="".join(parts)))

def save(path="chat.json"):
    with open(path, "w") as f:
        json.dump(messages_to_dict(history), f)

def load(path="chat.json"):
    try:
        with open(path) as f:
            history[:] = messages_from_dict(json.load(f))
    except FileNotFoundError:
        pass

Call load() at startup and save() after each turn. For a multi-user app, replace the file with a database table keyed by user and conversation ID. A streamed request keeps its concurrency slot until the stream finishes, which matters in the next step.

Step 7: expose it over HTTP

Once the loop works in a terminal, a web endpoint is a small step. This FastAPI sketch keeps one history per session ID in memory and returns the reply as JSON. Swap the dictionary for a database when you deploy more than one process.

import os
from fastapi import FastAPI
from pydantic import BaseModel
from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="uncensored",
    base_url="https://api.nsfwchatbot.cc/v1",
    api_key=os.environ["NSFWCHATBOT_API_KEY"],
    max_tokens=400,
)
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are Juno, a wry ship's AI. Stay in character."),
    MessagesPlaceholder("history"),
    ("human", "{input}"),
])
chain = prompt | llm

app = FastAPI()
sessions = {}

class Msg(BaseModel):
    session: str
    text: str

@app.post("/chat")
async def chat(m: Msg):
    hist = sessions.setdefault(m.session, [])
    out = await chain.ainvoke({"history": hist[-24:], "input": m.text})
    hist.append(HumanMessage(content=m.text))
    hist.append(AIMessage(content=out.content))
    return {"reply": out.content}

Run it with uvicorn app:app. Add the semaphore from the previous step around the ainvoke call before you put it on the internet, and never expose your API key to a browser. The key stays on the server; the browser only talks to your /chat route.

Step 6: serving more than one user

One user at a time is easy. A public bot needs to respect the limits: a full key allows 8 concurrent requests and 300 per minute, and a trial key allows 2 and 60. Exceed them and the API answers HTTP 429 with the code rate_limited or concurrency. On temporary overload you also get 429 with Retry-After: 5.

The straightforward fix is a semaphore around the call, sized below your limit, with a short queue behind it.

import asyncio

gate = asyncio.Semaphore(6)

async def reply_async(window, user_text):
    async with gate:
        out = await chain.ainvoke({"history": window, "input": user_text})
    return out.content

If you outgrow 8 concurrent streams, show users a typing indicator while their message waits for a slot rather than failing. Every response includes X-Balance-USD, X-Request-Id and rate-limit headers, so log the request ID with each chat turn for easier debugging. See the docs for error codes, and the pricing page for top-up amounts, which start at $20 and accept USDT on TRC20 or USDC on Base.

Troubleshooting and tuning

A few problems come up in almost every first LangChain chatbot, and each has a short fix.

  • The bot speaks as the user. Add a line to the persona such as "Never write the user's lines." Lower temperature to 0.7 if it keeps wandering.
  • Replies are too long. Lower max_tokens and ask for a length in the prompt, for example "two short paragraphs".
  • Authentication errors. Check that the environment variable is set in the shell that runs Python, and that the base URL ends in /v1.
  • The bot repeats itself. Pass a small frequency_penalty or presence_penalty through the constructor; these are forwarded to the model.
  • Costs creep up. Log reply.usage_metadata per turn. Input tokens grow with history, so confirm the trimmer is actually applied.

The hosted model is one fixed open-weight model run by an independent provider, so improvements come from your prompts and sampling settings, not from switching models. If you want a second opinion on structure, the quickstart has curl examples you can compare with what LangChain sends. Failed or refused requests are not charged, so debugging runs cost nothing when they error out.

Questions and answers

Do I need LangGraph or agents to build a chatbot?

No. A prompt template, a ChatOpenAI model and a message list are enough for a conversational bot. Add agents only if the bot must call tools in a loop.

Why does my bot forget earlier messages?

The server keeps no state between calls. You must pass the previous messages in each request, as the history list does in this tutorial.

Can this bot use tools?

Yes. The API supports tool calling, so you can use bind_tools on the model. Handle the tool result loop in your code.

How much does a test conversation cost?

A 20-turn chat at about 400 tokens per turn costs well under two cents at $0.15 per 1M input and $0.50 per 1M output tokens.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key