ReAct Agent
Reasoning and acting loop with dynamic tool selection, memory integration, and observation feedback.
Reasoning and acting loop with dynamic tool selection, effect-polymorphic tools, persistent conversation memory, and observation feedback.
Key Concepts
- Thought-Action-Observation: Iterative cycle where the LLM reasons about the problem, chooses a tool, executes it, and reflects on the observation.
- Effect-Polymorphic Tools: Tools run natively in the agent’s monad
m(Tool m), supportingExceptT,IO, or custom application transformer stacks. - Conversation Memory: Attach any
BaseMemoryinstance (such asWindowBufferMemoryorTokenBufferMemory) viawithMemory. - Builder-Style Configuration: Configure system prompts, model configs, iteration limits, error recovery strategies, streaming tools (
withStreamingTools), and callbacks using composablewith*combinators. - Real-Time Streaming Agents: Stream LLM text chunks,
ToolCalldeltas, and incrementalToolChunkoutput (StreamingTool,streamingShellTool) in real time withstreamReActAgent,streamReActAgentWithTrace, andrunReActAgentStream. - Full Reasoning Traces: Inspect intermediate reasoning steps, tool actions, and observations via
runReActAgentWithTraceorstreamReActAgentWithTrace.
Working Code Example
Compare local execution via Ollama and cloud API execution via OpenAI / OpenRouter. Use the toggle tabs or the global provider switcher in the header to switch:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Ollama.ReAct (runApp) where
import Control.Monad.Except (runExceptT)
import qualified Data.Text.IO as T
import Langchain.Prelude
import Langchain.Provider.Ollama
runApp :: IO ()
runApp = do
writeFile "/tmp/sample_task.txt" "Production note: Always use secure and tested tools."
o <- newOllama "qwen3.5:2b" defaultConfig
let policy = defaultSecurityPolicy
tools = [readFileTool Nothing policy, findFilesTool policy]
agent = defaultReActAgent o tools
prompt =
[ userMessage
"Read the contents of /tmp/sample_task.txt using read_file, then summarize its note."
]
res <- runExceptT $ runReActAgent agent prompt
case res of
Left err -> T.putStrLn $ errorMessage err
Right msg -> T.putStrLn $ extractMessageText msg{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module OpenAI.ReAct (runApp) where
import Control.Monad.Except (runExceptT)
import qualified Data.Text.IO as T
import Langchain.Prelude
import OpenAI.Common (defaultModelName, getOpenRouterModel)
runApp :: IO ()
runApp = do
writeFile "/tmp/sample_task.txt" "Important production note: Keep tools safe and reliable."
o <- getOpenRouterModel defaultModelName
let policy = defaultSecurityPolicy
tools = [readFileTool Nothing policy, findFilesTool policy]
agent = defaultReActAgent o tools
prompt =
[ userMessage
"Read the contents of /tmp/sample_task.txt using read_file, then summarize its note."
]
res <- runExceptT $ runReActAgent agent prompt
case res of
Left err -> T.putStrLn $ errorMessage err
Right msg -> T.putStrLn $ extractMessageText msgMulti-Turn Conversations with Memory
Attach conversation memory to persist dialogue history across multiple agent invocations:
-- Create sliding window memory
mem <- newWindowBufferMemory 20 []
let agent =
withMemory mem $
withSystemPrompt "You are an expert financial calculation assistant." $
defaultReActAgent model tools
-- First turn: Agent remembers user query and its final answer
res1 <- runExceptT $ runReActAgent agent [userMessage "What is 15% tip on $85?"]
-- Second turn: Agent recalls the previous answer from memory
res2 <- runExceptT $ runReActAgent agent [userMessage "Add that tip to the total bill."]Inspecting Intermediate Traces
Use runReActAgentWithTrace to inspect every tool action and observation in the reasoning chain:
res <- runExceptT $ runReActAgentWithTrace agent [userMessage "Calculate 45 * 12"]
case res of
Left err -> putStrLn $ "Agent error: " ++ show err
Right trace -> do
putStrLn $ "Final Answer: " ++ show (extractMessageText (traceFinalAnswer trace))
putStrLn $ "Total Iterations: " ++ show (length (traceSteps trace))
forM_ (traceSteps trace) $ \(step, obs) -> do
case step of
AgentAction msg calls -> putStrLn $ "Called: " ++ show (map toolCallName calls)
AgentFinish msg -> putStrLn "Finished reasoning"Streaming Execution & StreamingTool
Use withStreamingTools, streamReActAgent, or runReActAgentStream to receive real-time LLMChunk, ToolStart, ToolChunk, and ToolEnd events as the agent thinks and runs tools (such as streamingShellTool):
let sTools = [streamingShellTool defaultSecurityPolicy]
agent = withStreamingTools sTools $ defaultReActAgent model []
res <- runExceptT $ runReActAgentStream agent [userMessage "List files in cwd"] $ \case
LLMChunk _ _ (Just tc) -> liftIO $ putStrLn ("\n[tool_call] " <> show (toolCallName tc))
LLMChunk _ txt Nothing -> liftIO $ T.putStr txt
ToolChunk _ name chunk -> liftIO $ T.putStr ("[" <> name <> "] " <> chunk)
_ -> pure ()Core Types & API
-- | Construct agent with sensible defaults
defaultReActAgent :: model -> [Tool m] -> ReActAgent model m
-- | Builder configuration functions
withMemory :: (BaseMemory mem) => mem -> ReActAgent model m -> ReActAgent model m
withoutMemory :: ReActAgent model m -> ReActAgent model m
withSystemPrompt :: Text -> ReActAgent model m -> ReActAgent model m
withMaxIterations :: Int -> ReActAgent model m -> ReActAgent model m
withModelConfig :: Maybe (ModelConfig model) -> ReActAgent model m -> ReActAgent model m
withCallbackManager :: CallbackManager -> ReActAgent model m -> ReActAgent model m
withStopCondition :: (Message -> Bool) -> ReActAgent model m -> ReActAgent model m
withToolErrorStrategy :: ToolErrorStrategy -> ReActAgent model m -> ReActAgent model m
withStreamingTools :: [StreamingTool m] -> ReActAgent model m -> ReActAgent model m
-- | Agent execution
runReActAgent :: (ToolBinder model m, MonadIO m, MonadError LangchainError m) => ReActAgent model m -> [Message] -> m Message
runReActAgentWithTrace :: (ToolBinder model m, MonadIO m, MonadError LangchainError m) => ReActAgent model m -> [Message] -> m AgentTrace
-- | Streaming execution
reactStepStream :: (ToolBinder model m, MonadIO m, MonadError LangchainError m) => model -> [Tool m] -> [Message] -> Maybe (ModelConfig model) -> ConduitT () StreamEvent m AgentStep
streamReActAgent :: (ToolBinder model m, MonadIO m, MonadError LangchainError m) => ReActAgent model m -> [Message] -> EventStream m
streamReActAgentWithTrace :: (ToolBinder model m, MonadIO m, MonadError LangchainError m) => ReActAgent model m -> [Message] -> ConduitT () StreamEvent m AgentTrace
runReActAgentStream :: (ToolBinder model m, MonadIO m, MonadError LangchainError m) => ReActAgent model m -> [Message] -> (StreamEvent -> m ()) -> m MessageRunning This Example
Local Ollama
Ensure your Ollama daemon is running locally with the target model:
ollama run qwen3.5:2b # or your desired model
stack run reactollamaOpenAI / OpenRouter
Ensure your OPENROUTER_API_KEY or OPENAI_API_KEY is exported:
export OPENROUTER_API_KEY="your-api-key"
stack run reactopenai