Full-featured TypeScript SDK with session management and async support.
npm install @cognitora/sdk
1import { Cognitora } from '@cognitora/sdk';
2
3const client = new Cognitora({
4 apiKey: process.env.COGNITORA_API_KEY!,
5 baseURL: 'https://api.cognitora.dev'
6});
7
8class CodeInterpreter {
9 private sessionId: string | null = null;
10
11 async createSession() {
12 const sessionResponse = await client.codeInterpreter.createSession({
13 language: 'python',
14 timeout_minutes: 30
15 });
16
17 this.sessionId = sessionResponse.data.session_id;
18 return this.sessionId;
19 }
20
21 async execute(code: string, language: 'python' | 'javascript' | 'bash' = 'python') {
22 if (!this.sessionId) {
23 await this.createSession();
24 }
25
26 try {
27 const result = await client.codeInterpreter.execute({
28 code,
29 language,
30 session_id: this.sessionId!
31 });
32
33 return {
34 success: result.data.status === 'completed',
35 outputs: result.data.outputs,
36 execution_time: result.data.execution_time_ms,
37 session_id: this.sessionId
38 };
39 } catch (error) {
40 return {
41 success: false,
42 error: error instanceof Error ? error.message : 'Unknown error',
43 session_id: this.sessionId
44 };
45 }
46 }
47
48 async executeCompute(image: string, command: string[], options: {
49 cpu_cores?: number;
50 memory_mb?: number;
51 max_cost_credits?: number;
52 storage_gb?: number;
53 } = {}) {
54 try {
55 const execution = await client.containers.createContainer({
56 image,
57 command,
58 cpuCores: options.cpu_cores || 1.0,
59 memoryMb: options.memory_mb || 512,
60 maxCostCredits: options.max_cost_credits || 10,
61 storageGb: options.storage_gb || 5,
62 networking: false // Secure by default for containers
63 });
64
65 return {
66 execution_id: execution.id,
67 status: execution.status,
68 image: execution.image,
69 command: execution.command
70 };
71 } catch (error) {
72 return {
73 success: false,
74 error: error instanceof Error ? error.message : 'Unknown error'
75 };
76 }
77 }
78
79 async uploadFiles(files: Array<{ name: string; content: string; encoding?: string }>) {
80 if (!this.sessionId) {
81 await this.createSession();
82 }
83
84 try {
85 const result = await client.codeInterpreter.runWithFiles(
86 'print("Files uploaded successfully")',
87 files.map(f => ({ name: f.name, content: f.content, encoding: f.encoding || 'string' })),
88 'python',
89 this.sessionId!
90 );
91
92 return {
93 success: result.data.status === 'completed',
94 outputs: result.data.outputs
95 };
96 } catch (error) {
97 return {
98 success: false,
99 error: error instanceof Error ? error.message : 'Unknown error'
100 };
101 }
102 }
103
104 async cleanup() {
105 if (this.sessionId) {
106 await client.codeInterpreter.deleteSession(this.sessionId);
107 this.sessionId = null;
108 }
109 }
110}
111
112// Example usage
113async function main() {
114 const interpreter = new CodeInterpreter();
115
116 try {
117 // Execute Python code with persistent variables
118 await interpreter.execute('x = 42');
119 await interpreter.execute('y = "Hello World"');
120
121 // Use variables from previous execution
122 const result = await interpreter.execute('print(f"{y}! The answer is {x}")');
123 console.log('Session result:', result);
124
125 // Execute containerized workload
126 const computeResult = await interpreter.executeCompute(
127 'docker.io/library/python:3.11-slim',
128 ['python', '-c', 'print("Hello from container!")'],
129 { cpu_cores: 1.0, memory_mb: 512, max_cost_credits: 10 }
130 );
131 console.log('Compute result:', computeResult);
132
133 // Upload and process files
134 await interpreter.uploadFiles([
135 { name: 'data.csv', content: 'name,age\nJohn,25\nJane,30' }
136 ]);
137
138 await interpreter.execute(`
139import pandas as pd
140df = pd.read_csv('data.csv')
141print(df.describe())
142 `);
143
144 } finally {
145 await interpreter.cleanup();
146 }
147}
148
149main().catch(console.error);
Get started with TypeScript SDK and Cognitora in minutes. Secure, scalable, and ready for anything.