Skip to content

Commit

Permalink
examples[minor]: Port langchai examples code to run ts files in examples
Browse files Browse the repository at this point in the history
  • Loading branch information
bracesproul committed Aug 26, 2024
1 parent 002e68d commit e0b4c03
Show file tree
Hide file tree
Showing 6 changed files with 1,746 additions and 0 deletions.
1,302 changes: 1,302 additions & 0 deletions examples/how-tos/streaming-events-from-within-tools.ipynb

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions examples/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
{
"name": "examples",
"type": "module",
"description": "Dependencies for LangGraph examples.",
"scripts": {
"start": "tsx --experimental-wasm-modules -r dotenv/config src/index.ts"
},
"devDependencies": {
"@langchain/anthropic": "^0.2.15",
"@langchain/cloudflare": "^0.0.7",
Expand All @@ -20,6 +24,7 @@
"langchain": "^0.2.16",
"pg": "^8.11.0",
"tslab": "^1.0.22",
"tsx": "^4.18.0",
"uuid": "^10.0.0",
"zod": "^3.23.8",
"zod-to-json-schema": "^3.23.2"
Expand Down
56 changes: 56 additions & 0 deletions examples/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import path from "path";
import url from "url";
import { awaitAllCallbacks } from "@langchain/core/callbacks/promises";

const [exampleName, ...args] = process.argv.slice(2);

if (!exampleName) {
console.error("Please provide path to example to run");
process.exit(1);
}

// Allow people to pass all possible variations of a path to an example
// ./src/foo.ts, ./dist/foo.js, src/foo.ts, dist/foo.js, foo.ts
let exampleRelativePath = exampleName;

if (exampleRelativePath.startsWith("./examples/")) {
exampleRelativePath = exampleName.slice(11);
} else if (exampleRelativePath.startsWith("examples/")) {
exampleRelativePath = exampleName.slice(9);
}

if (exampleRelativePath.startsWith("./src/")) {
exampleRelativePath = exampleRelativePath.slice(6);
} else if (exampleRelativePath.startsWith("./dist/")) {
exampleRelativePath = exampleRelativePath.slice(7);
} else if (exampleRelativePath.startsWith("src/")) {
exampleRelativePath = exampleRelativePath.slice(4);
} else if (exampleRelativePath.startsWith("dist/")) {
exampleRelativePath = exampleRelativePath.slice(5);
}

let runExample;
try {
({ run: runExample } = await import(
path.join(
path.dirname(url.fileURLToPath(import.meta.url)),
exampleRelativePath
)
));
} catch (e) {
console.log(e);
throw new Error(`Could not load example ${exampleName}: ${e}`);
}

if (runExample) {
const maybePromise = runExample(args);

if (maybePromise instanceof Promise) {
maybePromise
.catch((e) => {
console.error(`Example failed with:`);
console.error(e);
})
.finally(() => awaitAllCallbacks());
}
}
75 changes: 75 additions & 0 deletions examples/src/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { z } from "zod";
import { tool } from "@langchain/core/tools";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { ChatAnthropic } from "@langchain/anthropic";
import { createReactAgent } from "@langchain/langgraph/prebuilt";

const model = new ChatAnthropic({
model: "claude-3-5-sonnet-20240620",
temperature: 0,
});

const getItems = tool(
async (input, config) => {
console.log("RUNNING TOOL");
const template = ChatPromptTemplate.fromMessages([
[
"human",
"Can you tell me what kind of items i might find in the following place: '{place}'. " +
"List at least 3 such items separating them by a comma. And include a brief description of each item..",
],
]);

const modelWithConfig = model.withConfig({
runName: "Get Items LLM",
tags: ["tool_llm"],
});

const chain = template.pipe(modelWithConfig);
const result = await chain.invoke(input, config);
return result.content;
},
{
name: "get_items",
description: "Use this tool to look up which items are in the given place.",
schema: z.object({
place: z.string(),
}),
}
);

const agent = createReactAgent({
llm: model,
tools: [getItems],
});

let finalEvent;
for await (const event of agent.streamEvents(
{
messages: [
[
"human",
"what items are on the shelf? You should call the get_items tool.",
],
],
},
{
version: "v2",
},
{
includeTags: ["tool_llm"],
}
)) {
console.log(event.data);
finalEvent = event;
}

const finalMessages = finalEvent?.data.output.messages;
console.dir(
finalMessages.map((msg: any) => ({
type: msg._getType(),
content: msg.content,
tool_calls: msg.tool_calls,
})),
{ depth: null }
);
31 changes: 31 additions & 0 deletions examples/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"extends": "@tsconfig/recommended",
"compilerOptions": {
"outDir": "dist",
"lib": [
"ES2021",
"ES2022.Object",
"DOM"
],
"target": "ES2021",
"module": "nodenext",
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"baseUrl": "./src",
"declaration": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUnusedParameters": true,
"useDefineForClassFields": true,
"strictPropertyInitialization": false
},
"exclude": [
"node_modules/",
"dist/",
"tests/"
],
"include": [
"*.ts",
"./src"
]
}
Loading

0 comments on commit e0b4c03

Please sign in to comment.