By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Wire the part 1 pieces into Harbor Helper, the agent. By the end of this step the agent answers order questions from tool data, grounds policy questions in retrieved documents, keeps a per-ticket conversation under a token budget, and never executes a write without a decision. All of it is tested with fake models, so the whole project runs in CI with no API key.
build_agent(model) returns create_agent(model=..., tools=[...], system_prompt=..., checkpointer=InMemorySaver()). One factory, so tests and production build the agent the same way.thread_id per ticket, a @before_model trimmer or trim_messages call with a token budget, and the system prompt kept on every request.search_docs(query) backed by a vector store; the answer must cite the passage's source, or say the docs do not cover the question. Use fake embeddings in tests and a real embedding model in production.request_replacement(...) returns a pending record instead of writing. Either gate it with HumanInTheLoopMiddleware(interrupt_on={...}) plus a checkpointer, or keep the plain queue from part 1 — but no write runs before a decision.import pytest
from langchain.agents import create_agent
from langchain.messages import AIMessage, HumanMessage, ToolCall
from langchain.tools import tool
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
class FakeToolCallingModel(GenericFakeChatModel):
def bind_tools(self, tools, **kwargs):
return self
@tool
def lookup_order(order_id: str) -> dict:
"""Read-only order lookup."""
orders = {"4521": {"status": "delivered", "items": ["ceramic mug"]}}
if order_id not in orders:
raise ValueError(f"Unknown order: {order_id}")
return {"order_id": order_id, **orders[order_id]}
@tool
def request_replacement(order_id: str, item_id: str) -> dict:
"""Queue a replacement for human approval. Never executes the write."""
return {"status": "pending_approval", "order_id": order_id, "item_id": item_id}
def test_read_only_question_uses_the_tool():
model = FakeToolCallingModel(
messages=iter(
[
AIMessage(
content="",
tool_calls=[
ToolCall(
name="lookup_order",
args={"order_id": "4521"},
id="call_1",
)
],
),
AIMessage(content="Order #4521 was delivered and contains a ceramic mug."),
]
)
)
agent = create_agent(model, tools=[lookup_order, request_replacement])
result = agent.invoke({"messages": [HumanMessage("Where is order #4521?")]})
tool_messages = [m for m in result["messages"] if m.type == "tool"]
assert tool_messages and "delivered" in str(tool_messages[0].content)
assert "4521" in result["messages"][-1].text
def test_write_is_queued_not_executed():
model = FakeToolCallingModel(
messages=iter(
[
AIMessage(
content="",
tool_calls=[
ToolCall(
name="request_replacement",
args={"order_id": "4521", "item_id": "mug"},
id="call_2",
)
],
),
AIMessage(content="I queued a replacement for approval."),
]
)
)
agent = create_agent(model, tools=[lookup_order, request_replacement])
result = agent.invoke(
{"messages": [HumanMessage("Replace the mug on order 4521.")]}
)
tool_messages = [m for m in result["messages"] if m.type == "tool"]
assert "pending_approval" in str(tool_messages[0].content)
assert "queued" in result["messages"][-1].textbuild_agent(model) used by both tests and the app; tools are the part 1 objects.checkpointer and a per-ticket thread_id; a trimmer with an explicit token budget keeps the system prompt.search_docs tool with source metadata; the system prompt requires answers to come from the passages or say they do not cover it.pytest -q passes without an API key, including the part 1 tests.source or says the documents do not cover it — no unsourced confident answer.HumanInTheLoopMiddleware and add an interrupt/resume test.SummarizationMiddleware and compare answer quality and token usage.Key takeaways
Wire the agent with one factory so tests and production share the same build.
Memory is a per-ticket thread plus a token budget, not an unbounded transcript.
Retrieval must ground and cite; a write must become a pending record, not an action.
Acceptance is behavioural: keyless tests, trace order, pending approval and grounded answers.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.