Lesson · 40 min · Free
AI Agents with LangChain: Architectures & Prompts
AI Agents with LangChain: Architectures & Prompts Traditional language model applications answer a single question and stop. An AI agent , by contrast, is a system in which the language model acts as a reasoning engi
AI Agents with LangChain: Architectures & Prompts
Traditional language model applications answer a single question and stop. An AI agent , by contrast, is a system in which the language model acts as a reasoning engine that decides what to do next : it can call tools (a drug database, a calculator, a literature search API), observe the results, and iterate until it produces a final answer. For pharmacy and biotech applications—where a question like "Which of these five compounds has the best predicted oral bioavailability?" may require multiple lookups and calculations—this iterative loop is what transforms a chatbot into a useful scientific assistant. The most common agent architecture is the ReAct pattern (Reason + Act). On each cycle, the model produces a thought explaining its reasoning, an action naming a tool to invoke, and an action input . The runtime executes the tool and feeds the observation back into the model's context. This loop repeats until the model emits a final answer . LangChain implements this pattern through agent executors, and recent versions encourage a cleaner abstraction: the language model itself decides when to call tools using structured tool calling , rather than parsing free-text instructions. Prompt engineering is central to reliable agent behavior. An agent's system prompt must define its role, describe each tool precisely (including units, expected input formats, and when not to use it), and constrain the output format. In biomedical settings, prompts should also enforce safety guardrails: the agent should cite its sources, avoid clinical recommendations beyond its data, and state uncertainty explicitly. A poorly specified tool description is the most common cause of agents calling the wrong function or hallucinating parameters. The first example below builds a minimal tool-calling agent with two domain-specific tools: a molecular weight calculator and a lookup of FDA approval status. The second example shows the system prompt template that governs the agent's behavior—demonstrating how role, tool policy, and safety constraints are encoded as text. from langchain_core.tools import tool from langchain_openai import ChatOpenAI from langgraph.prebuilt import create_react_agent @tool def molecular_weight(smiles: str) -> float: """Return the molecular weight (g/mol) of a compound given its SMILES string. Use for any question about compound size or mass properties.""" # In production, call RDKit: Chem.Descriptors.MolWt(...) MOCK_DB = {"CC(=O)Oc1ccccc1C(=O)O": 180.16} return MOCK_DB.get(smiles, -1.0) @tool def fda_status(drug_name: str) -> str: """Look up the FDA approval status of a drug by its generic name. Returns 'approved', 'withdrawn', or 'not found'. Do not guess statuses not returned here.""" MOCK_DB = {"aspirin": "approved", "troglitazone": "withdrawn"} return MOCK_DB.get(drug_name.lower(), "not found") llm = ChatOpenAI(model="gpt-4o-mini", temperature=0) agent = create_react_agent( llm, tools=[molecular_weight, fda_status], ) result = agent.invoke({ "messages": [{"role": "user", "content": "Is aspirin FDA-approved, and what is its molecular weight?"}] }) print(result["messages"][-1].content) Notice two prompt-level details in the tool definitions above: each docstring states the units (g/mol) and an explicit rule about when the tool applies ("Do not guess statuses not returned here"). These short sentences dramatically reduce hallucinated tool calls. The next example shows a full system prompt for a biotech analysis agent, injected via LangChain's prompt templating. from langchain_core.prompts import ChatPromptTemplate SYSTEM_PROMPT = """You are a pharmaceutical research assistant. ROLE: - Answer questions about drugs, compounds, and clinical data using ONLY the tools provided. TOOL POLICY: - Use `fda_status` for any regulatory question. Never state an approval status from memory. - Use `molecular_weight` for mass-related properties. - If a tool returns 'not found', say so explicitly rather than estimating. SAFETY CONSTRAINTS: - Never provide dosing advice or treatment recommendations. - Cite which tool provided each fact in your answer. - If information is insufficient, state what is missing. Respond concisely in plain language suitable for upper-level pharmacy students.""" prompt = ChatPromptTemplate.from_messages([ ("system", SYSTEM_PROMPT), ("placeholder", "{messages}"), ]) agent = create_react_agent(llm, tools=[molecular_weight, fda_status], prompt=prompt) Key design principles to remember: keep temperature at or near 0 for deterministic tool selection; write tool docstrings as if writing documentation for a new lab technician; limit the number of tools (more than roughly 10–15 degrades routing accuracy); and always log the intermediate thought/action/observation steps so you can audit why the agent reached a conclusion—an essential practice in regulated biomedical environments. Agents vs. chains: chains follow a fixed path; agents let the LLM choose the sequence of tool calls dynamically. ReAct loop: the agent alternates reasoning (thought), tool invocation (action), and result ingestion (observation) until a final answer emerges. Tool descriptions are prompts: units, input formats, and usage boundaries belong in every tool's docstring. Safety by prompt: biomedical agents should be instructed to cite tool sources, refuse clinical advice, and report missing data honestly. Auditability: low temperature and logged intermediate steps make agent decisions reproducible and reviewable. Practice exercise: Extend the code above with a third tool called half_life(drug_name: str) that returns the elimination half-life in hours from a small mock database of three drugs. Write a docstring that specifies units, instructs the model not to estimate missing values, and clarifies when the tool should be used. Then ask the agent: "What is the half-life of metformin, and is it FDA-approved?" Inspect the intermediate steps and note how many tool calls the agent made and in what order—then revise your docstring if the agent called the tool with incorrect arguments or skipped it when it should have been used.
Watch the full lesson — free
This topic is part of Build & Ship Generative AI Applications, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →