langchain-core-workflow-b

Build LangChain agents with tool calling for autonomous task execution. Use when creating AI agents, implementing tool/function calling, binding tools to models, or building autonomous multi-step workflows. Trigger: "langchain agents", "langchain tools", "tool calling", "create agent", "function calling", "createToolCallingAgent".

1,868 stars

Best use case

langchain-core-workflow-b is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Build LangChain agents with tool calling for autonomous task execution. Use when creating AI agents, implementing tool/function calling, binding tools to models, or building autonomous multi-step workflows. Trigger: "langchain agents", "langchain tools", "tool calling", "create agent", "function calling", "createToolCallingAgent".

Teams using langchain-core-workflow-b should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/langchain-core-workflow-b/SKILL.md --create-dirs "https://raw.githubusercontent.com/jeremylongshore/claude-code-plugins-plus-skills/main/plugins/saas-packs/langchain-pack/skills/langchain-core-workflow-b/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/langchain-core-workflow-b/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How langchain-core-workflow-b Compares

Feature / Agentlangchain-core-workflow-bStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Build LangChain agents with tool calling for autonomous task execution. Use when creating AI agents, implementing tool/function calling, binding tools to models, or building autonomous multi-step workflows. Trigger: "langchain agents", "langchain tools", "tool calling", "create agent", "function calling", "createToolCallingAgent".

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# LangChain Core Workflow B: Agents & Tools

## Overview

Build autonomous agents that use tools, make decisions, and execute multi-step tasks. Covers tool definition with Zod schemas, `createToolCallingAgent`, `AgentExecutor`, streaming agent output, and conversation memory.

## Prerequisites

- Completed `langchain-core-workflow-a` (chains)
- `npm install langchain @langchain/core @langchain/openai zod`

## Step 1: Define Tools (TypeScript)

```typescript
import { tool } from "@langchain/core/tools";
import { z } from "zod";

// Tool with Zod schema validation
const calculator = tool(
  async ({ expression }) => {
    try {
      // Use a safe math parser in production (e.g., mathjs)
      const result = Function(`"use strict"; return (${expression})`)();
      return String(result);
    } catch (e) {
      return `Error: invalid expression "${expression}"`;
    }
  },
  {
    name: "calculator",
    description: "Evaluate a mathematical expression. Input: a math expression string.",
    schema: z.object({
      expression: z.string().describe("Math expression like '2 + 2' or '100 * 0.15'"),
    }),
  }
);

const weatherLookup = tool(
  async ({ city }) => {
    // Replace with real API call
    const data: Record<string, string> = {
      "New York": "72F, sunny",
      "London": "58F, cloudy",
      "Tokyo": "80F, humid",
    };
    return data[city] ?? `No weather data for ${city}`;
  },
  {
    name: "weather",
    description: "Get current weather for a city.",
    schema: z.object({
      city: z.string().describe("City name"),
    }),
  }
);

const tools = [calculator, weatherLookup];
```

## Step 2: Create Agent with AgentExecutor

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { createToolCallingAgent, AgentExecutor } from "langchain/agents";
import { ChatPromptTemplate, MessagesPlaceholder } from "@langchain/core/prompts";

const llm = new ChatOpenAI({ model: "gpt-4o-mini" });

const prompt = ChatPromptTemplate.fromMessages([
  ["system", "You are a helpful assistant. Use tools when needed."],
  new MessagesPlaceholder("chat_history"),
  ["human", "{input}"],
  new MessagesPlaceholder("agent_scratchpad"),
]);

const agent = createToolCallingAgent({
  llm,
  tools,
  prompt,
});

const executor = new AgentExecutor({
  agent,
  tools,
  verbose: true,           // Log reasoning steps
  maxIterations: 10,       // Prevent infinite loops
  returnIntermediateSteps: true,
});
```

## Step 3: Run the Agent

```typescript
// Simple invocation
const result = await executor.invoke({
  input: "What's 25 * 4, and what's the weather in Tokyo?",
  chat_history: [],
});

console.log(result.output);
// "25 * 4 = 100. The weather in Tokyo is 80F and humid."

// The agent decided to call both tools, then composed the answer.
console.log(result.intermediateSteps);
// Shows each tool call and its result
```

## Step 4: Agent with Conversation Memory

```typescript
import { ChatMessageHistory } from "@langchain/community/stores/message/in_memory";
import { RunnableWithMessageHistory } from "@langchain/core/runnables";

const messageHistory = new ChatMessageHistory();

const agentWithHistory = new RunnableWithMessageHistory({
  runnable: executor,
  getMessageHistory: (_sessionId) => messageHistory,
  inputMessagesKey: "input",
  historyMessagesKey: "chat_history",
});

// First call
await agentWithHistory.invoke(
  { input: "My name is Alice" },
  { configurable: { sessionId: "user-1" } }
);

// Second call -- agent remembers
const res = await agentWithHistory.invoke(
  { input: "What's my name?" },
  { configurable: { sessionId: "user-1" } }
);
console.log(res.output); // "Your name is Alice!"
```

## Step 5: Stream Agent Events

```typescript
const eventStream = executor.streamEvents(
  { input: "Calculate 15% tip on $85", chat_history: [] },
  { version: "v2" }
);

