Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple createReactAgent will cause errors. #7856

Open
5 tasks done
phpmac opened this issue Mar 17, 2025 · 6 comments
Open
5 tasks done

Multiple createReactAgent will cause errors. #7856

phpmac opened this issue Mar 17, 2025 · 6 comments
Labels
auto:bug Related to a bug, vulnerability, unexpected error with an existing feature

Comments

@phpmac
Copy link

phpmac commented Mar 17, 2025

Checked other resources

  • I added a very descriptive title to this issue.
  • I searched the LangChain.js documentation with the integrated search.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain.js rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).

Example Code

demo code

import { createSupervisor } from "@langchain/langgraph-supervisor";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
// TODO You just need to switch the model to your
import { model } from "core/ai";
import chalk from "chalk";

const add = tool(
    async (args) => {
        console.debug("add", args);
        return args.a + args.b;
    },
    {
        name: "add",
        description: "Add two numbers together.",
        schema: z.object({
            a: z.number(),
            b: z.number(),
        }),
    }
);

const multiply = tool(
    async (args) => {
        console.debug("multiply", args);
        return args.a * args.b;
    },
    {
        name: "multiply",
        description: "Multiply two numbers together.",
        schema: z.object({
            a: z.number(),
            b: z.number(),
        }),
    }
);

const webSearch = tool(
    async (args) => {
        console.debug("webSearch", args);
        return (
            "Here is the total number of employees at FAANG companies in 2024:\n" +
            "1. **Facebook (Meta)**: 67,317 employees.\n" +
            "2. **Apple**: 164,000 employees.\n" +
            "3. **Amazon**: 1,551,000 employees.\n" +
            "4. **Netflix**: 14,000 employees.\n" +
            "5. **Google (Alphabet)**: 181,269 employees."
        );
    },
    {
        name: "web_search",
        description: "Search for information on the web.",
        schema: z.object({
            query: z.string(),
        }),
    }
);

const getPrice = tool(
    async (args) => {
        console.debug("getPrice", args);
        return {
            coin: args.coin,
            usd_price: 100,
            cny_price: 100,
        };
    },
    {
        name: "getPrice",
        description: "Get cryptocurrency price.",
        schema: z.object({
            coin: z.string(),
        }),
    }
);

const mathAgent = createReactAgent({
    // TODO You just need to switch the model to your
    llm: model,
    tools: [add, multiply],
    name: "math_expert",
    prompt: "You are a mathematics expert.",
});

const researchAgent = createReactAgent({
    // TODO You just need to switch the model to your
    llm: model,
    tools: [webSearch],
    name: "research_expert",
    prompt: "You are a world-class research expert who can use web search.",
});

const getPriceAgent = createReactAgent({
    // TODO You just need to switch the model to your
    llm: model,
    tools: [getPrice],
    name: "getPrice_expert",
    prompt: "You can get cryptocurrency prices.",
});

const workflow = createSupervisor({
    agents: [researchAgent, mathAgent, getPriceAgent],
    llm: model,
    prompt: `
    You are a team supervisor responsible for managing a research expert and a math expert.
    For questions related to current events, use the research expert (research_agent).
    For math problems, use the math expert (math_agent).
    For other questions, use the research expert (research_agent).
    For cryptocurrency price questions, use the cryptocurrency price expert (getPrice_expert).
    `
});

const app = workflow.compile();

interface ToolCall {
    name: string;
    id: string;
    args: Record<string, unknown>;
}

interface Message {
    role: "user" | "assistant";
    content: string;
}

interface StreamChunk {
    messages?: Message[];
    supervisor?: {
        toolCalls?: ToolCall;
        output?: string;
    };
}

/**
 * Print a separator line
 * @param text Text to display in the separator
 */
function printSeparator(text: string) {
    const line = "=".repeat(32);
    console.log(`${line}${chalk.bold(text)}${line}`);
}

/**
 * Format and print tool call information
 * @param toolCall Tool call information
 */
function printToolCall(toolCall: ToolCall) {
    console.log("Tool Calls:");
    console.log(`  ${toolCall.name} (${toolCall.id})`);
    console.log(` Call ID: ${toolCall.id}`);
    console.log("  Args:");
    Object.entries(toolCall.args).forEach(([key, value]) => {
        console.log(`    ${key}: ${value}`);
    });
}

/**
 * Format and print message stream
 * @param stream Message stream
 */
async function printStream(stream: AsyncIterable<StreamChunk>) {
    for await (const chunk of stream) {
        if (chunk.messages) {
            const message = chunk.messages[chunk.messages.length - 1];

            if (message.role === "user") {
                printSeparator(" Human Message ");
                console.log("\n" + message.content.trim() + "\n");
            } else if (message.role === "assistant") {
                printSeparator(" AI Message ");
                console.log("\n" + message.content.trim() + "\n");
            }
        }

        if (chunk.supervisor?.toolCalls) {
            printSeparator(" Tool Message ");
            printToolCall(chunk.supervisor.toolCalls);
        }

        if (chunk.supervisor?.output) {
            printSeparator(" Tool Output ");
            console.log("\n" + chunk.supervisor.output + "\n");
        }
    }
}

const stream = await app.stream({
    messages: [
        {
            role: "user",
            content: `
            What is 1+1 and then 2*2, what's the final result?
            By the way, do you know what AI is?
            Do you know the price of Bitcoin?
            `,
        },
    ],
});

// Use the new formatted print function
await printStream(stream);

