-
Couldn't load subscription status.
- Fork 204
docs: Add AI/ML API example #61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
D1m7asis
wants to merge
8
commits into
e2b-dev:main
Choose a base branch
from
D1m7asis:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d4caf70
Add AI/ML API example
D1m7asis fd9f289
Merge branch 'main' into main
mishushakov 7e9dfcb
Enhance AIML API examples
D1m7asis cf84173
Merge branch 'main' of https://github.com/D1m7asis/e2b-cookbook-aimlapi
D1m7asis 1cd05b6
Simplify sandbox code execution and output handling
D1m7asis 0f776dd
Update README.md
D1m7asis 5b57589
Update README.md
D1m7asis 456b21c
Merge branch 'main' into main
D1m7asis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| # API keys for running the example | ||
| AIML_API_KEY=your_aimlapi_api_key_here | ||
| E2B_API_KEY=your_e2b_api_key_here |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| .env | ||
| node_modules | ||
| .eslintcache | ||
| .eslintrc.json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| # AI Code Execution with AI/ML API and E2B | ||
|
|
||
| This example demonstrates how to run LLM-generated Python code using the [AI/ML API](https://aimlapi.com/app/?utm_source=e2b&utm_medium=github&utm_campaign=integration) and [E2B Code Interpreter SDK](https://e2b.dev). | ||
|
|
||
| The AI performs a data analysis task on an uploaded CSV file, generates Python code with an AI/ML API model, and executes the code inside a sandboxed environment using E2B. | ||
|
|
||
| --- | ||
|
|
||
| ## π§ Setup | ||
|
|
||
| ### 1. Install dependencies | ||
|
|
||
| ```bash | ||
| npm install | ||
| ```` | ||
|
|
||
| ### 2. Setup environment | ||
|
|
||
| Create `.env` file: | ||
|
|
||
| ```bash | ||
| cp .env.template .env | ||
| ``` | ||
|
|
||
| Then set your: | ||
|
|
||
| * `AIML_API_KEY`: Get it at [https://aimlapi.com/app/keys](https://aimlapi.com/app/keys/?utm_source=e2b&utm_medium=github&utm_campaign=integration) | ||
| * `E2B_API_KEY`: Get it at [https://e2b.dev/docs/getting-started/api-key](https://e2b.dev/docs/getting-started/api-key) | ||
|
|
||
| ### 3. Run | ||
|
|
||
| ```bash | ||
| npm run start | ||
| ``` | ||
|
|
||
| You will see: | ||
|
|
||
| * The dataset gets uploaded | ||
| * Prompt sent to the model | ||
| * Code generated and executed in the cloud | ||
| * A result saved as `image_1.png` | ||
|
|
||
|  | ||
|
|
||
| --- | ||
|
|
||
| ## π€ Models | ||
|
|
||
| This example defaults to **`openai/gpt-4o`** via AI/ML API. | ||
| You can switch to any OpenAI-compatible model available on AI/ML API (see the Models Directory in their docs). | ||
|
|
||
| **Examples:** | ||
|
|
||
| * `openai/gpt-4o` | ||
| * `google/gemini-1.5-flash` | ||
| * `deepseek/deepseek-chat` | ||
| * and many more | ||
|
|
||
| > Ensure your API key has access to the chosen model. | ||
|
|
||
| --- | ||
|
|
||
| ## π§ Learn more | ||
|
|
||
| * [AI/ML API Documentation](https://docs.aimlapi.com/?utm_source=e2b&utm_medium=github&utm_campaign=integration) | ||
| * [E2B Code Interpreter Docs](https://e2b.dev/docs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| import fs from 'node:fs' | ||
| import path from 'node:path' | ||
| import { Sandbox, Result, OutputMessage } from '@e2b/code-interpreter' | ||
| import * as dotenv from 'dotenv' | ||
| import OpenAI from 'openai' | ||
|
|
||
| dotenv.config() | ||
|
|
||
| const AIML_API_KEY = process.env.AIML_API_KEY || '' | ||
| const E2B_API_KEY = process.env.E2B_API_KEY || '' // required by E2B SDK | ||
|
|
||
| if (!AIML_API_KEY || !E2B_API_KEY) { | ||
| console.error('Missing API key(s). Please set AIML_API_KEY and E2B_API_KEY in your .env file.') | ||
| process.exit(1) | ||
| } | ||
|
|
||
| const openai = new OpenAI({ | ||
| apiKey: AIML_API_KEY, | ||
| baseURL: 'https://api.aimlapi.com/v1', | ||
| }) | ||
|
|
||
| const MODEL_ID = 'openai/gpt-5-chat-latest' | ||
|
|
||
| // ---------- Prompts ---------- | ||
| const SYSTEM_STRAWBERRY = ` | ||
| You are a helpful assistant that can execute python code in a Jupyter notebook. | ||
| Only respond with the code to be executed and nothing else. | ||
| Respond with a Python code block in Markdown (\`\`\`python ... \`\`\`). | ||
| ` | ||
|
|
||
| const PROMPT_STRAWBERRY = "Calculate how many r's are in the word 'strawberry'" | ||
|
|
||
| const SYSTEM_LINEAR = ` | ||
| You're a Python data scientist. You are given tasks to complete and you run Python code to solve them. | ||
| Information about the csv dataset: | ||
| - It's in the \`/home/user/data.csv\` file | ||
| - The CSV file uses "," as the delimiter | ||
| - It contains statistical country-level data | ||
| Rules: | ||
| - ALWAYS FORMAT YOUR RESPONSE IN MARKDOWN | ||
| - RESPOND ONLY WITH PYTHON CODE INSIDE \`\`\`python ... \`\`\` BLOCKS | ||
| - You can use matplotlib/seaborn/pandas/numpy/etc. | ||
| - Code is executed in a secure Jupyter-like environment with internet access and preinstalled packages | ||
| ` | ||
|
|
||
| const PROMPT_LINEAR = | ||
| 'Plot a linear regression of "GDP per capita (current US$)" vs "Life expectancy at birth, total (years)" from the dataset. Drop rows with missing values.' | ||
|
|
||
| // ---------- Helpers ---------- | ||
| function extractPythonCode(markdown: string): string | null { | ||
| if (!markdown) return null | ||
|
|
||
| // 1) ```python ... ``` | ||
| const rePython = /```python\s*([\s\S]*?)```/i | ||
| const m1 = rePython.exec(markdown) | ||
| if (m1 && m1[1]) return m1[1].trim() | ||
|
|
||
| // 2) ``` ... ``` | ||
| const reAnyFence = /```\s*([\s\S]*?)```/ | ||
| const m2 = reAnyFence.exec(markdown) | ||
| if (m2 && m2[1]) return m2[1].trim() | ||
|
|
||
| // 3) Fallback: treat whole string as code if it looks python-ish | ||
| if (/import |def |print\(|len\(/.test(markdown)) return markdown.trim() | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| async function requestCode(systemPrompt: string, userPrompt: string): Promise<string> { | ||
| let response | ||
| try { | ||
| response = await openai.chat.completions.create( | ||
| { | ||
| model: MODEL_ID, | ||
| messages: [ | ||
| { role: 'system', content: systemPrompt }, | ||
| { role: 'user', content: userPrompt }, | ||
| ], | ||
| }, | ||
| { | ||
| headers: { | ||
| 'HTTP-Referer': 'https://github.com/e2b-dev/e2b-cookbook', | ||
| 'X-Title': 'e2b-cookbook:aimlapi-js', | ||
| }, | ||
| } | ||
| ) | ||
| } catch (err) { | ||
| throw new Error(`LLM request failed: ${String(err)}`) | ||
| } | ||
|
|
||
| const content = response?.choices?.[0]?.message?.content | ||
| if (content == null) { | ||
| throw new Error('Model returned null/empty content (possibly filtered). Try adjusting the prompt.') | ||
| } | ||
|
|
||
| const code = extractPythonCode(content) | ||
| if (!code) { | ||
| // Show what model returned for easier debugging | ||
| console.error('LLM response content:\n', content) | ||
| throw new Error('No Python code block found in LLM response.') | ||
| } | ||
| return code | ||
| } | ||
|
|
||
| async function runCodeInSandbox(code: string): Promise<{ results: Result[]; text: string; png?: Buffer }> { | ||
| const sandbox = await Sandbox.create() | ||
| try { | ||
| let stdoutBuf = '' | ||
| let stderrBuf = '' | ||
|
|
||
| const exec = await sandbox.runCode(code, { | ||
| onStdout: (msg: OutputMessage) => { | ||
| const s = typeof msg === 'string' ? msg : JSON.stringify(msg) | ||
| stdoutBuf += s | ||
| }, | ||
| onStderr: (msg: OutputMessage) => { | ||
| const s = typeof msg === 'string' ? msg : JSON.stringify(msg) | ||
| stderrBuf += s | ||
| }, | ||
| }) | ||
|
|
||
| if (exec.error) throw new Error(exec.error.value) | ||
|
|
||
| const first = (exec.results?.[0] ?? {}) as any | ||
| const text = | ||
| (first?.text ? String(first.text).trim() : '') || | ||
| stdoutBuf.trim() || | ||
| stderrBuf.trim() || | ||
| '' | ||
|
|
||
| let png: Buffer | undefined | ||
| if (first?.png) { | ||
| try { | ||
| png = Buffer.from(first.png, 'base64') | ||
| } catch {} | ||
| } | ||
|
|
||
| return { results: exec.results ?? [], text, png } | ||
| } finally { | ||
| await sandbox.kill() | ||
| } | ||
| } | ||
|
|
||
| async function uploadDatasetIfExists(sandbox: Sandbox, localPath = './data.csv', targetName = 'data.csv') { | ||
| const p = path.resolve(localPath) | ||
| if (!fs.existsSync(p)) return false | ||
| const buf = fs.readFileSync(p) | ||
| await sandbox.files.write(targetName, buf) | ||
| return true | ||
| } | ||
|
|
||
| // ---------- Tests ---------- | ||
| export async function testStrawberry(): Promise<string> { | ||
| const code = await requestCode(SYSTEM_STRAWBERRY, PROMPT_STRAWBERRY) | ||
| const { text } = await runCodeInSandbox(code) | ||
| if (!text.includes('3')) { | ||
| throw new Error(`Expected '3' in output, got: ${JSON.stringify(text)}`) | ||
| } | ||
| return text | ||
| } | ||
|
|
||
| export async function testLinearRegression(imageOut = 'image_1.png'): Promise<string> { | ||
| const code = await requestCode(SYSTEM_LINEAR, PROMPT_LINEAR) | ||
|
|
||
| const sandbox = await Sandbox.create() | ||
| try { | ||
| const uploaded = await uploadDatasetIfExists(sandbox, './data.csv', 'data.csv') | ||
| if (!uploaded) { | ||
| console.warn('β οΈ data.csv not found next to aimlapi.ts β running anyway, code may fail if it expects the file.') | ||
| } | ||
|
|
||
| let stdoutBuf = '' | ||
| let stderrBuf = '' | ||
|
|
||
| const exec = await sandbox.runCode(code, { | ||
| onStdout: (msg: OutputMessage) => { | ||
| const s = typeof msg === 'string' ? msg : JSON.stringify(msg) | ||
| stdoutBuf += s | ||
| }, | ||
| onStderr: (msg: OutputMessage) => { | ||
| const s = typeof msg === 'string' ? msg : JSON.stringify(msg) | ||
| stderrBuf += s | ||
| }, | ||
| }) | ||
D1m7asis marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| if (exec.error) throw new Error(exec.error.value) | ||
|
|
||
| const first = (exec.results?.[0] ?? {}) as any | ||
| const text = | ||
| (first?.text ? String(first.text).trim() : '') || | ||
| stdoutBuf.trim() || | ||
| stderrBuf.trim() || | ||
| '' | ||
|
|
||
| if (first?.png) { | ||
| try { | ||
| const png = Buffer.from(first.png, 'base64') | ||
| fs.writeFileSync(imageOut, png) | ||
| console.log(`β Image saved as ${imageOut}`) | ||
| } catch (e) { | ||
| console.warn('β οΈ Could not save image:', e) | ||
| } | ||
| } else { | ||
| console.warn('β οΈ No image result returned.') | ||
| } | ||
|
|
||
| return text | ||
| } finally { | ||
| await sandbox.kill() | ||
| } | ||
| } | ||
|
|
||
| // ---------- Entry ---------- | ||
| async function main() { | ||
| console.log('=== Strawberry test ===') | ||
| const s = await testStrawberry() | ||
| console.log(PROMPT_STRAWBERRY, '->', s) | ||
|
|
||
| console.log('\n=== Linear regression test ===') | ||
| const l = await testLinearRegression() | ||
| console.log('Linear regression output:\n', l) | ||
| } | ||
|
|
||
| if (require.main === module) { | ||
| main().catch((e) => { | ||
| console.error('β Error:', e) | ||
| process.exit(1) | ||
| }) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.