npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@lamemind/react-agent-ts

v2.0.4

Published

Streaming ReAct agent in typescript with multiple LLM providers

Readme

@lamemind/react-agent-ts

npm version TypeScript License: ISC

Streaming ReAct agent in TypeScript - bring your own LLM model

A lightweight, streaming-first ReAct (Reasoning + Acting) agent that works with any LangChain-compatible model. Focus on agent logic while LangChain handles the provider complexity.

✨ Features

  • 🔄 Streaming-first: Real-time chunked response processing
  • 🔧 Tool Integration: Seamless function calling with automatic iteration
  • 🎯 Provider Agnostic: Works with any LangChain model (Anthropic, OpenAI, Groq, local, etc.)
  • 💡 Minimal: ~200 LOC focused on ReAct pattern only
  • 🔐 Type Safe: Full TypeScript support with proper interfaces
  • Zero Config: Just pass your model and tools

📦 Installation

npm install @lamemind/react-agent-ts

You'll also need a LangChain model provider:

# Choose your provider
npm install @langchain/anthropic    # for Claude
npm install @langchain/openai       # for GPT
npm install @langchain/google-genai  # for Gemini

🚀 Quick Start

import { ChatAnthropic } from "@langchain/anthropic";
import { ReActAgent } from "@lamemind/react-agent-ts";
import { DynamicTool } from "@langchain/core/tools";

// Create your model
const model = new ChatAnthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
  model: "claude-3-sonnet-20240229"
});

// Define tools
const tools = [
  new DynamicTool({
    name: "calculator",
    description: "Performs basic math operations",
    func: async (input: string) => {
      return eval(input).toString();
    }
  })
];

// Create and use agent
const agent = new ReActAgent(model, tools);
const response = await agent.invoke("What's 15 * 24 + 100?");
console.log(response);

🎯 Usage Examples

With OpenAI GPT

import { ChatOpenAI } from "@langchain/openai";

const model = new ChatOpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  model: "gpt-4"
});

const agent = new ReActAgent(model, tools);

With Google Gemini

import { ChatGoogleGenerativeAI } from "@langchain/google-genai";

const model = new ChatGoogleGenerativeAI({
  apiKey: process.env.GOOGLE_API_KEY,
  model: "gemini-pro"
});

const agent = new ReActAgent(model, tools);

Advanced Tool Example

import { z } from "zod";
import { validateAndParseInput } from "@lamemind/react-agent-ts";

const weatherTool = new DynamicTool({
  name: "get_weather",
  description: "Get current weather for a city",
  func: async (input: string) => {
    const schema = z.object({
      city: z.string(),
      country: z.string().optional()
    });
    
    const parsed = validateAndParseInput(JSON.parse(input), schema);
    
    // Your weather API call here
    return `Weather in ${parsed.city}: 22°C, sunny`;
  }
});

const agent = new ReActAgent(model, [weatherTool]);
await agent.invoke("What's the weather like in Rome?");

Conversation Management

import { systemPrompt, userMessage } from "@lamemind/react-agent-ts";

// Start with system prompt
const messages = [
  systemPrompt("You are a helpful data analyst assistant"),
  userMessage("Analyze this sales data...")
];

const response = await agent.invoke(messages);

// Continue conversation
const textResponse = await agent.extractAiTextResponse();
console.log("AI said:", textResponse);

Streaming Callbacks

const agent = new ReActAgent(model, tools);

// Get notified of each iteration
agent.onMessage((messages) => {
  console.log(`Agent completed iteration, ${messages.length} messages so far`);
});

const response = await agent.invoke("Complex multi-step task...");

📚 API Reference

ReActAgent

Constructor

new ReActAgent(model: BaseChatModel, tools: any[], maxIterations?: number)
  • model: Any LangChain-compatible chat model
  • tools: Array of LangChain tools
  • maxIterations: Maximum reasoning iterations (default: 10)

Methods

invoke(messages: string | any[]): Promise<any> Execute the agent with a message or conversation history.

extractAiTextResponse(): Promise<string> Extract the final text response from the agent, excluding tool calls.

onMessage(callback: (messages: any[]) => void): void Set callback for streaming updates during execution.

dumpConversation(): void Debug method to log the complete conversation history.

🔧 Configuration

Model Configuration

The agent accepts any LangChain BaseChatModel. Configure your model according to LangChain documentation:

// Anthropic with custom settings
const model = new ChatAnthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
  model: "claude-3-sonnet-20240229",
  temperature: 0.7,
  maxTokens: 4000
});

// OpenAI with streaming
const model = new ChatOpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  model: "gpt-4",
  streaming: true
});

Agent Configuration

const agent = new ReActAgent(
  model, 
  tools, 
  5  // Max iterations - prevents infinite loops
);

🎯 Why This Approach?

Separation of Concerns: You handle model configuration and API keys, we handle ReAct logic.

No Vendor Lock-in: Switch between providers without changing agent code.

Minimal Dependencies: Only LangChain core, no provider-specific dependencies.

Production Ready: Built for real applications with proper error handling and streaming.

🛠️ Development

# Clone the repo
git clone https://github.com/lamemind/react-agent-ts
cd react-agent-ts

# Install dependencies
npm install

# Build
npm run build

# Development mode
npm run dev

🤝 Contributing

Contributions are welcome! This project focuses on the ReAct pattern implementation. For provider-specific issues, please refer to LangChain documentation.

  1. Fork the repo
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

ISC © lamemind

🙏 Acknowledgments


🌟 If this helped you, consider giving it a star on GitHub!