print

file:///Users/a/Downloads/remix/node_modules/@langchain/core/dist/language_models/chat_models.js:64
        return chatGeneration.message;
                              ^

TypeError: Cannot read properties of undefined (reading 'message')
    at ChatOpenAI.invoke (file:///Users/a/Downloads/remix/node_modules/@langchain/core/dist/language_models/chat_models.js:64:31)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async RunnableSequence.invoke (file:///Users/a/Downloads/remix/node_modules/@langchain/core/dist/runnables/base.js:1280:27)
    at async RunnableCallable.callModel (/Users/a/Downloads/remix/node_modules/@langchain/langgraph/src/prebuilt/react_agent_executor.ts:490:23)
    at async RunnableCallable.invoke (/Users/a/Downloads/remix/node_modules/@langchain/langgraph/src/utils.ts:85:21)
    at async RunnableSequence.invoke (file:///Users/a/Downloads/remix/node_modules/@langchain/core/dist/runnables/base.js:1274:33)
    at async _runWithRetry (/Users/a/Downloads/remix/node_modules/@langchain/langgraph/src/pregel/retry.ts:94:16)
    at async PregelRunner._executeTasksWithRetry (/Users/a/Downloads/remix/node_modules/@langchain/langgraph/src/pregel/runner.ts:338:27)
    at async PregelRunner.tick (/Users/a/Downloads/remix/node_modules/@langchain/langgraph/src/pregel/runner.ts:90:35)
    at async CompiledStateGraph._runLoop (/Users/a/Downloads/remix/node_modules/@langchain/langgraph/src/pregel/index.ts:1709:9) {
  pregelTaskId: 'f81bdbf1-470d-598d-80dd-5fde65f9bca5'
}

Node.js v23.10.0

This is true regardless of the model used.

Error Message and Stack Trace (if applicable)

No response

Description

    "@langchain/community": "^0.3.35",
    "@langchain/core": "^0.3.42",
    "@langchain/langgraph": "^0.2.55",
    "@langchain/langgraph-supervisor": "^0.0.9",
    "@langchain/mcp-adapters": "^0.2.4",
    "@langchain/openai": "^0.4.4",

System Info

node v23.10.0
yarn 1.22.22
npm 10.9.2

Copy link

dosubot bot commented Mar 17, 2025

I found a similar open issue related to the error "Cannot read properties of undefined (reading 'message')" when using the createReactAgent function. The suggested solution involves several steps:

  1. Message Structure: Ensure that the messages array passed to the stream method is correctly structured and that each message is properly instantiated as a HumanMessage.

  2. Model-Specific Handling: Since the issue occurs regardless of the model used, check if there are any known limitations or differences in how different models handle messages compared to others.

  3. Direct Invocation: If invoking the method directly on the model works, the issue might be related to how the agent is configured or interacts with the model. Review the agent's configuration and any model-specific settings.

  4. Error Handling: Implement additional error handling or logging around the method call to capture more detailed information about what might be going wrong.

These steps might help in resolving the issue. If the problem persists, further investigation into the interaction between the agents and the supervisor function might be necessary [1].

To continue talking to Dosu, mention @dosu.


Help Dosu learn! Give it feedback: Great Response | Irrelevant Answer | Incorrect Sources | Too Verbose | Hallucination | Bug Report | Other

@dosubot dosubot bot added the auto:bug Related to a bug, vulnerability, unexpected error with an existing feature label Mar 17, 2025
@jacoblee93
Copy link
Collaborator

@vbarda could you have a look at this?

@vbarda
Copy link
Collaborator

vbarda commented Mar 24, 2025

@phpmac any chance you're using some custom chat model implementation? trace shows ChatOpenAI, but it's unclear what the model is from your import (import { model } from "core/ai";)

I tested the code you provided replacing model with

import { ChatOpenAI } from "@langchain/openai";
const model = new ChatOpenAI();

and it works perfectly fine for me

@phpmac
Copy link
Author

phpmac commented Mar 24, 2025 via email

@vbarda
Copy link
Collaborator

vbarda commented Mar 24, 2025

@phpmac which @langchain/openai version / which model are you using? i tested on the latest version

@phpmac
Copy link
Author

phpmac commented Mar 25, 2025

@phpmac which @langchain/openai version / which model are you using? i tested on the latest version


const mathAgent = createReactAgent({
    llm: model,
    tools: [add, multiply],
    name: "math_expert",
    prompt: "你是一位数学专家。",
});

const researchAgent = createReactAgent({
    llm: model,
    tools: [webSearch],
    name: "research_expert",
    prompt: "你是一位世界级的研究专家,可以使用网络搜索。",
});

const getPriceAgent = createReactAgent({
    llm: model,
    tools: [getPrice],
    name: "getPrice_expert",
    prompt: "你可以获得加密货币价格。",
});

const workflow = createSupervisor({
    agents: [researchAgent, mathAgent, getPriceAgent],
    llm: model,
    prompt: `
    你是一位团队主管,负责管理一位研究专家和一位数学专家。
    对于当前事件相关的问题,使用研究专家(research_agent)。
    对于数学问题,使用数学专家(math_agent)。
    对于其他问题,使用研究专家(research_agent)。
    对于币种价格问题,使用币种价格专家(getPrice_expert)。
    `
});

Try this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auto:bug Related to a bug, vulnerability, unexpected error with an existing feature
Projects
None yet
Development

No branches or pull requests

3 participants