Single-Agent Handoffs in LangChain: Building an IT Help Desk Workflow
One LangChain agent that changes its prompt and tools per step: a staged IT help desk with real identity checks, middleware handoffs and an out-of-scope exit.
This article is published in English.
Imagine phoning an IT help desk after being locked out of an account. The person on the line doesn't ask the same things at every stage, and what they can do depends on how far along the call is. First they confirm identity, usually through an employee ID or a manager's name, and they won't touch the account problem until that is settled. Next they find out what is wrong: a locked account, a forgotten password or a missing authentication device. Only after that do they act, by re-enabling the account, sending a reset link or transferring the call to the security team. For the caller it feels like one conversation, although its scope shifts as the call advances.
Handoffs give an AI agent the same shape. The agent changes what it is allowed to do according to the current stage of the interaction. At the start it only gathers identifying details. When that's done, it asks about the real issue, and once the problem is clear, it takes action.
Two ways to build it
- Type 1, the middleware approach, uses one agent whose permissions change as the conversation moves forward. Think of the same help desk employee working through a checklist.
- Type 2, the multi-agent approach, uses several agents that pass the conversation to one another, like being transferred to another department when the first person can't help.
The build below follows Type 1, often called single-agent because the code contains exactly one agent. That agent verifies identity, then diagnoses the issue, then resolves it. No new agent appears at any point. What changes is its instructions and its toolset as each stage begins. Type 2 differs by creating separate agents and handing the conversation between them.
The project
The target is an IT help desk agent, and three rules are enforced in code:
- No account issue is discussed until the user's identity checks out against a real record.
- No action is taken until the issue falls into one of three supported categories.
- When the issue fits none of them, the agent says so instead of guessing.
A sample run
A user contacts the help desk after being locked out of a company account. The agent asks for an employee ID and the manager's name. The first attempt matches no employee record, so the agent asks again, and the second attempt verifies. Then the agent asks about the problem. The user first brings up a personal net banking account, which the agent correctly flags as out of scope. After the user clarifies that the trouble is with the company's IT portal, the agent classifies it as a locked account, restores access and ends the conversation once the request is confirmed resolved.
Walking through the code
1. State schema
class HelpdeskState(AgentState):
current_step: NotRequired[HelpdeskStep]
identity_verified: NotRequired[bool]
verification_attempts: NotRequired[int]
issue_type: NotRequired[Literal["locked_account", "forgotten_password", "lost_mfa_device"]]
The current_step field decides which entry of STEP_CONFIG shapes the next response, a point picked up again in section 4. Three further fields (identity_verified, verification_attempts and issue_type) store what the conversation has gathered so far. They get inserted into prompts with .format(), so the resolution prompt can include a line such as EMPLOYEE STATUS: identity_verified = {identity_verified}.
2. Ground truth for verification
EMPLOYEE_DIRECTORY = {
"EMP-4471": {"name": "Amit Rao", "manager": "Priya Nair", "department": "Finance"},
"EMP-1029": {"name": "Sara Khan", "manager": "David Chen", "department": "Engineering"},
"EMP-3305": {"name": "Neha Verma", "manager": "Priya Nair", "department": "Finance"},
}
MAX_VERIFICATION_ATTEMPTS = 3
def normalize_employee_id(raw_id: str) -> str:
digits = "".join(ch for ch in raw_id if ch.isdigit())
return f"EMP-{digits}" if digits else raw_id.strip().upper()
The model never decides whether an employee ID is valid. verify_identity compares the ID with EMPLOYEE_DIRECTORY, so the answer comes from a lookup and not from the model's opinion. A normalizer also copes with the different ways people type the same ID: 4471, emp4471 and EMP-4471 all become one format before the lookup, which keeps valid IDs from being rejected over formatting.
3. Tools
Tools come in two kinds. Transition tools hand back a Command object. It writes new values into the workflow state and advances current_step to whatever stage comes next.
@tool
def verify_identity(
employee_id: str,
manager_name: str,
runtime: ToolRuntime[None, HelpdeskState],
) -> Command:
attempts = (runtime.state.get("verification_attempts") or 0) + 1
normalized_id = normalize_employee_id(employee_id)
record = EMPLOYEE_DIRECTORY.get(normalized_id)
verified = bool(record and manager_name.strip().lower() == record["manager"].lower())
if verified:
content = f"Identity verified for {normalized_id} ({record['name']})."
elif attempts >= MAX_VERIFICATION_ATTEMPTS:
content = f"Verification failed {attempts} times. Session locked — visit IT in person."
elif record is None:
content = f"No employee found with ID '{employee_id}'. Please retry."
else:
content = "The manager name doesn't match our records. Please retry."
return Command(
update={
"messages": [ToolMessage(content=content, tool_call_id=runtime.tool_call_id)],
"identity_verified": verified,
"verification_attempts": attempts,
"current_step": "issue_diagnosis" if verified else "identity_verification",
}
)
Verification has four possible outcomes. It succeeds only when both the employee ID and the manager name match the record. The other three outcomes are reaching the maximum number of attempts, using an ID that doesn't exist, and giving an existing ID with the wrong manager name. Each case produces a different message. A verified user moves to the issue_diagnosis step, and every other outcome stays in identity_verification, so nothing proceeds until identity is confirmed.
Terminal tools return a plain string and leave current_step alone, because the workflow has reached its last stage.
@tool
def flag_out_of_scope(reason: str) -> str:
return (
f"This request appears to be about a personal account, not your "
f"company IT account ({reason}). This helpdesk can't assist with "
f"that — please contact the relevant provider directly."
)
flag_out_of_scope matters as much as the classifier. Without it the workflow would try to fit every request into one of the supported issue types, even unrelated ones, so a personal banking problem could be mislabeled as IT support. The tool gives the agent a clean way to recognize requests outside the workflow's scope.
4. Prompts and step configuration
Every stage has its own prompt and its own tool list, kept in a single dictionary and chosen by the current value of current_step.
STEP_CONFIG = {
"identity_verification": {"prompt": IDENTITY_VERIFICATION_PROMPT, "tools": [verify_identity], "requires": []},
"issue_diagnosis": {"prompt": ISSUE_DIAGNOSIS_PROMPT, "tools": [record_issue_type, flag_out_of_scope], "requires": ["identity_verified"]},
"resolution": {"prompt": RESOLUTION_PROMPT, "tools": [unlock_account, send_password_reset_link, escalate_mfa_recovery, go_back_to_verification], "requires": ["identity_verified", "issue_type"]},
}
The requires field acts as a guard for the middleware, which checks that the needed conditions hold before applying a step's configuration.
5. Middleware
@wrap_model_call
def apply_step_config(
request: ModelRequest,
handler: Callable[[ModelRequest], ModelResponse],
) -> ModelResponse:
current_step = request.state.get("current_step", "identity_verification")
step_config = STEP_CONFIG[current_step]
for key in step_config["requires"]:
if request.state.get(key) is None:
raise ValueError(f"'{key}' must be set before reaching '{current_step}'")
system_prompt = step_config["prompt"].format(**request.state)
request = request.override(system_prompt=system_prompt, tools=step_config["tools"])
return handler(request)
The name comes from where this code runs: between the current workflow state and the model call. Before the model produces a reply, the middleware reads the state, swaps in the prompt and tools for the current step and then passes control on. It runs ahead of every model call. It reads current_step, loads the matching configuration, confirms the required conditions are met, formats the prompt with the current state values and assigns the right tools. That is how the agent's behavior changes as the workflow moves.
6. Building the agent
agent = create_agent(
model,
tools=all_tools,
state_schema=HelpdeskState,
middleware=[apply_step_config],
checkpointer=InMemorySaver(),
)
The checkpointer is essential because it keeps workflow state between messages. Without one, current_step resets on every call, and the agent restarts at the first step each time and never advances.
Design choices that prevent mistakes
Several details exist to head off common failures in this kind of workflow.
- Verification checks a real record. Had
verify_identityput the question to the model, asking if an ID and manager name seemed right, anything plausible would pass. Looking upEMPLOYEE_DIRECTORYremoves the guesswork. - IDs are normalized before matching. Demanding one exact format such as EMP-4471 would reject valid inputs like 4471 or emp4471 purely because of how they were typed. The normalizer converts the common formats to one canonical form first.
- The classifier has a "none of these" exit.
record_issue_typeaccepts only three categories. Withoutflag_out_of_scope, unrelated requests such as a banking question would be forced into the nearest category. - The CLI exit check matches a word. A plain test like
user_input in {"quit", "exit"}works only when the whole message is exactly one of those words. A word-boundary regex catches them anywhere in a sentence, including something like "quit and exit".
In each case the simplest implementation looks fine and then fails on realistic input.
The pattern in short
Single-agent handoffs need just three parts. A current_step field holds the stage, tools change it, and middleware consults it prior to each model call. Together they steer how the workflow progresses. Correct behavior still comes from the details: verifying against a real record, normalizing IDs, offering an out-of-scope path and matching exit words properly. The state machine controls the order of the workflow, and the validation logic makes sure each step behaves.