Why AI Trading Agents Need a Pause Button
A $1,000 problem
Making $1,000 a month without going to work sounds like a pretty good assignment for an AI investment bot.
Give it $150,000 in investment capital, access to financial markets, company fundamentals, dividend histories and analyst reports. Tell it to build a portfolio that generates a steady stream of passive income.
Within seconds, the bot encounters a problem that has nothing to do with AI. It's a problem of arithmetic.
Generating $12,000 a year from $150,000 requires an annual dividend yield of 8%, before taxes and fees.
While ambitious, it's an achievable target - certainly for Super Intelligence ;)
The bot could start screening the market for high-yielding stocks. It might find companies offering attractive dividends, real estate investment trusts, business development companies and various income-oriented funds. On paper, it could assemble something that meets the investor's target.
But there's a catch. A company doesn't become a better investment simply because its share price has fallen and its dividend yield has gone up. Sometimes that attractive yield is the market's way of telling you that something is wrong.
Dividends can be reduced. Companies can struggle. Capital can disappear considerably faster than dividends accumulate.
Consider the following numbers:
| Annual dividend yield | Annual income | Average monthly income | Capital needed for $1,000/month |
|---|---|---|---|
| 3% | $4,500 | $375 | $400,000 |
| 4% | $6,000 | $500 | $300,000 |
| 6% | $9,000 | $750 | $200,000 |
| 8% | $12,000 | $1,000 | $150,000 |
These are straightforward calculations that bot will assume, not expected market returns. However, of course, actual dividend payments may vary throughout the year.
The investment bot has the numbers. What it doesn't have is the investor's definition of an acceptable trade-off.
Is the $1,000 monthly target non-negotiable? Would the investor accept less income in exchange for potentially greater dividend sustainability? Is capital appreciation important? Is the money needed for living expenses, or will the dividends be reinvested?
No amount of additional market data will reliably answer those questions.
So instead of producing another investment report, the bot stops and asks:
Reaching your income target requires an annual dividend yield of 8%. Which investment objective should I prioritize?
Dividend sustainability: Accept potentially lower income and focus on financially resilient companies.
Maximum current income: Investigate higher-yielding investments and their associated risks.
Balanced approach: Consider both dividend income and long-term capital growth.
The investor selects the balanced approach. The bot incorporates that decision into its analysis and continues researching the market.
It sounds like a small improvement to the user experience. Underneath, however, something rather interesting has happened.
The AI has interrupted its own workflow, handed control back to the investor, received a decision and resumed its work.
How you engineer that seemingly mundane interaction is one of the more interesting problems in modern AI application development.
The problem with AI that always has an answer
The financial industry has spent decades building increasingly sophisticated systems for analyzing markets. We have quantitative models, portfolio optimization algorithms, risk engines and enough financial data to keep a small army of analysts occupied indefinitely.
Now we're putting LLMs on top of all that infrastructure.
An investment agent can retrieve company financial statements, examine dividend histories, compare valuation metrics and orchestrate a portfolio simulation. But the availability of more information doesn't eliminate the need for human judgment.
A portfolio optimized for a 30-year-old investor accumulating wealth may look very different from one designed for someone approaching retirement. Both investors might ask exactly the same question about dividend stocks.
The problem isn't a lack of intelligence. It's a lack of context.
Traditional chatbots handle this by generating a textual response:
Before proceeding, could you tell me more about your investment horizon and risk tolerance?
That works in a conversation. It becomes less convenient when the chatbot is actually an agent running a multi-step investment research pipeline.
Suppose the bot has already retrieved financial data, screened hundreds of companies and started evaluating portfolio allocations. It now needs a decision before selecting its next analytical step.
Should it discard its progress? Should the user's next message restart the entire analysis? How does the application distinguish an answer to the pending question from an unrelated request?
What we need is a way to make human interaction part of the execution pipeline itself.
In software engineering, this pattern is known as human-in-the-loop, or HITL.
A question is just another tool
If you've used Claude Code or one of the newer coding assistants, you've probably encountered interactive questions. Instead of dumping a paragraph into the chat window, the assistant presents a set of options. You make a selection, and it continues working.
There's no particular magic behind this interface and the underlying mechanism is called tool calling.
Modern LLMs can request operations defined by the application. An investment assistant, for example, might have access to tools such as:
get_stock_fundamentalsget_dividend_historycalculate_portfolio_yieldanalyze_dividend_coveragesimulate_portfolioask_user
That last tool is the interesting one.
From the model's perspective, asking an investor a question is simply another available operation. It doesn't need to know anything about React components, mobile interfaces, buttons or radio groups.
The application defines what a question looks like using a structured schema.
Here's a simplified tool definition using the OpenAI-compatible API format:
{
"type": "function",
"function": {
"name": "ask_user",
"description": "Ask the investor to resolve an important investment decision.",
"parameters": {
"type": "object",
"properties": {
"question": {
"type": "string"
},
"options": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": ["question", "options"]
}
}
}This definition is sent to the model alongside its other available tools.
When the model encounters an unresolved investment preference, it can invoke ask_user with a question and a set of possible answers. The question is no longer just a piece of text. It's a structured operation with a defined input and an expected result.
That's an important distinction. We don't need another language model to read the assistant's response and figure out whether it should display a questionnaire. The application already knows what to do because the model has explicitly invoked the appropriate tool.
What actually comes back from the LLM?
Let's look at what happens at the HTTP API level.
After analyzing the dividend income target, the model might return the following assistant message:
{
"role": "assistant",
"content": null,
"tool_calls": [
{
"id": "call_784",
"type": "function",
"function": {
"name": "ask_user",
"arguments": "{\"question\":\"Which investment objective should I prioritize?\",\"options\":[\"Dividend sustainability\",\"Maximum current income\",\"Balanced approach\"]}"
}
}
]
}There are two particularly important fields here.
The first is the function name, ask_user. It tells the application that the model is requesting human input.
The second is the tool call identifier, call_784. It identifies this particular invocation and will eventually allow us to associate the investor's answer with the original question.
The application parses the arguments and renders the appropriate interface.
This mechanism isn't unique to OpenAI. Anthropic's Messages API represents tool invocations using tool_use content blocks. Open-weight models such as Qwen can expose similar functionality through inference servers such as llama.cpp or vLLM.
Qwen may generate tool calls using its own native token format, but the inference server converts that representation into a structured, OpenAI-compatible HTTP response.
The model provider can change without fundamentally changing the application's architecture.
As long as the model and inference server support reliable tool calling, the investment agent can use the same interaction mechanism.
The difficult part isn't asking. It's waiting.
Imagine the investor receives the dividend question while sitting on a train.
They look at the options, close the application and decide to think about it.
Six hours later, they return and select the balanced approach.
What happened to the investment analysis during those six hours?
Keeping an HTTP connection open while somebody thinks about their retirement strategy isn't a particularly sensible architecture. Keeping a Python worker occupied is no better. And there's certainly no reason to keep an expensive GPU running.
The workflow needs to stop!
The application must preserve enough information to continue later: the conversation, the pending tool call, the investment analysis already performed and the question waiting for an answer.
When the investor returns, the system restores that state and picks up the work.
Developers can implement this themselves using a database, a custom agent loop and a state machine. For a small application, that's a perfectly reasonable approach.
Things become more complicated when the agent performs parallel research, executes multiple tools, handles failures or asks several questions at different stages of a workflow.
This is where LangGraph becomes useful.
LangGraph: Giving the investment bot a pause button
LangGraph is an orchestration framework for building stateful AI applications and we've had a stab at it when we were building our v1 financial bot.
Rather than treating an AI interaction as a single model request, LangGraph represents the workflow as a graph of operations.
One node might retrieve market data. Another might invoke an LLM. A third might calculate portfolio income. Conditional edges determine which operation happens next.
The graph can branch, loop and execute tools. More importantly, it can suspend its execution and resume later.
LangChain provides higher-level abstractions for working with language models, messages and tools. Its create_agent() function uses LangGraph underneath, so we don't necessarily need to construct the entire graph ourselves.
For our dividend investment assistant, two primitives are particularly important:
from langgraph.types import interrupt, CommandThe first pauses the workflow. The second resumes it.
Here's what an interrupt looks like:
answer = interrupt({
"type": "question",
"question": "Which investment objective should I prioritize?",
"options": [
"Dividend sustainability",
"Maximum current income",
"Balanced approach"
]
})On its first execution, interrupt() doesn't return an answer. It suspends the workflow and exposes the question to the calling application.
LangGraph records the execution state using a checkpointer. The backend forwards the question to the frontend, and the investor can take as much time as necessary, subject to the application's own expiration policy.
When the answer arrives, the backend resumes execution:
Command(
resume={"answer": "Balanced approach"}
)During resumed execution, the original interrupt() call returns the supplied value.
The investment agent can now continue its analysis.
What happens beneath the surface?
LangGraph isn't literally freezing a Python function and keeping it alive somewhere in memory.
It persists the graph's execution state.
When the workflow resumes, LangGraph re-executes the interrupted node and supplies the stored answer when it reaches the relevant interrupt.
That's a subtle distinction with significant consequences, particularly in trading applications.
Imagine a node that submits a buy order and then interrupts execution. If the node runs again when the workflow resumes, it could attempt to submit the same order twice.
That's not a software bug anybody wants to discover with real money.
Operations preceding an interrupt must therefore be safe to repeat. Financial transactions should use separate, carefully controlled execution steps, with idempotency guarantees and independent authorization.
LangGraph provides the machinery for pausing execution. It doesn't automatically make financial operations safe.
How does the agent know which question was answered?
Suppose the investor has several active analyses. One concerns dividend income, another evaluates technology stocks, and a third investigates portfolio rebalancing.
When the investor selects an option, how does the system know which workflow to resume?
Three identifiers establish the relationship:
| Identifier | Responsibility |
|---|---|
thread_id | Identifies the persisted investment workflow. |
interrupt_id | Identifies the pending human interaction. |
tool_call_id | Associates the answer with the model's original tool invocation. |
Our dividend analysis might belong to a thread called dividend_analysis_123.
The model invokes ask_user with a tool call ID of call_784. LangGraph encounters an interrupt and assigns it an identifier, represented here as int_456.
The frontend receives the question together with the relevant identifiers.
When the investor makes a selection, the application submits:
{
"thread_id": "dividend_analysis_123",
"interrupt_id": "int_456",
"answer": "Balanced approach"
}The backend explicitly resumes the corresponding interrupt:
Command(
resume={
"int_456": {
"answer": "Balanced approach"
}
}
)LangGraph restores the appropriate workflow and completes the interrupted tool execution.
The agent runtime subsequently constructs a tool-result message associated with the original LLM invocation:
{
"role": "tool",
"tool_call_id": "call_784",
"content": "{\"answer\":\"Balanced approach\"}"
}The next model request includes the original question and its corresponding result.
The LLM doesn't need another prompt explaining that the investor is now answering a question from six hours ago. That relationship is already represented by the tool-calling protocol.
LangGraph manages execution state. The model API manages the relationship between a tool invocation and its result.
Building the investment agent
Let's put these ideas together using Python, LangChain, LangGraph and a locally hosted Qwen model running through llama.cpp.
The same architecture can work with other tool-capable models.
First, install the dependencies:
pip install langchain langgraph langchain-openaiDefine the tools
We'll create two tools. The first asks the investor a question. The second calculates hypothetical dividend income at different yield levels.
import json
from decimal import Decimal
from langchain.tools import tool
from langgraph.types import interrupt
@tool
def ask_user(
question: str,
options: list[str]
) -> str:
"""Ask the investor to resolve a material
investment preference before continuing."""
answer = interrupt({
"type": "question",
"question": question,
"options": options
})
if answer["answer"] not in options:
raise ValueError("Invalid selection")
return json.dumps(answer)
@tool
def calculate_dividend_income(
capital: int,
annual_yield: float
) -> str:
"""Calculate hypothetical gross dividend
income. Annual yield is expressed as a
percentage, e.g. 4 for 4%."""
annual_income = (
Decimal(capital)
* Decimal(str(annual_yield))
/ 100
)
return json.dumps({
"annual_income": str(round(annual_income, 2)),
"monthly_average": str(
round(annual_income / 12, 2)
)
})Notice the separation of responsibilities.
The financial arithmetic is performed by conventional Python code. The LLM decides which operations to request and interprets their results.
There's little reason to ask a probabilistic language model to do arithmetic when a deterministic function can do it reliably.
Configure the agent
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
model = ChatOpenAI(
model="local",
base_url="http://localhost:8080/v1",
api_key="local"
)
agent = create_agent(
model=model,
tools=[
ask_user,
calculate_dividend_income
],
checkpointer=InMemorySaver(),
system_prompt="""
You are an investment research assistant.
Use calculation tools for financial arithmetic.
Distinguish hypothetical yields from
actual market data.
Use ask_user when an unresolved investment
preference could materially change the analysis.
Do not equate high dividend yields
with investment quality.
Do not promise investment returns.
Do not execute trades.
"""
)The local inference server must support the model's tool-calling format. The configured model name must match the server's model or alias.
A production investment assistant would also have tools for retrieving market prices, financial statements, dividend coverage ratios and historical distributions.
For now, we're concentrating on the mechanics of the interaction itself.
Start the investment analysis
config = {
"configurable": {
"thread_id": "dividend_analysis_123"
}
}
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": """
I have $150,000 to invest.
I want to generate $1,000 a month
from dividends.
Calculate the required yield
and clarify my investment objective
before recommending an approach.
"""
}
]
},
config=config
)The model can perform its calculations, recognize the demanding income target and invoke ask_user.
When it does, LangGraph suspends execution.
Send the question to the frontend
The application detects the pending interrupt:
pending = result.get("__interrupt__", [])
for item in pending:
event = {
"type": "user_input_required",
"thread_id": "dividend_analysis_123",
"interrupt_id": item.id,
"payload": item.value
}
print(json.dumps(event, indent=2))Instead of simply printing the event, a real backend would send it to the mobile application or web frontend.
The payload might look like this:
{
"type": "user_input_required",
"thread_id": "dividend_analysis_123",
"interrupt_id": "int_456",
"payload": {
"type": "question",
"question": "Which investment objective should I prioritize?",
"options": [
"Dividend sustainability",
"Maximum current income",
"Balanced approach"
]
}
}The frontend renders an interactive question using its existing component library.
It doesn't need to know which model produced the question or how the underlying investment analysis works.
Resume the investment analysis
When the investor makes a selection, the backend validates the answer and resumes the workflow.
from langgraph.types import Command
def resume_analysis(
thread_id: str,
interrupt_id: str,
answer: str
):
config = {
"configurable": {
"thread_id": thread_id
}
}
state = agent.get_state(config)
pending = [
item
for task in state.tasks
for item in task.interrupts
]
question = next(
(
item for item in pending
if item.id == interrupt_id
),
None
)
if question is None:
raise ValueError("Unknown pending question")
if answer not in question.value["options"]:
raise ValueError("Invalid selection")
return agent.invoke(
Command(
resume={
interrupt_id: {
"answer": answer
}
}
),
config=config
)We can now continue the analysis:
result = resume_analysis(
thread_id="dividend_analysis_123",
interrupt_id=pending[0].id,
answer="Balanced approach"
)LangGraph restores the workflow, completes the question tool and returns its result to the model.
The agent might now compare several hypothetical income scenarios, explain the capital required to reach the investor's target and identify the additional research needed to construct a portfolio.
If another important preference remains unresolved, it can ask another question.
The process repeats until the analysis is complete.
The complete execution flow
The investment assistant operates as a loop, with human interaction represented as a conditional branch.
INVESTOR
|
v
"I want $1,000/month
in dividends"
|
v
LANGGRAPH AGENT
|
v
INVOKE LLM <----------------+
| |
v |
INSPECT TOOL CALL |
| |
+--------+--------+ |
| | |
Financial tool ask_user |
| | |
v v |
Calculate yield interrupt() |
Retrieve data | |
Analyze stocks v |
| Save checkpoint |
| | |
| v |
| Display question |
| | |
| WAIT FOR INVESTOR |
| | |
| v |
| Investor answers |
| | |
| v |
| Command(resume) |
| | |
| v |
| Restore workflow |
| | |
+--------+--------+ |
| |
v |
CREATE TOOL RESULT |
| |
v |
UPDATE MESSAGE HISTORY ----------+
When analysis is complete:
|
v
INVESTMENT RESEARCH REPORTThe critical feature is that waiting for the investor is a persisted workflow state, not a continuously running computational task.
Wall Street doesn't wait for your checkpoint
There is an additional complication when building investment and trading agents: markets keep moving while the application waits.
Suppose the agent calculates dividend yields using Monday morning's prices. The investor answers on Tuesday afternoon. By then, share prices may have changed, a company might have announced earnings, or a dividend reduction could have completely altered the analysis.
The workflow checkpoint remains valid as a record of execution. The financial assumptions might not.
A production investment agent should distinguish persistent user decisions from time-sensitive market observations.
Investment preferences can generally be carried forward. Market data may need to be refreshed. Portfolio calculations may need to be repeated.
The application should retain timestamps, data sources and the assumptions used to generate each analysis. That information is particularly important when an investment recommendation is reviewed later.
There is also a world of difference between selecting an investment objective and authorizing a trade.
Choosing the balanced approach doesn't authorize the bot to spend $150,000.
Actual trade execution requires independent risk checks, appropriate permissions, explicit authorization and protection against duplicate orders. An LLM-generated question should never bypass those controls.
For production systems, the in-memory checkpointer used in our example should be replaced with durable storage, such as PostgreSQL. Resume requests must be authenticated, validated against the current workflow state and protected against concurrent or duplicate submissions.
The language model is one component of the investment system. It shouldn't be the system's entire risk management department.
Do we need a universal protocol for interactive AI?
Several emerging technologies address different aspects of this architecture.
MCP Elicitation defines structured mechanisms for requesting information from users. AG-UI provides standardized communication between agents and application frontends. A2UI allows agents to describe dynamically generated user interfaces.
These technologies become interesting when building platforms that support multiple models, independent agents and different frontend applications.
But our dividend assistant doesn't necessarily need a generative UI protocol.
A carefully designed library of financial charts, stock comparison tables, questionnaires and investment review screens may be more useful than giving an LLM unrestricted control over the interface.
The model can decide what to ask. The application can decide how to present it.
Native tool calling, LangGraph interrupts and structured frontend events are enough to build a sophisticated interactive investment assistant.
Sometimes the smartest answer is a question
There's a tendency in AI development to measure progress by how much an agent can accomplish without human intervention.
In investing, that's not necessarily the right metric.
An algorithm can find hundreds of companies paying dividends. It can rank them by yield, calculate payout ratios, analyze earnings and simulate different allocations.
What it cannot determine from market data alone is how much uncertainty somebody is willing or financially able to tolerate with their life savings.
A good investment assistant should recognize the difference.
The real opportunity isn't to build a bot that always has an answer. It's to build one that knows when the answer depends on information it doesn't have, and when the person supplying that information should remain in control.
Tool calling gives the model a structured way to ask. LangGraph gives the application a reliable mechanism for stopping and continuing. The frontend gives the investor a practical way to participate.
The technology behind it is sophisticated. The underlying idea is remarkably simple.
Before you optimize somebody's portfolio, find out what they're actually trying to achieve.
After all, it's their money.
Comments
Post a Comment