Back to Integrations
Integration/LangChain

LangChain Integration

Build complex AI applications with LangChain agents and tool integrations.

Category
AI Frameworks
Difficulty
Intermediate
Tags
3 features
Setup Time
5-15 min
Agents
Tools
Chains

Quick Start Guide

Installation

Terminal
npm install langchain @langchain/openai cognitora

Implementation

TypeScript
typescript
1import { ChatOpenAI } from '@langchain/openai';
2import { DynamicTool } from '@langchain/core/tools';
3import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
4import { ChatPromptTemplate, MessagesPlaceholder } from '@langchain/core/prompts';
5import { Cognitora } from 'cognitora';
6
7const cognitora = new Cognitora({ apiKey: process.env.COGNITORA_API_KEY });
8
9async function createLangChainCodeInterpreter() {
10  const session = await cognitora.sessions.create({
11    image: 'python:3.11-slim',
12    timeout: 300,
13    persistent: true
14  });
15
16  const codeExecutionTool = new DynamicTool({
17    name: "execute_python_code",
18    description: "Execute Python code in a secure sandbox environment.",
19    func: async (code: string) => {
20      try {
21        const execution = await cognitora.compute.execute({
22          sessionId: session.id,
23          command: ["python", "-c", code]
24        });
25        
26        if (execution.exitCode === 0) {
27          return `Execution successful:\n${execution.stdout}`;
28        } else {
29          return `Execution failed:\n${execution.stderr}`;
30        }
31      } catch (error) {
32        return `Error executing code: ${error.message}`;
33      }
34    },
35  });
36
37  return { session, codeExecutionTool };
38}
39
40async function runLangChainAgent(userQuery: string) {
41  const { session, codeExecutionTool } = await createLangChainCodeInterpreter();
42  
43  const model = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });
44
45  const prompt = ChatPromptTemplate.fromMessages([
46    ["system", "You are a helpful AI assistant with access to a Python code execution environment."],
47    ["human", "{input}"],
48    new MessagesPlaceholder("agent_scratchpad"),
49  ]);
50
51  const agent = await createOpenAIFunctionsAgent({
52    llm: model,
53    tools: [codeExecutionTool],
54    prompt,
55  });
56
57  const agentExecutor = new AgentExecutor({
58    agent,
59    tools: [codeExecutionTool],
60    verbose: true,
61  });
62
63  const result = await agentExecutor.invoke({ input: userQuery });
64  
65  return {
66    output: result.output,
67    sessionId: session.id
68  };
69}

Ready to integrate LangChain?

Get started with LangChain and Cognitora in minutes. Secure, scalable, and ready for anything.