DEV Community

Alex Spinov
Alex Spinov

Posted on

LangChain.js Has a Free API — Here's How to Build AI Chains in JavaScript

LangChain.js is a framework for building LLM-powered applications. It provides abstractions for chains, agents, retrieval, and memory — making it easy to build complex AI workflows.

Installation

npm install langchain @langchain/openai @langchain/community
Enter fullscreen mode Exit fullscreen mode

Simple Chain

import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

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

const prompt = ChatPromptTemplate.fromMessages([
  ["system", "You are a technical writer. Write concise explanations."],
  ["user", "Explain {topic} in {style} style"]
]);

const chain = prompt.pipe(model).pipe(new StringOutputParser());

const result = await chain.invoke({
  topic: "web scraping",
  style: "beginner-friendly"
});
console.log(result);
Enter fullscreen mode Exit fullscreen mode

RAG (Retrieval-Augmented Generation)

import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";

// Split documents
const splitter = new RecursiveCharacterTextSplitter({ chunkSize: 1000 });
const docs = await splitter.createDocuments([longText]);

// Create vector store
const vectorStore = await MemoryVectorStore.fromDocuments(
  docs,
  new OpenAIEmbeddings()
);

// Query
const results = await vectorStore.similaritySearch("How does auth work?", 3);
results.forEach(doc => console.log(doc.pageContent.slice(0, 100)));
Enter fullscreen mode Exit fullscreen mode

Agents with Tools

import { DynamicTool } from "@langchain/core/tools";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";

const searchTool = new DynamicTool({
  name: "web_search",
  description: "Search the web for current information",
  func: async (query) => {
    // Your search implementation
    return `Results for: ${query}`;
  }
});

const agent = await createOpenAIToolsAgent({ llm: model, tools: [searchTool], prompt });
const executor = new AgentExecutor({ agent, tools: [searchTool] });

const result = await executor.invoke({ input: "What is the latest version of React?" });
console.log(result.output);
Enter fullscreen mode Exit fullscreen mode

Streaming

const stream = await chain.stream({ topic: "APIs", style: "technical" });
for await (const chunk of stream) {
  process.stdout.write(chunk);
}
Enter fullscreen mode Exit fullscreen mode

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)