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.compute.createExecution({
56 image,
57 command,
58 cpu_cores: options.cpu_cores || 1.0,
59 memory_mb: options.memory_mb || 512,
60 max_cost_credits: options.max_cost_credits || 10,
61 storage_gb: options.storage_gb || 5
62 });
63
64 return {
65 execution_id: execution.id,
66 status: execution.status,
67 image: execution.image,
68 command: execution.command
69 };
70 } catch (error) {
71 return {
72 success: false,
73 error: error instanceof Error ? error.message : 'Unknown error'
74 };
75 }
76 }
77
78 async uploadFiles(files: Array<{ name: string; content: string; encoding?: string }>) {
79 if (!this.sessionId) {
80 await this.createSession();
81 }
82
83 try {
84 const result = await client.codeInterpreter.runWithFiles(
85 'print("Files uploaded successfully")',
86 files.map(f => ({ name: f.name, content: f.content, encoding: f.encoding || 'string' })),
87 'python',
88 this.sessionId!
89 );
90
91 return {
92 success: result.data.status === 'completed',
93 outputs: result.data.outputs
94 };
95 } catch (error) {
96 return {
97 success: false,
98 error: error instanceof Error ? error.message : 'Unknown error'
99 };
100 }
101 }
102
103 async cleanup() {
104 if (this.sessionId) {
105 await client.codeInterpreter.deleteSession(this.sessionId);
106 this.sessionId = null;
107 }
108 }
109}
110
111// Example usage
112async function main() {
113 const interpreter = new CodeInterpreter();
114
115 try {
116 // Execute Python code with persistent variables
117 await interpreter.execute('x = 42');
118 await interpreter.execute('y = "Hello World"');
119
120 // Use variables from previous execution
121 const result = await interpreter.execute('print(f"{y}! The answer is {x}")');
122 console.log('Session result:', result);
123
124 // Execute containerized workload
125 const computeResult = await interpreter.executeCompute(
126 'docker.io/library/python:3.11-slim',
127 ['python', '-c', 'print("Hello from container!")'],
128 { cpu_cores: 1.0, memory_mb: 512, max_cost_credits: 10 }
129 );
130 console.log('Compute result:', computeResult);
131
132 // Upload and process files
133 await interpreter.uploadFiles([
134 { name: 'data.csv', content: 'name,age\nJohn,25\nJane,30' }
135 ]);
136
137 await interpreter.execute(`
138import pandas as pd
139df = pd.read_csv('data.csv')
140print(df.describe())
141 `);
142
143 } finally {
144 await interpreter.cleanup();
145 }
146}
147
148main().catch(console.error);
Get started with TypeScript SDK and Cognitora in minutes. Secure, scalable, and ready for anything.