A tool the agent can use to look up user information
import * as z from "zod";
import { createAgent, tool } from "langchain";
import { InMemoryStore, type Runtime } from "@langchain/langgraph";
// InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production.
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Write sample data to the store using the put method
await store.put(
["users"], // Namespace to group related data together (users namespace for user data)
"user_123", // Key within the namespace (user ID as key)
{
name: "John Smith",
language: "English",
} // Data to store for the given user
);
const getUserInfo = tool(
// Look up user info.
async (_, runtime: Runtime<z.infer<typeof contextSchema>>) => {
// Access the store - same as that provided to `createAgent`
const userId = runtime.context?.userId;
if (!userId) {
throw new Error("userId is required");
}
// Retrieve data from store - returns StoreValue object with value and metadata
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
}
);
const agent = createAgent({
model: "openai:gpt-4o-mini",
tools: [getUserInfo],
contextSchema,
// Pass store to agent - enables agent to access store when running tools
store,
});
// Run the agent
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } }
);
console.log(result.messages.at(-1)?.content);
/**
* Outputs:
* User Information:
* - Name: John Smith
* - Language: English
*/