03. Your First Agent (AI Harness)#
A fast, conceptual revision guide for 03-ai-harness. Focused on how agents work — the ReAct loop, tool schemas, live search, custom vs. vendor tools, parallel tool calls, and validated structured outputs — without boilerplate code clutter.
Agent Execution Traces & Message History#
Revision Notes#
Reference files: pyproject.toml, agent_trace_printer.py
Concept#
A simple chain runs once: one prompt in, one AIMessage out. An agent, by contrast, runs in a loop and produces a multi-message conversation trajectory stored in result["messages"]. Reading that message trail is the core skill for debugging and understanding why an agent behaved the way it did.
Key Mental Models#
- Every step in the loop is a typed message:
HumanMessage— The user's original question.AIMessage(withtool_calls) — The model's decision to call one or more tools with specific arguments.ToolMessage— The output returned by executing a tool, tagged with the tool's name.- Final
AIMessage(notool_calls) — The model's synthesized answer once it decides it has enough information.
- Why trace readability matters: Real search tools return large JSON payloads that easily flood a terminal. Summarizing each message to a single truncated line (
agent_trace_printer.py) — and enabling LangSmith (LANGSMITH_TRACING=true) for visual timelines — lets you immediately inspect the model's reasoning path, tool arguments, and loop count.
Code Reference#
# -----------------------------------------------------------------------------
# _one_line()
# -----------------------------------------------------------------------------
# Squashes any text to a single line and cuts it to `limit` characters, so long
# search results don't flood the terminal.
#
# _one_line("a\nb\nc", 10) → "a b c"
# _one_line("x" * 500, 10) → "xxxxxxxxxx … (+490 chars)"
def _one_line(text: str, limit: int = 160) -> str:
# str(text).split() collapses newlines, tabs, and repeated spaces in one pass;
# casting to str() first also lets us pass dicts (like tool args) safely.
flat = " ".join(str(text).split())
# -> "{'query': 'Bengaluru weather now'}" (newlines/extra spaces collapsed)
if len(flat) <= limit:
return flat
# Show how many characters were omitted so the reader knows output was truncated.
return f"{flat[:limit]} … (+{len(flat) - limit} chars)"
# -----------------------------------------------------------------------------
# print_agent_trace()
# -----------------------------------------------------------------------------
# Input : result (dict) — the value returned by agent.invoke(...)
# It always has a "messages" key; with response_format=... it also
# has a "structured_response" key (see Script 04).
# Output: None (prints to the terminal)
def print_agent_trace(result: dict) -> None:
# LangChain agents return the entire conversation history (Human -> AI tool call
# -> Tool result -> final AI answer) so every step of the loop is inspectable.
messages = result["messages"]
# -> [HumanMessage("What's the weather..."), AIMessage(tool_calls=[...]),
# ToolMessage(name='search', ...), AIMessage("It's about 24°C...")]
print(f"\nThe agent produced {len(messages)} messages:")
for index, message in enumerate(messages):
kind = type(message).__name__
# -> 'HumanMessage' | 'AIMessage' | 'ToolMessage'
# AIMessages that request tools carry their calls in `.tool_calls` and
# usually have empty text. `getattr(..., None)` safely handles Human/Tool
# messages that don't define that attribute.
tool_calls = getattr(message, "tool_calls", None) or []
# -> [{'name': 'search', 'args': {'query': 'Bengaluru weather now'}, ...}]
# on msg [1]; [] on HumanMessage, ToolMessage, and final AIMessage
if tool_calls:
# One AIMessage can request multiple tools in parallel, so iterate over all.
for call in tool_calls:
print(
f" [{index}] {kind}: 🛠 tool call → {call['name']}({_one_line(call['args'], 120)})"
)
elif kind == "ToolMessage":
# ToolMessages pair the tool's name with the raw payload returned to the LLM.
print(f" [{index}] {kind}: ({message.name}) {_one_line(message.text)}")
else:
print(f" [{index}] {kind}: {_one_line(message.text)}")
# Once the LLM stops requesting tools, the final entry in `messages` is its answer.
print("\nFINAL ANSWER:")
print(messages[-1].text)
# ↑ Example:
# result = agent.invoke({"messages": [HumanMessage(content="What's the weather like in Bengaluru right now?")]})
# print_agent_trace(result)
# → prints the 4-line trail shown in the module docstring, then the final answer.
>>> from agent_trace_printer import print_agent_trace
>>> print_agent_trace(result)
The agent produced 4 messages:
[0] HumanMessage: What's the weather like in Bengaluru right now?
[1] AIMessage: 🛠 tool call → search({'query': 'Bengaluru weather now'})
[2] ToolMessage: (search) Bengaluru right now: 24°C, light drizzle, humidity 78%
[3] AIMessage: It's about 24°C in Bengaluru right now, with light drizzle and 78% humidity — keep an umbrella handy!
FINAL ANSWER:
It's about 24°C in Bengaluru right now, with light drizzle and 78% humidity — keep an umbrella handy!
Live Web Search & Parallel Tool Calling#
Revision Notes#
Reference file: 02_agent_with_tavily_sdk_tool.py (requires OPENAI_API_KEY + TAVILY_API_KEY)
Concept#
Because the agent only interacts with tools through their schema and return value, upgrading from a fake placeholder to real live web search (tavily-python) changes only the body of the tool function — create_agent(model, tools), the tool name, and the docstring remain identical.
Key Mental Models#
- Decoupled agent architecture: Your agent loop does not care whether a tool returns a hardcoded string, calls a REST API, queries SQL, or searches the web.
- Automatic serialization of structured tool returns: Returning a JSON-serializable
dict(e.g., Tavily's list of search results withtitle,url,content, andscore) is automatically serialized into text inside theToolMessageso the LLM can read and synthesize it. - Parallel tool calls: For broader questions (like finding 3 upcoming developer meetups), modern LLMs often emit multiple tool calls inside a single
AIMessage(e.g., issuing two complementary search queries at once). LangChain executes all of them and appends aToolMessagefor each before the LLM writes its final answer.
For broad research questions, modern LLMs emit multiple tool_calls inside a single AIMessage; LangChain executes every search concurrently, appends one ToolMessage per call, and lets the model synthesize a deduplicated answer in the next turn.
Code Reference#
"""
===============================================================================
Future with Shivank — AI Harness
Section 2 · Script 02 · Give the agent REAL web search (your own Tavily tool)
===============================================================================
WHAT THIS FILE TEACHES
----------------------
Same agent as Script 01. The ONLY change is the inside of the `search` tool:
instead of a hard-coded string it now calls Tavily, a search API built for
LLMs (free tier: 1,000 credits/month at https://app.tavily.com).
Script 01: return "Bengaluru right now: 24°C, light drizzle, ..."
Script 02: return tavily.search(query=query) ← real internet results
This is "writing your own tool around a vendor SDK". In Script 03 we replace
our hand-written tool with the vendor's ready-made LangChain tool and compare.
PREREQUISITES (.env)
--------------------
OPENAI_API_KEY=sk-...
TAVILY_API_KEY=tvly-... ← must be EXACTLY this name; the SDK looks it up
HOW TO RUN
----------
# default question (meetups — the agent may search several times)
uv run python 02_agent_with_tavily_sdk_tool.py
# any question you like, e.g. the weather question from Script 01
uv run python 02_agent_with_tavily_sdk_tool.py "What's the weather like in Bengaluru right now?"
EXPECTED OUTPUT (sample — live web results change every day)
------------------------------------------------------------
Hello from Future with Shivank — AI Harness!
Question: Find 3 upcoming AI or developer meetups in Bengaluru and give the date, venue and a link for each.
🔎 search tool called with: upcoming AI meetups Bengaluru
🔎 search tool called with: developer meetups Bangalore this month
... ← the LLM may call the tool several
times IN PARALLEL with different queries
The agent produced 6 messages:
[0] HumanMessage : Find 3 upcoming AI or developer meetups in Bengaluru ...
[1] AIMessage : 🛠 tool call → search({'query': 'upcoming AI meetups Bengaluru'})
[1] AIMessage : 🛠 tool call → search({'query': 'developer meetups Bangalore this month'})
[2] ToolMessage : (search) {"query": "upcoming AI meetups Bengaluru", "results": [{"url": "https://www.meetup.com/...
[3] ToolMessage : (search) {"query": "developer meetups Bangalore this month", "results": [...
...
FINAL ANSWER:
Here are 3 upcoming meetups in Bengaluru:
1) <meetup name> — <date> — <venue> — https://www.meetup.com/...
2) ...
For the weather question you get a live report instead, e.g.
"It's 23°C and partly cloudy in Bengaluru right now (source: ...)".
===============================================================================
"""
# Reads OPENAI_MODEL and verifies TAVILY_API_KEY after load_dotenv() runs.
import os
# ... (see full file: 02_agent_with_tavily_sdk_tool.py)
# Key pattern in the body:
# - Replacing only the body of `@tool def search(query: str)` swaps fake data for
# live Tavily web search while keeping the agent loop and trace printer identical.
$ uv run python 02_agent_with_tavily_sdk_tool.py
Hello from Future with Shivank — AI Harness!
Question: Find 3 upcoming AI or developer meetups in Bengaluru and give the date, venue and a link for each.
🔎 search tool called with: upcoming AI meetups Bengaluru
🔎 search tool called with: developer meetups Bangalore this month
The agent produced 6 messages:
[0] HumanMessage: Find 3 upcoming AI or developer meetups in Bengaluru and give the date, venue and a link for each.
[1] AIMessage: 🛠 tool call → search({'query': 'upcoming AI meetups Bengaluru'})
[1] AIMessage: 🛠 tool call → search({'query': 'developer meetups Bangalore this month'})
[2] ToolMessage: (search) {"query": "upcoming AI meetups Bengaluru", "results": [{"url": "https://www.meetup.com/bengaluru-ai-builders/", ... … (+1840 chars)
[3] ToolMessage: (search) {"query": "developer meetups Bangalore this month", "results": [{"url": "https://lu.ma/bengaluru-dev", ... … (+1620 chars)
[4] AIMessage: Here are 3 upcoming meetups in Bengaluru: 1) Bengaluru AI Builders Night — Sat 14 Jun — Indiranagar, Bengaluru — https://www.meetup.com/bengaluru-ai-builders/ … (+210 chars)
FINAL ANSWER:
Here are 3 upcoming meetups in Bengaluru:
1) Bengaluru AI Builders Night — Sat 14 Jun — Indiranagar, Bengaluru — https://www.meetup.com/bengaluru-ai-builders/
2) Bangalore Python & LLM Hackday — Sun 22 Jun — HSR Layout, Bengaluru — https://lu.ma/bengaluru-dev
3) Cloud Native Bengaluru — Sat 28 Jun — Koramangala, Bengaluru — https://www.meetup.com/cncf-bengaluru/
Custom Wrapper vs. Built-In Vendor Tools#
Revision Notes#
Reference file: 03_agent_with_builtin_tavily_tool.py (requires OPENAI_API_KEY + TAVILY_API_KEY)
Concept#
When integrating a third-party service (like Tavily), you have two options: wrap the raw vendor SDK yourself with @tool, or use the vendor's official LangChain tool (langchain_tavily.TavilySearch). In most cases, the vendor's built-in tool is strictly better.
Trade-Offs: Hand-Written Wrapper vs. Vendor Tool#
- Maintenance & boilerplate:
- A hand-written wrapper requires you to initialize the SDK client, write docstrings, and keep up with vendor API changes.
- A built-in vendor tool (
TavilySearch()) eliminates that boilerplate and is maintained directly by the vendor.
- Schema richness ("bigger menu card" for the LLM):
- A simple custom
search(query: str)tool only lets the model pass a single search string. TavilySearch()exposes rich optional parameters (time_range,topic,search_depth,include_domains,exclude_domains,start_date,end_date) in its schema. Because the LLM sees those options, it can autonomously settime_range='month'for upcoming events without extra prompting.
- A simple custom
- Still controllable in Python: You can lock down defaults when instantiating the vendor tool (e.g., capping
max_results=5). - When to still write a custom
@tool: Use custom wrappers for internal/proprietary APIs, custom business rules, or when you deliberately want to restrict which parameters the LLM is allowed to choose.
Code Reference#
"""
===============================================================================
Future with Shivank — AI Harness
Section 2 · Script 03 · Use the vendor's ready-made LangChain tool (TavilySearch)
===============================================================================
WHAT THIS FILE TEACHES
----------------------
In Script 02 we wrapped the Tavily SDK in our own @tool. Tavily also publishes
an official LangChain integration, `langchain_tavily.TavilySearch`. Using it:
• deletes our custom function — less code for us to maintain;
• gives the LLM a much richer "menu card": besides `query`, the model may set
optional arguments such as `include_domains`, `search_depth`, `time_range`
or `topic`, all documented by the vendor;
• keeps the tool up to date when the vendor's API changes.
Script 02: tools = [search] ← our hand-written tool
Script 03: tools = [TavilySearch()] ← vendor-maintained tool
Rule of thumb: if a well-maintained integration exists, prefer it over writing
your own wrapper.
PREREQUISITES (.env)
--------------------
OPENAI_API_KEY=sk-...
TAVILY_API_KEY=tvly-...
HOW TO RUN
----------
uv run python 03_agent_with_builtin_tavily_tool.py
uv run python 03_agent_with_builtin_tavily_tool.py "Which team won the most recent IPL final?"
EXPECTED OUTPUT (sample — live results change)
----------------------------------------------
Hello from Future with Shivank — AI Harness!
Tool name the LLM sees: tavily_search
Question: Find 3 upcoming AI or developer meetups in Bengaluru and give the date, venue and a link for each.
The agent produced 4 messages:
[0] HumanMessage : Find 3 upcoming AI or developer meetups in Bengaluru ...
[1] AIMessage : 🛠 tool call → tavily_search({'query': 'upcoming AI developer meetups Bengaluru',
'time_range': 'month', 'topic': 'general'})
[2] ToolMessage : (tavily_search) {"query": "upcoming AI developer meetups Bengaluru", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "... Bengaluru | Meetup", ...
[3] AIMessage : Here are 3 upcoming meetups in Bengaluru: ...
FINAL ANSWER:
Here are 3 upcoming meetups in Bengaluru:
1) <meetup name> — <date> — <venue> — https://www.meetup.com/...
2) ...
WHAT TO NOTICE
--------------
The tool is now called `tavily_search`, and the LLM chose EXTRA arguments
(time_range='month', topic='general') on its own, because the vendor's tool
description tells it those options exist. Our own tool in Script 02 only
offered `query`.
===============================================================================
# ... (see full file: 03_agent_with_builtin_tavily_tool.py)
# Key pattern in the body:
# - Vendor-supplied tools expose richer Pydantic argument schemas (`time_range`,
# `topic`, `include_domains`) so the LLM can narrow searches without custom glue code.
$ uv run python 03_agent_with_builtin_tavily_tool.py
Hello from Future with Shivank — AI Harness!
Tool name the LLM sees: tavily_search
Question: Find 3 upcoming AI or developer meetups in Bengaluru and give the date, venue and a link for each.
The agent produced 4 messages:
[0] HumanMessage: Find 3 upcoming AI or developer meetups in Bengaluru and give the date, venue and a link for each.
[1] AIMessage: 🛠 tool call → tavily_search({'query': 'upcoming AI developer meetups Bengaluru', 'time_range': 'month', 'topic': 'general'})
[2] ToolMessage: (tavily_search) {"query": "upcoming AI developer meetups Bengaluru", "follow_up_questions": null, "results": [{"title": "AI Meetups in Bengaluru | Meetup", ... … (+1950 chars)
[3] AIMessage: Here are 3 upcoming meetups in Bengaluru: 1) Bengaluru AI Builders Night — Sat 14 Jun — Indiranagar — https://www.meetup.com/bengaluru-ai-builders/ … (+198 chars)
FINAL ANSWER:
Here are 3 upcoming meetups in Bengaluru:
1) Bengaluru AI Builders Night — Sat 14 Jun — Indiranagar, Bengaluru — https://www.meetup.com/bengaluru-ai-builders/
2) Bangalore Python & LLM Hackday — Sun 22 Jun — HSR Layout, Bengaluru — https://lu.ma/bengaluru-dev
3) Cloud Native Bengaluru — Sat 28 Jun — Koramangala, Bengaluru — https://www.meetup.com/cncf-bengaluru/
Structured Output with Pydantic (`response_format`)#
Revision Notes#
Reference file: 04_agent_with_structured_output.py (requires OPENAI_API_KEY + TAVILY_API_KEY)
Concept#
Free-text answers are great for humans, but fragile for downstream software (rendering UI cards, storing citations in a database, or returning JSON from a backend API). Passing a Pydantic model via response_format=AgentAnswer to create_agent(...) guarantees that the agent returns a validated, typed Python object in result["structured_response"] alongside its normal message trace.
Key Mental Models#
- Schema descriptions are prompt instructions: Class docstrings (
Source,AgentAnswer) and everyField(description=...)are compiled into a JSON schema sent to the LLM, telling it exactly what belongs in each field (e.g., a plain-textanswerplus a list ofsources, each with atitleandhttps://url). - Nested models & safe defaults: Composing models (
sources: list[Source]with a default empty list) gives downstream code strongly typed attributes (source.title,source.url) instead of untyped dictionaries or fragile regex parsing. - Two under-the-hood enforcement strategies: LangChain automatically picks the best strategy for your model (or lets you override it explicitly):
ProviderStrategy(OpenAI, Anthropic, xAI): Uses the provider's native structured-output JSON schema enforcement; the finalAIMessagecontains the schema-compliant JSON.ToolStrategy(models without native structured output): Injects a synthetic final-answer tool whose parameters match your Pydantic schema; the model returns its structured answer by calling that tool.
- Read from
result["structured_response"], never parse raw text: Always consume the validated Pydantic instance directly fromresult["structured_response"](and use.model_dump()if you need a plaindict).
Passing response_format=AgentAnswer guarantees a validated Pydantic instance in result['structured_response']: LangChain uses native provider schema decoding when supported and seamlessly falls back to a synthetic final-answer tool on other models.
Code Reference#
"""
===============================================================================
Future with Shivank — AI Harness
Section 2 · Script 04 · Structured output: make the agent return a Python object
===============================================================================
WHAT THIS FILE TEACHES
----------------------
Free-text answers are great for humans but painful for programs ("which part
of this paragraph is the link?"). With `response_format=<Pydantic model>` the
agent must ALSO return its answer as data that matches a schema we define:
class AgentAnswer(BaseModel):
answer: str
sources: list[Source] # Source = {title: str, url: str}
result["structured_response"]
→ AgentAnswer(answer="...", sources=[Source(title="...", url="https://...")])
Now your code can do `for s in result["structured_response"].sources: ...`
— e.g. show each meetup link as a button in an app — with no parsing at all.
HOW LANGCHAIN ENFORCES THE SCHEMA (two strategies, chosen automatically)
------------------------------------------------------------------------
• ProviderStrategy — the model provider supports native structured output
(OpenAI, Anthropic, xAI ...). LangChain passes the schema to the API and the
provider guarantees the JSON matches it. Used here with OpenAI.
• ToolStrategy — for models without native support. LangChain gives the LLM
one extra "tool" whose arguments ARE the schema and asks it to call that
tool to finish. Same result, different mechanism.
You can force one: response_format=ToolStrategy(AgentAnswer) or
ProviderStrategy(AgentAnswer) (import from langchain.agents.structured_output).
PREREQUISITES (.env)
--------------------
OPENAI_API_KEY=sk-...
TAVILY_API_KEY=tvly-...
HOW TO RUN
----------
uv run python 04_agent_with_structured_output.py
EXPECTED OUTPUT (sample — live results change)
----------------------------------------------
Hello from Future with Shivank — AI Harness!
... (message trail as in Script 03) ...
============================================================
STRUCTURED RESPONSE
============================================================
type: AgentAnswer
answer:
Here are 3 upcoming meetups in Bengaluru:
1) <meetup name> — <date> — <venue>
2) ...
sources (3):
- <meetup 1 title>
https://www.meetup.com/...
# ... (see full file: 04_agent_with_structured_output.py)
# Key pattern in the body:
# - Passing `response_format=AgentAnswer` to `create_agent(...)` guarantees a
# validated Pydantic instance under `result["structured_response"]`, eliminating
# fragile regex or JSON string parsing in downstream application code.
$ uv run python 04_agent_with_structured_output.py
Hello from Future with Shivank — AI Harness!
... (message trail as in Script 03) ...
============================================================
STRUCTURED RESPONSE
============================================================
type: AgentAnswer
answer:
Here are 3 upcoming meetups in Bengaluru:
1) Bengaluru AI Builders Night — Sat 14 Jun — Indiranagar
2) Bangalore Python & LLM Hackday — Sun 22 Jun — HSR Layout
3) Cloud Native Bengaluru — Sat 28 Jun — Koramangala
sources (3):
- Bengaluru AI Builders Night | Meetup
https://www.meetup.com/bengaluru-ai-builders/
- Bangalore Python & LLM Hackday | Luma
https://lu.ma/bengaluru-dev
- Cloud Native Bengaluru | Meetup
https://www.meetup.com/cncf-bengaluru/
How All Building Blocks Connect#
Revision Notes#
Each script in 03-ai-harness introduces exactly one new concept on top of the previous one:
- Script 01 (
01_agent_with_placeholder_tool.py): Establishes the core ReAct loop (HumanMessage→AIMessagetool call →ToolMessage→ finalAIMessage) with@toolandcreate_agent(model, tools). - Script 02 (
02_agent_with_tavily_sdk_tool.py): Swaps the fake tool body for live web search viatavily-python, introducing real-world data and parallel tool calls without changing the agent loop. - Script 03 (
03_agent_with_builtin_tavily_tool.py): Replaces the hand-written wrapper with the vendor'sTavilySearch()tool, giving the LLM a richer parameter schema with less code to maintain. - Script 04 (
04_agent_with_structured_output.py): Addsresponse_format=AgentAnswerso the agent produces a validated Pydantic object (result["structured_response"]) ready for real applications. - Observability (
agent_trace_printer.py+ LangSmith): Gives both concise terminal traces and full visual LangSmith timelines of every model decision and tool execution.
Quick Self-Check Questions#
Self-Check Questions#
Does the LLM actually run the Python code inside a @tool function?
No. The LLM only outputs an AIMessage containing a structured tool_calls request (name + arguments). LangChain executes the Python function and passes the output back as a ToolMessage.
What three pieces of information does @tool send to the LLM so it knows when and how to call a function?
The function name, type hints, and docstring.
Why might a single AIMessage trigger multiple tool calls at the same step?
Modern LLMs support parallel tool calling, emitting multiple entries in AIMessage.tool_calls to gather information concurrently in one turn.
Why is an official vendor tool like TavilySearch() usually better than a custom search(query: str) wrapper?
It removes wrapper maintenance and exposes a much richer parameter schema (time_range, topic, search_depth, domain filters) that the LLM can leverage autonomously.
What is the difference between ProviderStrategy and ToolStrategy for response_format?
ProviderStrategy uses native provider-side JSON schema enforcement, while ToolStrategy emulates structured output on models without native support by registering a schema-typed tool for the final answer.
Where should application code read the validated Pydantic object from when response_format is enabled?
From result["structured_response"] — never by manually parsing result["messages"][-1].text.