for await (const event of eventStream) {
  if (event.event === "on_chat_model_stream") {
    process.stdout.write(event.data.chunk.content ?? "");
  } else if (event.event === "on_tool_start") {
    console.log(`\n[Calling tool: ${event.name}]`);
  } else if (event.event === "on_tool_end") {
    console.log(`[Tool result: ${event.data.output}]`);
  }
}
```

## Step 6: Bind Tools Directly (Without AgentExecutor)

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage } from "@langchain/core/messages";

const model = new ChatOpenAI({ model: "gpt-4o-mini" });
const modelWithTools = model.bindTools(tools);

const response = await modelWithTools.invoke([
  new HumanMessage("What's 42 * 17?"),
]);

// Check if model wants to call a tool
if (response.tool_calls && response.tool_calls.length > 0) {
  for (const tc of response.tool_calls) {
    console.log(`Tool: ${tc.name}, Args: ${JSON.stringify(tc.args)}`);
    // Execute tool manually
    const toolResult = await tools
      .find((t) => t.name === tc.name)!
      .invoke(tc.args);
    console.log(`Result: ${toolResult}`);
  }
}
```

## Python Equivalent

```python
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.tools import tool

@tool
def calculator(expression: str) -> str:
    """Evaluate a math expression."""
    return str(eval(expression))

tools = [calculator]
llm = ChatOpenAI(model="gpt-4o-mini")

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant."),
    MessagesPlaceholder("chat_history", optional=True),
    ("human", "{input}"),
    MessagesPlaceholder("agent_scratchpad"),
])

agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = executor.invoke({"input": "What is 25 * 4?", "chat_history": []})
```

## Error Handling

| Error | Cause | Fix |
|-------|-------|-----|
| `Max iterations reached` | Agent stuck in loop | Increase `maxIterations` or improve system prompt |
| `Tool not found` | Tool name mismatch | Verify tools array passed to both `createToolCallingAgent` and `AgentExecutor` |
| `Missing agent_scratchpad` | Prompt missing placeholder | Add `new MessagesPlaceholder("agent_scratchpad")` |
| Tool execution error | Tool throws exception | Wrap tool body in try/catch, return error string |

## Resources

- [Agents Guide](https://js.langchain.com/docs/concepts/agents/)
- [Tool Calling](https://js.langchain.com/docs/concepts/tool_calling/)
- [createToolCallingAgent API](https://v03.api.js.langchain.com/functions/langchain.agents.createToolCallingAgent.html)

## Next Steps

Proceed to `langchain-common-errors` for debugging guidance.

Related Skills

calendar-to-workflow

1868
from jeremylongshore/claude-code-plugins-plus-skills

Converts calendar events and schedules into Claude Code workflows, meeting prep documents, and standup notes. Use when the user mentions calendar events, meeting prep, standup generation, or scheduling workflows. Trigger with phrases like "prep for my meetings", "generate standup notes", "create workflow from calendar", or "summarize today's schedule".

workhuman-core-workflow-b

1868
from jeremylongshore/claude-code-plugins-plus-skills

Workhuman core workflow b for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman core workflow b".

workhuman-core-workflow-a

1868
from jeremylongshore/claude-code-plugins-plus-skills

Workhuman core workflow a for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman core workflow a".

wispr-core-workflow-b

1868
from jeremylongshore/claude-code-plugins-plus-skills

Wispr Flow core workflow b for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr core workflow b".

wispr-core-workflow-a

1868
from jeremylongshore/claude-code-plugins-plus-skills

Wispr Flow core workflow a for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr core workflow a".

windsurf-core-workflow-b

1868
from jeremylongshore/claude-code-plugins-plus-skills

Execute Windsurf's secondary workflow: Workflows, Memories, and reusable automation. Use when creating reusable Cascade workflows, managing persistent memories, or automating repetitive development tasks. Trigger with phrases like "windsurf workflow", "windsurf automation", "windsurf memories", "cascade workflow", "windsurf slash command".

windsurf-core-workflow-a

1868
from jeremylongshore/claude-code-plugins-plus-skills

Execute Windsurf's primary workflow: Cascade Write mode for multi-file agentic coding. Use when building features, refactoring across files, or performing complex code tasks. Trigger with phrases like "windsurf cascade write", "windsurf agentic coding", "windsurf multi-file edit", "cascade write mode", "windsurf build feature".

webflow-core-workflow-b

1868
from jeremylongshore/claude-code-plugins-plus-skills

Execute Webflow secondary workflows — Sites management, Pages API, Forms submissions, Ecommerce (products/orders/inventory), and Custom Code via the Data API v2. Use when managing sites, reading pages, handling form data, or working with Webflow Ecommerce products and orders. Trigger with phrases like "webflow sites", "webflow pages", "webflow forms", "webflow ecommerce", "webflow products", "webflow orders".

webflow-core-workflow-a

1868
from jeremylongshore/claude-code-plugins-plus-skills

Execute the primary Webflow workflow — CMS content management: list collections, CRUD items, publish items, and manage content lifecycle via the Data API v2. Use when working with Webflow CMS collections and items, managing blog posts, team members, or any dynamic content. Trigger with phrases like "webflow CMS", "webflow collections", "webflow items", "create webflow content", "manage webflow CMS", "webflow content management".

veeva-core-workflow-b

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault core workflow b for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva core workflow b".

veeva-core-workflow-a

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault core workflow a for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva core workflow a".

vastai-core-workflow-b

1868
from jeremylongshore/claude-code-plugins-plus-skills

Execute Vast.ai secondary workflow: multi-instance orchestration, spot recovery, and cost optimization. Use when running distributed training, handling spot preemption, or optimizing GPU spend across multiple instances. Trigger with phrases like "vastai distributed training", "vastai spot recovery", "vastai multi-gpu", "vastai cost optimization".