Skip to content

Commit 8fcaa72

Browse files
committed
Add example of code execution with tools reading files
1 parent ea973a4 commit 8fcaa72

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* Example demonstrating Code Execution Middleware with additional tools.
3+
*
4+
* This example shows how to combine code execution capabilities with custom tools
5+
* that can access files generated by code execution. The example creates an
6+
* email_file tool that reads files from the agent's workspace and demonstrates
7+
* how tools can interact with code execution outputs.
8+
*/
9+
10+
import { ChatAnthropic } from "@langchain/anthropic";
11+
import { AnthropicContainerProvider } from "@langchain/anthropic/middleware";
12+
import { HumanMessage } from "@langchain/core/messages";
13+
import { getCurrentTaskInput } from "@langchain/langgraph";
14+
import {
15+
codeExecutionMiddleware,
16+
createAgent,
17+
MemoryFileProvider,
18+
tool,
19+
type CodeExecutionMiddlewareState,
20+
} from "langchain";
21+
import fs from "node:fs/promises";
22+
import { z } from "zod";
23+
24+
// Initial setup
25+
const model = new ChatAnthropic({
26+
model: "claude-sonnet-4-5-20250929",
27+
});
28+
29+
const middleware = codeExecutionMiddleware(
30+
new AnthropicContainerProvider(),
31+
new MemoryFileProvider()
32+
);
33+
34+
const emailTool = tool(
35+
async ({ path }, config) => {
36+
// Access the current agent state using getCurrentTaskInput
37+
const state = getCurrentTaskInput<CodeExecutionMiddlewareState>(config);
38+
39+
// Find the file using the middleware's files method
40+
const file = middleware.files(state).find((f) => f.path === path);
41+
42+
if (!file) {
43+
return `Error: File not found at path: ${path}`;
44+
}
45+
46+
// Get the file content
47+
const content = await file.getContent();
48+
49+
// Simulate emailing the file
50+
console.log("Pretending to email file with content:");
51+
console.log(content.toString());
52+
53+
return `Successfully emailed file: ${path}`;
54+
},
55+
{
56+
name: "email_file",
57+
description:
58+
"Email a file by providing its path. The file must exist in the agent's workspace.",
59+
schema: z.object({
60+
path: z.string().describe("The path to the file to email"),
61+
}),
62+
}
63+
);
64+
65+
const agent = createAgent({
66+
model,
67+
middleware: [middleware],
68+
tools: [emailTool],
69+
});
70+
71+
// Read and add the test data file
72+
const testDataPath = "test_data.csv";
73+
const fileContent = await fs.readFile(testDataPath);
74+
75+
await agent.invoke({
76+
messages: new HumanMessage(
77+
"Turn this into a markdown file with a table and then email it."
78+
),
79+
files: [await middleware.addFile(testDataPath, fileContent)],
80+
});

0 commit comments

Comments
 (0)