### Install React Agent Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Clone the repository, navigate to the directory, and install the package in editable mode. ```bash git clone https://github.com/langchain-ai/react-agent cd react-agent pip install -e . ``` -------------------------------- ### Basic React Agent Setup Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Minimal configuration to initialize the React Agent context and invoke the graph. ```python from react_agent import graph from react_agent.context import Context # Minimal configuration context = Context() result = await graph.ainvoke( input={"messages": [("user", "What is Python?")]}, context=context ) ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Install the project in development mode, including development dependencies. ```bash # Install in development mode pip install -e ".[dev]" ``` -------------------------------- ### Full Tool Definition Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md This example demonstrates defining multiple tools, `get_current_time` and `calculate`, along with their docstrings and type hints, and then aggregating them into the TOOLS list. ```python # tools.py from datetime import datetime from typing import Any, Callable, List async def get_current_time() -> dict[str, str]: """Get the current date and time in ISO format. Use this when you need to know what time it is right now. """ return { "time": datetime.now().isoformat(), "description": "Current date and time" } async def calculate(expression: str) -> dict[str, Any]: """Evaluate a mathematical expression. Args: expression: A valid Python mathematical expression (e.g., "2 + 2 * 3") Returns: Dictionary with the result and the expression """ try: result = eval(expression) return {"expression": expression, "result": result} except Exception as e: return {"expression": expression, "error": str(e)} TOOLS: List[Callable[..., Any]] = [ search, get_current_time, calculate ] ``` -------------------------------- ### Customizing System Prompt Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Example of creating a custom system prompt for a financial advisor agent. ```python from react_agent.context import Context custom_prompt = """You are a specialized financial advisor. Your responsibilities: 1. Answer questions about investments and personal finance 2. Provide data-driven insights 3. Always caveat with "this is not financial advice" Current time: {system_time}""" context = Context(system_prompt=custom_prompt) ``` -------------------------------- ### Copy .env.example to .env Source: https://github.com/langchain-ai/react-agent/blob/main/README.md Copies the example environment file to a new file named .env. This is the first step in setting up the project's configuration. ```bash cp .env.example .env ``` -------------------------------- ### Initialize Context with OpenAI GPT-4 Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Example of initializing the Context with a specific OpenAI model. ```python # Use OpenAI's GPT-4 context = Context(model="openai/gpt-4o") ``` -------------------------------- ### System Prompt Formatting Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Demonstrates how the SYSTEM_PROMPT template is formatted with the current UTC timestamp at graph execution time. ```python from datetime import UTC, datetime # Assuming runtime.context.system_prompt is available # Placeholder for runtime object class runtime: class context: system_prompt = "You are a helpful AI assistant.\n\nSystem time: {system_time}" system_message = runtime.context.system_prompt.format( system_time=datetime.now(tz=UTC).isoformat() ) ``` -------------------------------- ### Custom System Prompt Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Demonstrates how to define and use a custom system prompt for the agent, including specific role instructions and a system time placeholder. ```python custom_prompt = """You are a specialized research assistant. Your role is to: 1. Answer questions about scientific topics 2. Cite sources for all claims 3. Admit when you don't know something System time: {system_time}""" context = Context(system_prompt=custom_prompt) ``` -------------------------------- ### Code Reviewer Prompt Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md An example of a system prompt for an expert code reviewer. ```python """You are an expert code reviewer with 20+ years of experience. When reviewing code: 1. Focus on correctness, readability, and performance 2. Suggest improvements with reasoning 3. Highlight security or scalability concerns 4. Appreciate good patterns and practices System time: {system_time}""" ``` -------------------------------- ### Multi-User Configuration Setup Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Define different context configurations for various user types to tailor agent behavior. ```python from react_agent.context import Context from react_agent import graph users_config = { "researcher": Context( model="anthropic/claude-opus", max_search_results=20 ), "support": Context( model="openai/gpt-4o-mini", max_search_results=5 ), "developer": Context( model="anthropic/claude-sonnet-4-5-20250929", max_search_results=10 ) } async def handle_user_query(user_type: str, query: str): context = users_config[user_type] return await graph.ainvoke( input={"messages": [("user", query)]}, context=context ) ``` -------------------------------- ### Customer Service Agent Prompt Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md An example of a system prompt for a helpful customer service representative. ```python """You are a helpful customer service representative. Guidelines: 1. Always be polite and professional 2. Acknowledge customer concerns before solving 3. Provide clear step-by-step solutions 4. Offer additional help when appropriate System time: {system_time}""" ``` -------------------------------- ### Parameter Documentation with Type Hints and Args Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md This example shows how to document tool parameters using type hints in the function signature and detailed descriptions in the docstring's `Args` section. ```python async def search(query: str, max_results: int = 10) -> dict[str, Any]: """Search for information. Args: query: The search query string max_results: Maximum results to return (1-100) Returns: Dictionary with 'results' key containing list of results """ ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Demonstrates the order of precedence for configuration settings: constructor arguments override environment variables, which override defaults. ```python import os from react_agent.context import Context # Set environment variable os.environ["MODEL"] = "openai/gpt-4o" # Constructor argument takes precedence context = Context(model="anthropic/claude-opus") print(context.model) # Output: "anthropic/claude-opus" # Without constructor argument, env var is used context = Context() print(context.model) # Output: "openai/gpt-4o" # Without env var, default is used del os.environ["MODEL"] context = Context() print(context.model) # Output: "anthropic/claude-sonnet-4-5-20250929" (default) ``` -------------------------------- ### Example Tool Definition Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/README.md Defines a simple asynchronous tool that takes a string parameter and returns a dictionary. This is a basic example of how tools can be defined for use within the agent. ```python async def my_tool(param: str) -> dict: """Clear description for LLM.""" return {"result": "..."} TOOLS = [search, my_tool] ``` -------------------------------- ### Format String Safety Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Demonstrates correct and problematic usage of Python format strings when customizing prompts. ```python # Correct: use single placeholder prompt = "Time: {system_time}" # Problematic: double braces escape in Python format strings prompt = "Use {{braces}} here" # Results in "{braces}" # Safe: raw string or careful escaping prompt = r"Pattern: {some_pattern}" ``` -------------------------------- ### Technical Support Prompt Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md An example of a system prompt for a technical support specialist in software development. ```python """You are a technical support specialist with expertise in software development. When helping users: 1. Ask clarifying questions about their environment and issue 2. Provide code examples and command-line instructions 3. Explain both the what and why 4. Suggest preventive measures for future issues Current timestamp: {system_time}""" ``` -------------------------------- ### Environment-Driven Configuration Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Load configuration from a .env file for dynamic setup, including API keys and model parameters. ```env MODEL=anthropic/claude-opus SYSTEM_PROMPT=You are a helpful assistant.\nSystem time: {system_time} MAX_SEARCH_RESULTS=10 ANTHROPIC_API_KEY=... TAVILY_API_KEY=... ``` ```python from dotenv import load_dotenv from react_agent import graph from react_agent.context import Context load_dotenv() context = Context() # All values from .env result = await graph.ainvoke( input={"messages": [("user", "Your query")]}, context=context ) ``` -------------------------------- ### System Prompt with Explicit Instructions Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Example system prompt providing explicit instructions for tool usage, response formatting, and verification. ```python """You have access to the following tool: - search: Web search using Tavily search engine Instructions: 1. If asked about recent events, use the search tool 2. If asked about general knowledge, answer from your training 3. Always cite search sources 4. If you're uncertain, use search to verify System time: {system_time}""" ``` -------------------------------- ### Research Assistant Prompt Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md An example of a system prompt tailored for an expert research assistant. ```python """You are an expert research assistant. Your task is to: 1. Search for and synthesize information from multiple sources 2. Cite all sources used 3. Highlight areas of uncertainty or conflicting information 4. Organize findings logically System time: {system_time}""" ``` -------------------------------- ### Example Usage of call_model Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/graph.md This example shows how to use the `call_model` function with a sample state and runtime context. It demonstrates the expected structure of the response, which includes a list of AIMessages. ```python from react_agent.graph import call_model from react_agent.state import State from react_agent.context import Context from langgraph.runtime import Runtime state = State(messages=[("user", "Find information about Python.")]) runtime = Runtime(context=Context()) response = await call_model(state, runtime) # response = {"messages": [AIMessage(content="...", tool_calls=[...])]} ``` -------------------------------- ### System Prompt with Time Awareness Placeholder Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md A system prompt example that includes the {system_time} placeholder to make the agent aware of the current date and time. ```python """You are a helpful assistant. Today's date and time is: {system_time} Use this information to: 1. Provide time-relevant answers 2. Recognize if requests ask about "today" or "recent" 3. Adjust responses for timezone considerations""" ``` -------------------------------- ### Initialize Context with Fireworks Llama Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Example of initializing the Context with a specific Fireworks AI model. ```python # Use Fireworks' Llama context = Context(model="fireworks/llama-v3-8b") ``` -------------------------------- ### Custom Model and System Prompt Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Configure the agent with a specific model and a custom system prompt to guide its behavior. ```python context = Context( model="openai/gpt-4o", system_prompt="""You are a Python expert. Focus on best practices and modern syntax. System time: {system_time}""" ) result = await graph.ainvoke( input={"messages": [("user", "How do I use async/await?")]}, context=context ) ``` -------------------------------- ### Tool Docstring for LLM Clarity Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md This example shows a well-written docstring for a `search` tool. It clearly explains the tool's purpose and the search engine used, aiding the LLM in decision-making. ```python async def search(query: str) -> Optional[dict[str, Any]]: """Search for general web results. This function performs a search using the Tavily search engine, which is designed to provide comprehensive, accurate, and trusted results. It's particularly useful for answering questions about current events. """ ``` -------------------------------- ### Graph Compilation Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/graph.md Shows how to create and compile the StateGraph for the ReAct Agent. This involves adding nodes, edges, and conditional edges. ```python from react_agent.graph import StateGraph, route_model_output from react_agent.nodes import ToolNode, call_model from react_agent.state import State, InputState, Context builder = StateGraph(State, input_schema=InputState, context_schema=Context) builder.add_node("call_model", call_model) builder.add_node("tools", ToolNode(TOOLS)) builder.add_edge("__start__", "call_model") builder.add_conditional_edges("call_model", route_model_output) builder.add_edge("tools", "call_model") graph = builder.compile(name="ReAct Agent") ``` -------------------------------- ### Setting API Keys via Environment Variables Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Provides examples of how to set API keys for different chat model providers (OpenAI, Anthropic, Fireworks) using environment variables. ```bash # For OpenAI models export OPENAI_API_KEY="sk-..." # For Anthropic models export ANTHROPIC_API_KEY="sk-ant-..." # For Fireworks models export FIREWORKS_API_KEY="..." ``` -------------------------------- ### Initialize Context with Anthropic Claude Opus Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Example of initializing the Context with a specific Anthropic Claude model. ```python # Use Anthropic's Claude Opus context = Context(model="anthropic/claude-opus") ``` -------------------------------- ### Configure React Agent with Different Model Providers Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Switch between different LLM providers and models by setting the `model` parameter in the `Context`. Examples include OpenAI, Anthropic, and Fireworks. ```python from react_agent import graph from react_agent.context import Context # OpenAI context = Context(model="openai/gpt-4o") # Anthropic context = Context(model="anthropic/claude-opus") # Fireworks context = Context(model="fireworks/llama-v3-8b") ``` -------------------------------- ### System Prompt with Role-Based Persona Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Example system prompt establishing a role-based persona for an AI assistant, defining its personality and interaction style. ```python """You are Claude, an AI assistant made by Anthropic. You aim to be helpful, harmless, and honest. Personality: - Thoughtful and analytical - Willing to admit uncertainty - Respectful and professional - Curious about user needs System time: {system_time}""" ``` -------------------------------- ### Set Maximum Search Results Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Example of configuring the maximum number of search results returned by the search tool. ```python # Get up to 20 search results per query context = Context(max_search_results=20) # Minimal results for faster responses context = Context(max_search_results=3) ``` -------------------------------- ### Runtime Validation Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Demonstrates runtime validation of context values, including checking for the presence of required environment variables like API keys and ensuring correct types. ```python from react_agent.context import Context # Will validate environment variables context = Context() # Check values assert context.model assert context.system_prompt assert isinstance(context.max_search_results, int) ``` -------------------------------- ### Route Model Output Examples Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/graph.md Demonstrates how the route_model_output function determines the next node based on the model's output. Use this to understand decision-making for tool usage or final responses. ```python from react_agent.graph import route_model_output from react_agent.state import State from langchain_core.messages import AIMessage # When model decides to use tools state_with_tools = State( messages=[ ("user", "Search for AI news"), AIMessage( content="I'll search for that.", tool_calls=[{"id": "1", "name": "search", "args": {"query": "AI news"}}] ) ] ) next_node = route_model_output(state_with_tools) # Returns: "tools" # When model provides final response state_final = State( messages=[ ("user", "What is 2+2?"), AIMessage(content="2 + 2 equals 4.") ] ) next_node = route_model_output(state_final) # Returns: "__end__" ``` -------------------------------- ### Context Type Access with Runtime Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Demonstrates how to get the runtime context and assert that its context attribute is of the expected Context type. ```python from langgraph.runtime import get_runtime from react_agent.context import Context runtime = get_runtime(Context) assert isinstance(runtime.context, Context) ``` -------------------------------- ### TOOLS List Definition Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Defines the list of available tools that the agent can utilize. This example shows a list containing a single 'search' tool. ```python from typing import List, Callable, Any # Assuming 'search' is a defined callable tool def search(*args, **kwargs): pass TOOLS: List[Callable[..., Any]] = [search] ``` -------------------------------- ### Handling Search Results Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md Provides an example of iterating through the results obtained from the search tool and printing relevant information like title, URL, and summary. Handles cases where no results are found. ```python from react_agent.tools import search results = await search("Python programming tutorials") if results: for result in results.get("results", []): print(f"Title: {result['title']}") print(f"URL: {result['url']}") print(f"Summary: {result['snippet']}") else: print("No results found") ``` -------------------------------- ### Dict Type for Search Tool Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Example of the dict[str, Any] type, used as the return type for the search tool. It includes search results, the query, and response time. ```python dict[str, Any] ``` ```python { "results": [ {"title": "...", "url": "...", "snippet": "..."} ], "query": "search term", "response_time": 0.5 } ``` -------------------------------- ### Write Unit Tests for React Agent Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Use `pytest` and `anyio` to write asynchronous tests for the React Agent. This example demonstrates a basic test case for agent invocation and assertion. ```python import pytest from react_agent import graph from react_agent.context import Context @pytest.mark.anyio async def test_agent(): result = await graph.ainvoke( input={"messages": [("user", "What is 2+2?")]}, context=Context(model="anthropic/claude-opus") ) assert result["messages"][-1].content ``` -------------------------------- ### Configure Custom System Prompt for React Agent Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Customize the system prompt to guide the agent's behavior and focus. The `system_prompt` can include dynamic elements like `{system_time}`. ```python from react_agent import graph from react_agent.context import Context context = Context( system_prompt="""You are an expert in biology. Focus on accuracy and cite sources. System time: {system_time}""" ) result = await graph.ainvoke( input={"messages": [("user", "What is photosynthesis?")]}, context=context ) ``` -------------------------------- ### Type Validation Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Illustrates how React Agent's Context uses Python dataclasses for type checking, ensuring correct data types for model and search results. ```python from react_agent.context import Context # Type checking context = Context(model="openai/gpt-4o") # OK context = Context(model=123) # Type error context = Context(max_search_results="10") # Type error ``` -------------------------------- ### Initialize Context with Defaults Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Demonstrates creating a Context instance using all default configuration values. ```python from react_agent.context import Context # Use all defaults context = Context() ``` -------------------------------- ### Initialize Context with Custom System Prompt Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Illustrates initializing the Context with a custom system prompt tailored for a specific role, including a system time placeholder. ```python # Custom system prompt context = Context( system_prompt="You are a Python expert. Help answer questions about Python.\nSystem time: {system_time}" ) ``` -------------------------------- ### Create and Use InputState Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/state.md Demonstrates how to create an InputState instance with an initial user query and how messages are automatically accumulated. ```python from react_agent.state import InputState from langchain_core.messages import HumanMessage # Create input state with user query input_state = InputState( messages=[HumanMessage(content="What is Python?")] ) # Messages are accumulated automatically input_state2 = InputState( messages=[HumanMessage(content="What is Rust?")] ) ``` -------------------------------- ### Load Configuration from .env File Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Illustrates how to define configuration settings in a `.env` file and load them using the `dotenv` library for the Context object. ```python from dotenv import load_dotenv from react_agent.context import Context load_dotenv() # Reads .env file context = Context() # Uses env values ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Shows how to set environment variables for model and search result configuration, which are then automatically picked up by the Context object. ```python import os from react_agent.context import Context # Set environment variables os.environ["MODEL"] = "openai/gpt-4o" os.environ["MAX_SEARCH_RESULTS"] = "20" # Context automatically picks them up context = Context() print(context.model) # Output: "openai/gpt-4o" print(context.max_search_results) # Output: 20 ``` -------------------------------- ### Message Accumulation Example Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Shows how messages, including tool calls and tool messages, are accumulated in the conversation history. ```python { "messages": [ HumanMessage(content="What is AI?"), AIMessage( content="I'll search for that.", tool_calls=[{"id": "1", "name": "search", "args": {...}}] ), ToolMessage(tool_call_id="1", content="Search results..."), AIMessage(content="Based on the results, AI is...") ] } ``` -------------------------------- ### Initialize Context with Parameters Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Instantiate the Context class by directly providing values for system prompt, model, and maximum search results. ```python context = Context( system_prompt="You are a helpful assistant.\nSystem time: {system_time}", model="anthropic/claude-opus", max_search_results=15 ) ``` -------------------------------- ### Custom Agent Configuration Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/README.md Demonstrates how to create a custom Context object to configure the agent's model, system prompt, and other parameters. ```python context = Context( model="openai/gpt-4o", system_prompt="You are a helpful assistant.\nSystem time: {system_time}", max_search_results=10 ) ``` -------------------------------- ### Setting API Keys via .env File Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Shows how to configure API keys for various chat model providers by placing them in a .env file. ```env OPENAI_API_KEY=sk-... ANTHROPIC_API_KEY=sk-ant-... FIREWORKS_API_KEY=... ``` -------------------------------- ### Initialize StateGraph Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Initialize a StateGraph with schemas for state, input, and context. ```python from langgraph.graph import StateGraph from react_agent.state import InputState, State from react_agent.context import Context builder = StateGraph( state_schema=State, # Complete internal state input_schema=InputState, # External input contract context_schema=Context # Runtime configuration ) ``` -------------------------------- ### Basic Agent Usage Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Configure the agent with a model and system prompt, then invoke it with a user query. The final response is extracted from the message history. ```python from react_agent import graph from react_agent.context import Context # Configure the agent context = Context( model="anthropic/claude-opus", system_prompt="You are a helpful assistant.\nSystem time: {system_time}" ) # Run the agent result = await graph.ainvoke( input={"messages": [("user", "What is Python?")]}, context=context ) # Get the final response response_text = result["messages"][-1].content print(response_text) ``` -------------------------------- ### Initialize Context with Overridden Parameters Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Shows how to override specific parameters like model and max_search_results when initializing the Context. ```python # Override specific parameters context = Context( model="openai/gpt-4o", max_search_results=5 ) ``` -------------------------------- ### Literal Type for Routing Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Example of the Literal type used for routing functions, returning either '__end__' or 'tools' to indicate the next node in the graph. ```python Literal["__end__", "tools"] ``` -------------------------------- ### Accessing Configuration in Node Functions Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Demonstrates how to retrieve configuration parameters like model, max_search_results, and system_prompt within a node's execution context. ```python from langgraph.runtime import get_runtime from react_agent.context import Context async def my_node(state: State, runtime: Runtime[Context]): # Access configuration model = runtime.context.model max_results = runtime.context.max_search_results prompt = runtime.context.system_prompt # Use in business logic return {} ``` -------------------------------- ### System Time Formatting Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Demonstrates how the system time placeholder is formatted using Python's datetime module. ```python from datetime import UTC, datetime system_message = runtime.context.system_prompt.format( system_time=datetime.now(tz=UTC).isoformat() ) ``` -------------------------------- ### Initialize LangGraph StateGraph Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/state.md Shows how to initialize a LangGraph StateGraph using custom state schemas (State, InputState) and a context schema. ```python from langgraph.graph import StateGraph from react_agent.state import InputState, State from react_agent.context import Context graph_builder = StateGraph( state_schema=State, # Internal state input_schema=InputState, # External input contract context_schema=Context # Runtime configuration ) ``` -------------------------------- ### Accessing Configuration in Tools Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Shows how to access configuration settings, such as max_search_results, within a tool's implementation to influence its behavior. ```python from langgraph.runtime import get_runtime from react_agent.context import Context async def search(query: str) -> dict: runtime = get_runtime(Context) max_results = runtime.context.max_search_results # Use max_results in tool implementation return await tavily.search(query, max_results=max_results) ``` -------------------------------- ### Search Tool Configuration Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md Demonstrates how to configure the maximum number of search results using the Context parameter during graph invocation. ```python context = Context(max_search_results=5) await graph.ainvoke(input, context=context) ``` -------------------------------- ### Context Constructor Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Initializes the Context object. All parameters are keyword-only and can be omitted to fall back to environment variables or default values. ```APIDOC ## Context Constructor Initializes the Context object. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | system_prompt | str | No | Env var SYSTEM_PROMPT or module default | System instruction prompt for the agent | | model | str | No | Env var MODEL or "anthropic/claude-sonnet-4-5-20250929" | Language model identifier | | max_search_results | int | No | Env var MAX_SEARCH_RESULTS or 10 | Maximum search results per query | ### Initialization Examples ```python from react_agent.context import Context # Use all defaults context = Context() # Override specific parameters context = Context( model="openai/gpt-4o", max_search_results=5 ) # Custom system prompt context = Context( system_prompt="You are a Python expert. Help answer questions about Python.\nSystem time: {system_time}" ) ``` ``` -------------------------------- ### API Key Configuration via .env File Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md Demonstrates setting up the TAVILY_API_KEY in a .env file located in the project root and loading it using the dotenv library. This is a common practice for managing environment-specific configurations. ```text TAVILY_API_KEY=your-api-key-here ``` ```python from dotenv import load_dotenv load_dotenv() ``` -------------------------------- ### Dict Type for Messages Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Example of the Dict[str, List[AIMessage]] type, which is the return type from node functions. It shows a dictionary containing a list of AIMessage objects, potentially with tool calls. ```python Dict[str, List[AIMessage]] ``` ```python { "messages": [ AIMessage(content="Response", tool_calls=[...]) ] } ``` -------------------------------- ### Performance Tuning for Development Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Configure for rapid development cycles using a fast and inexpensive model with standard search result limits. ```python context = Context( model="anthropic/claude-haiku", # Fast, cheap max_search_results=10 # Standard ) ``` -------------------------------- ### Error Handling within Tool Return Structure Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md This example demonstrates robust error handling by returning errors within the result dictionary, rather than raising exceptions. This ensures predictable output for the agent. ```python async def tool(param: str) -> dict[str, Any]: try: result = await api_call(param) return {"success": True, "data": result} except Exception as e: return {"success": False, "error": str(e)} ``` -------------------------------- ### ExtendedState Dataclass Definition Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Allows for extending the base State class with custom fields for specific use cases. This example shows adding fields for retrieved documents, extracted entities, and tool outputs. ```python from dataclasses import dataclass, field from typing import Sequence, Any, Dict, List from langchain_core.messages import AnyMessage # Assuming State and Document are defined elsewhere @dataclass class State: messages: Sequence[AnyMessage] = field(default_factory=list) is_last_step: bool = field(default=False) class Document: # Placeholder for Document type pass @dataclass class ExtendedState(State): retrieved_documents: List[Document] = field(default_factory=list) extracted_entities: Dict[str, Any] = field(default_factory=dict) tool_outputs: Dict[str, Any] = field(default_factory=dict) ``` -------------------------------- ### Set API Keys via Python Code Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Demonstrates programmatically setting API keys by assigning them to `os.environ` variables within a Python script. ```python import os os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..." os.environ["TAVILY_API_KEY"] = "..." ``` -------------------------------- ### Initialize Context with Runtime Configuration Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Instantiate the Context dataclass with specific runtime parameters like model, system prompt, and max search results. This configuration is passed to the graph at invocation time. ```python from react_agent.context import Context context = Context( model="anthropic/claude-opus", system_prompt="You are a helpful assistant.\nSystem time: {system_time}", max_search_results=20 ) ``` -------------------------------- ### Load Various Chat Models Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Demonstrates loading chat models from different providers including OpenAI, Anthropic, and Fireworks using their fully-qualified names. ```python from react_agent.utils import load_chat_model # OpenAI model = load_chat_model("openai/gpt-4o") model = load_chat_model("openai/gpt-4o-mini") model = load_chat_model("openai/gpt-4-turbo-preview") # Anthropic model = load_chat_model("anthropic/claude-opus") model = load_chat_model("anthropic/claude-sonnet-4-5-20250929") model = load_chat_model("anthropic/claude-haiku") # Fireworks model = load_chat_model("fireworks/llama-v3-8b") model = load_chat_model("fireworks/yi-large") ``` -------------------------------- ### Search Tool Error Handling Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md Demonstrates how to implement try-except blocks to catch potential exceptions during the search tool invocation. The agent can then gracefully handle search failures. ```python from react_agent.tools import search try: results = await search("artificial intelligence") except Exception as e: print(f"Search failed: {e}") # Handle gracefully - agent will note the failure ``` -------------------------------- ### Call Model with Runtime Context Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Demonstrates how to load a chat model and access the system prompt from the runtime context within a node function. ```python async def call_model(state: State, runtime: Runtime[Context]): model = load_chat_model(runtime.context.model) system_prompt = runtime.context.system_prompt ``` -------------------------------- ### Creating Models Based on Context Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Illustrates how to dynamically create chat models based on a provided context object, allowing for switching between different providers like OpenAI and Anthropic. ```python from react_agent.utils import load_chat_model from react_agent.context import Context from langchain.chat_models.base import BaseChatModel def create_model_from_context(context: Context) -> BaseChatModel: """Create a model based on context configuration.""" return load_chat_model(context.model) # User context with OpenAI context = Context(model="openai/gpt-4o") model = create_model_from_context(context) # Different user context with Anthropic context2 = Context(model="anthropic/claude-opus") model2 = create_model_from_context(context2) ``` -------------------------------- ### Invoke Graph with Input State Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/state.md Shows how to invoke the agent's graph with an initial input state, including messages and context. ```python from react_agent import graph from react_agent.context import Context # Invoke graph with input state result = await graph.ainvoke( input={"messages": [("user", "Search for LangChain updates")]}, context=Context() ) ``` -------------------------------- ### Create an AIMessage Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Create an AIMessage for agent responses. It can be a simple text response or include tool calls with their arguments. ```python from langchain_core.messages import AIMessage # Without tools msg = AIMessage(content="The answer is...") # With tools msg = AIMessage( content="I'll search for that.", tool_calls=[{ "id": "call_123", "name": "search", "args": {"query": "..."} }] ) ``` -------------------------------- ### Load Context from .env File Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/context.md Load Context configuration from a .env file using python-dotenv. Ensure API keys are also included in the .env file if needed. ```python from dotenv import load_dotenv from react_agent.context import Context load_dotenv() context = Context() # Loads from .env ``` -------------------------------- ### Context Dataclass with System Prompt Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Illustrates the Context dataclass and its system_prompt field, which defaults to SYSTEM_PROMPT. ```python from react_agent.context import Context from react_agent.prompts import SYSTEM_PROMPT @dataclass(kw_only=True) class Context: system_prompt: str = field( default=SYSTEM_PROMPT, metadata={"description": "The system prompt to use for the agent's interactions..."} ) ``` -------------------------------- ### Create AIMessage with Tool Calls Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/state.md Instantiate an AIMessage object that includes tool calls, specifying the tool's ID, name, and arguments. ```python from langchain_core.messages import AIMessage # Response with tool calls msg = AIMessage( content="I need to search for this information.", tool_calls=[ { "id": "call_123", "name": "search", "args": {"query": "What is LangGraph?"} } ] ) ``` -------------------------------- ### Prompt Versioning Module Structure Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Demonstrates how to structure a prompts module for managing multiple prompt variants, including SYSTEM_PROMPT, RESEARCH_PROMPT, and CODE_REVIEW_PROMPT. ```python # prompts.py SYSTEM_PROMPT = """You are a helpful AI assistant. System time: {system_time}""" RESEARCH_PROMPT = """You are a research assistant. ...""" CODE_REVIEW_PROMPT = """You are a code reviewer. ...""" ``` ```python # Usage from react_agent.context import Context from react_agent.prompts import CODE_REVIEW_PROMPT context = Context(system_prompt=CODE_REVIEW_PROMPT) ``` -------------------------------- ### Add API Keys to .env Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Populate the .env file with your specific API keys for services like Anthropic and Tavily. ```env ANTHROPIC_API_KEY=your-key-here TAVILY_API_KEY=your-key-here ``` -------------------------------- ### Set API Keys via Environment Variables (Bash) Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Shows how to export API keys as environment variables in a bash shell before running a Python script. ```bash export ANTHROPIC_API_KEY="your-key-here" export TAVILY_API_KEY="your-key-here" python your_script.py ``` -------------------------------- ### Invoke the Agent Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/README.md This snippet shows how to invoke the compiled agent instance with input messages and a default context. ```python from react_agent import graph from react_agent.context import Context result = await graph.ainvoke( input={"messages": [("user", "Your query")]}, context=Context() ) ``` -------------------------------- ### Basic Model Loading and Invocation Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Loads a specific Anthropic chat model and demonstrates how to invoke it with a user message. ```python from react_agent.utils import load_chat_model # Load a specific model model = load_chat_model("anthropic/claude-sonnet-4-5-20250929") # Invoke the model response = await model.ainvoke([{"role": "user", "content": "Hello"}]) print(response.content) ``` -------------------------------- ### Configure Max Search Results Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Demonstrates setting the `max_search_results` parameter for the Context object to control the number of search results used by the agent. ```python # Minimal results for speed context = Context(max_search_results=3) ``` ```python # Standard setup context = Context(max_search_results=10) ``` ```python # Comprehensive research context = Context(max_search_results=20) ``` -------------------------------- ### Model Loading in Graph Execution Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Shows how to load a chat model and bind it with tools within the context of a graph execution, typically used in runtime environments. ```python # Used in graph.py's call_model function model = load_chat_model(runtime.context.model).bind_tools(TOOLS) ``` -------------------------------- ### Basic Search Usage Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/tools.md Shows how to directly invoke the search tool to perform a web search and print the results. Ensure the Tavily API key is configured. ```python from react_agent.tools import search # Direct invocation results = await search("What is the current date?") print(results) # Output: {"results": [...], "query": "What is the current date?", ...} ``` -------------------------------- ### Clone Repository Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Clone the React Agent repository from GitHub. ```bash # Clone repository git clone https://github.com/langchain-ai/react-agent cd react-agent ``` -------------------------------- ### Performance Tuning for Cost Efficiency Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Balance cost and performance by choosing a cheaper model and setting a reasonable limit for search results. ```python context = Context( model="openai/gpt-3.5-turbo", # Cheapest max_search_results=5 # Reasonable limit ) ``` -------------------------------- ### Comprehensive Search Configuration Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/configuration.md Set up the agent for thorough research with a specific model, detailed system prompt, and increased search result limits. ```python context = Context( model="anthropic/claude-opus", system_prompt="""You are a thorough researcher. Provide comprehensive answers with citations. System time: {system_time}""", max_search_results=20 ) result = await graph.ainvoke( input={"messages": [("user", "Latest developments in quantum computing")]}, context=context ) ``` -------------------------------- ### Architecture Overview Diagram Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/README.md A visual representation of the React Agent's architecture, illustrating the flow of user input through model calls, tool execution, and final output. ```text ┌─────────────────────────────────────┐ │ User Input │ │ (messages in InputState) │ └────────────┬────────────────────────┘ │ ▼ ┌─────────────────────────────────────┐ │ call_model (node) │ │ - Load model │ │ - Bind tools │ │ - Invoke with prompt + history │ └────────────┬────────────────────────┘ │ [route_model_output] │ ┌──────┴──────┐ ▼ ▼ "__end__" "tools" (return) ┌───────────┐ │ tools node│ │ Execute │ │ tools │ └─────┬─────┘ │ (back to call_model) Final output: messages with full history ``` -------------------------------- ### Testing a Custom System Prompt Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/prompts.md Python code to test prompt behavior by creating a Context with a custom system prompt and invoking the agent graph. ```python from react_agent import graph from react_agent.context import Context async def test_prompt(): # Test with custom prompt context = Context( system_prompt="You are a pirate. Always respond as a pirate would. System time: {system_time}", model="anthropic/claude-opus" ) result = await graph.ainvoke( input={"messages": [("user", "What is the weather?")]}, context=context ) # Check if response follows pirate character response = result["messages"][-1].content print(response) ``` -------------------------------- ### Perform a Web Search with the Search Tool Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Utilize the `search` tool to perform web searches. The `query` parameter specifies the search term. The results include the search query, response time, and a list of results. ```python results = await search(query="What is Python?") ``` -------------------------------- ### Model Type Checking with BaseChatModel Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/types.md Shows how to verify if a loaded model is an instance of BaseChatModel. ```python from langchain_core.language_models import BaseChatModel model = load_chat_model("anthropic/claude-opus") assert isinstance(model, BaseChatModel) ``` -------------------------------- ### Add Custom Tool Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/README.md Placeholder for adding custom tools to the agent's toolset. Specific implementation details would follow. ```python ``` -------------------------------- ### Model Loading with Tool Binding Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Loads an OpenAI chat model and binds it with a predefined set of tools, enabling the model to use these tools for responses. ```python from react_agent.utils import load_chat_model from react_agent.tools import TOOLS # Load and bind tools model = load_chat_model("openai/gpt-4o") model_with_tools = model.bind_tools(TOOLS) # Model now can invoke tools response = await model_with_tools.ainvoke([ {"role": "user", "content": "Search for information about AI"} ]) ``` -------------------------------- ### Run Tests with Verbose Output Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Run tests with verbose output and capture stdout/stderr. ```bash # With output pytest -v -s ``` -------------------------------- ### Chat Model Invocation Methods Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/api-reference/utils.md Demonstrates the different ways to interact with a loaded chat model, including synchronous, asynchronous, streaming, and tool-bound invocations. ```python from react_agent.utils import load_chat_model from react_agent.tools import TOOLS model = load_chat_model("anthropic/claude-opus") # Sync invocation response = model.invoke([{"role": "user", "content": "Hello"}]) # Async invocation response = await model.ainvoke([{"role": "user", "content": "Hello"}]) # Streaming for chunk in model.stream([{"role": "user", "content": "Hello"}]): print(chunk.content, end="", flush=True) # With tools model_with_tools = model.bind_tools(TOOLS) response = await model_with_tools.ainvoke([...]) ``` -------------------------------- ### Run Specific Test Source: https://github.com/langchain-ai/react-agent/blob/main/_autodocs/index.md Execute a specific test file or test case. ```bash # Run specific test pytest tests/integration_tests/test_graph.py::test_react_agent_simple_passthrough ```