Build complex AI applications with LangChain agents and tool integrations.
npm install langchain @langchain/openai cognitora
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.codeInterpreter.createSession({
11 language: 'python',
12 timeout_minutes: 30,
13 resources: {
14 cpu_cores: 1.0,
15 memory_mb: 512,
16 storage_gb: 5
17 }
18 });
19
20 const codeExecutionTool = new DynamicTool({
21 name: "execute_python_code",
22 description: "Execute Python code in a secure sandbox environment.",
23 func: async (code: string) => {
24 try {
25 const execution = await cognitora.codeInterpreter.execute({
26 code: code,
27 language: 'python',
28 session_id: session.data.session_id,
29 networking: true // Enable networking for code interpreter
30 });
31
32 if (execution.data.status === 'completed') {
33 const outputs = execution.data.outputs;
34 const stdout = outputs.filter(o => o.type === 'stdout').map(o => o.content).join('\n');
35 return `Execution successful:\n${stdout}`;
36 } else {
37 const stderr = execution.data.outputs.filter(o => o.type === 'stderr').map(o => o.content).join('\n');
38 return `Execution failed:\n${stderr}`;
39 }
40 } catch (error) {
41 return `Error executing code: ${error.message}`;
42 }
43 },
44 });
45
46 return { session, codeExecutionTool };
47}
48
49async function runLangChainAgent(userQuery: string) {
50 const { session, codeExecutionTool } = await createLangChainCodeInterpreter();
51
52 const model = new ChatOpenAI({ modelName: "gpt-4", temperature: 0 });
53
54 const prompt = ChatPromptTemplate.fromMessages([
55 ["system", "You are a helpful AI assistant with access to a Python code execution environment."],
56 ["human", "{input}"],
57 new MessagesPlaceholder("agent_scratchpad"),
58 ]);
59
60 const agent = await createOpenAIFunctionsAgent({
61 llm: model,
62 tools: [codeExecutionTool],
63 prompt,
64 });
65
66 const agentExecutor = new AgentExecutor({
67 agent,
68 tools: [codeExecutionTool],
69 verbose: true,
70 });
71
72 const result = await agentExecutor.invoke({ input: userQuery });
73
74 return {
75 output: result.output,
76 sessionId: session.id
77 };
78}
Get started with LangChain and Cognitora in minutes. Secure, scalable, and ready for anything.