Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Update docs
Vasek Mlejnsky30116bfac7fa
diff --git a/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdxindex b1ed77e50..925e365c6 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdx@@ -22,9 +22,10 @@ This short example will show you how to use E2B Sandbox to run AI-generated code5. [Prepare the method for running AI-generated code](#5-prepare-the-method-for-running-ai-generated-code)6. [Prepare the prompt and initialize Anthropic client](#6-prepare-the-prompt-and-initialize-anthropic-client)7. [Connect the sandbox to the LLM with tool calling](#7-connect-the-sandbox-to-the-llm-with-tool-calling)-8. [Parse the response and run the AI-generated code in the sandbox](#8-parse-the-response-and-run-the-ai-generated-code-in-the-sandbox)+8. [Parse the LLM response and run the AI-generated code in the sandbox](#8-parse-the-llm-response-and-run-the-ai-generated-code-in-the-sandbox)9. [Save the generated chart](#9-save-the-generated-chart)-10. [Run the full code](#10-run-the-full-code)+10. [Run the code](#10-run-the-code)+11. [Full final code](#11-full-final-code)### 1. Install dependenciesInstall the E2B SDK and Claude SDK to your project by running the following command in your terminal.@@ -34,7 +35,7 @@ Install the E2B SDK and Claude SDK to your project by running the following commnpm i @e2b/code-interpreter @anthropic-ai/sdk dotenv``````bash {{ language: 'python' }}-pip install e2b_code_interpreter anthropic python-dotenv+pip install e2b-code-interpreter anthropic python-dotenv```</CodeGroup>@@ -127,7 +128,7 @@ The prompt we'll be using describes the dataset and the analysis we want to perfimport Anthropic from '@anthropic-ai/sdk'const prompt = `-I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at ${datasetPathInSandbox.path}.+I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at ${dataset_path_in_sandbox.path}.These are the columns:- 'id': number, id of the movie- 'original_language': string like "eng", "es", "ko", etc@@ -142,6 +143,7 @@ These are the columns:I want to better understand how the vote average has changed over the years. Write Python code that analyzes the dataset based on my request and produces right chart accordingly`const anthropic = new Anthropic()+console.log('Waiting for the model response...')const msg = await anthropic.messages.create({model: 'claude-3-5-sonnet-20240620',max_tokens: 1024,@@ -150,8 +152,6 @@ const msg = await anthropic.messages.create({``````python {{ language: 'python', description: 'main.py' }}-from dotenv import load_dotenv-load_dotenv()from anthropic import Anthropicprompt = '''@@ -234,7 +234,7 @@ msg = anthropic.messages.create(```</CodeGroup>-### 8. Parse the LLM's response and run the AI-generated code in the sandbox+### 8. Parse the LLM response and run the AI-generated code in the sandboxNow we'll parse the `msg` object to get the code from the LLM's response based on the tool we created in the previous step.Once we have the code, we'll pass it to the `runAIGeneratedCode` method in JavaScript or `run_ai_generated_code` method in Python we created in the previous step to run the code in the sandbox.@@ -284,7 +284,10 @@ async function runAIGeneratedCode(aiGeneratedCode: string) {// First let's check if the code ran successfully.if (execution.error) { // $HighlightLine- console.error('AI-generated code had an error. Try prompting the LLM differently.', execution.error) // $HighlightLine+ console.error('AI-generated code had an error.') // $HighlightLine+ console.log(execution.error.name) // $HighlightLine+ console.log(execution.error.value) // $HighlightLine+ console.log(execution.error.traceback) // $HighlightLineprocess.exit(1) // $HighlightLine} // $HighlightLine@@ -295,6 +298,7 @@ async function runAIGeneratedCode(aiGeneratedCode: string) {// Save the png to a file// The png is in base64 format.fs.writeFileSync(`chart-${resultIdx}.png`, result.png, { encoding: 'base64' }) // $HighlightLine+ console.log(`Chart saved to chart-${resultIdx}.png`) // $HighlightLineresultIdx++ // $HighlightLine} // $HighlightLine} // $HighlightLine@@ -308,7 +312,10 @@ def run_ai_generated_code(ai_generated_code: str):# First let's check if the code ran successfully.if execution.error: # $HighlightLine- print('AI-generated code had an error. Try prompting the LLM differently.', execution.error) # $HighlightLine+ print('AI-generated code had an error.') # $HighlightLine+ print(execution.error.name) # $HighlightLine+ print(execution.error.value) # $HighlightLine+ print(execution.error.traceback) # $HighlightLinesys.exit(1) # $HighlightLine# Iterate over all the results and specifically check for png files that will represent the chart.@@ -319,11 +326,12 @@ def run_ai_generated_code(ai_generated_code: str):# The png is in base64 format.with open(f'chart-{result_idx}.png', 'wb') as f: # $HighlightLinef.write(base64.b64decode(result.png)) # $HighlightLine+ print(f'Chart saved to chart-{result_idx}.png') # $HighlightLineresult_idx += 1 # $HighlightLine```</CodeGroup>-### 10. Run the full code+### 10. Run the codeNow you can run the whole code to see the results.<CodeGroup isTerminalCommand>@@ -342,4 +350,186 @@ You should see the chart in the root of your project that will look similar to tclassName="rounded w-full"alt="Chart visualizing voting average of our dataset over time"unoptimized-/>\ No newline at end of file+/>++### Full final code+Check the full code in JavaScript and Python below:+<CodeGroup>+```js {{ language: 'js', description: 'index.ts' }}+import 'dotenv/config'+import fs from 'fs'+import Anthropic from '@anthropic-ai/sdk'+import { Sandbox } from '@e2b/code-interpreter'++// Create sandbox+const sbx = await Sandbox.create()++// Upload the dataset to the sandbox+const content = fs.readFileSync('dataset.csv')+const datasetPathInSandbox = await sbx.files.write('/home/user/dataset.csv', content)++async function runAIGeneratedCode(aiGeneratedCode: string) {+ const execution = await sbx.runCode(aiGeneratedCode)+ if (execution.error) {+ console.error('AI-generated code had an error.')+ console.log(execution.error.name)+ console.log(execution.error.value)+ console.log(execution.error.traceback)+ process.exit(1)+ }+ // Iterate over all the results and specifically check for png files that will represent the chart.+ let resultIdx = 0+ for (const result of execution.results) {+ if (result.png) {+ // Save the png to a file+ // The png is in base64 format.+ fs.writeFileSync(`chart-${resultIdx}.png`, result.png, { encoding: 'base64' })+ console.log('Chart saved to chart-${resultIdx}.png')+ resultIdx+++ }+ }+}++const prompt = `+I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at ${datasetPathInSandbox.path}.+These are the columns:+- 'id': number, id of the movie+- 'original_language': string like "eng", "es", "ko", etc+- 'original_title': string that's name of the movie in the original language+- 'overview': string about the movie+- 'popularity': float, from 0 to 9137.939. It's not normalized at all and there are outliers+- 'release_date': date in the format yyyy-mm-dd+- 'title': string that's the name of the movie in english+- 'vote_average': float number between 0 and 10 that's representing viewers voting average+- 'vote_count': int for how many viewers voted++I want to better understand how the vote average has changed over the years. Write Python code that analyzes the dataset based on my request and produces right chart accordingly`++const anthropic = new Anthropic()+console.log('Waiting for the model response...')+const msg = await anthropic.messages.create({+ model: 'claude-3-5-sonnet-20240620',+ max_tokens: 1024,+ messages: [{ role: 'user', content: prompt }],+ tools: [+ {+ name: 'run_python_code',+ description: 'Run Python code',+ input_schema: {+ type: 'object',+ properties: {+ code: {+ type: 'string',+ description: 'The Python code to run',+ },+ },+ required: ['code'],+ },+ },+ ],+})++interface CodeRunToolInput {+ code: string+}++for (const contentBlock of msg.content) {+ if (contentBlock.type === 'tool_use') {+ if (contentBlock.name === 'run_python_code') {+ const code = (contentBlock.input as CodeRunToolInput).code+ console.log('Will run following code in the sandbox', code)+ // Execute the code in the sandbox+ await runAIGeneratedCode(code)+ }+ }+}+```+```python {{ language: 'python', description: 'main.py' }}+import sys+import base64+from dotenv import load_dotenv+load_dotenv()+from e2b_code_interpreter import Sandbox+from anthropic import Anthropic++# Create sandbox+sbx = Sandbox()++# Upload the dataset to the sandbox+with open("../dataset.csv", "rb") as f:+ dataset_path_in_sandbox = sbx.files.write("dataset.csv", f)+++def run_ai_generated_code(ai_generated_code: str):+ print('Running the code in the sandbox....')+ execution = sbx.notebook.exec_cell(ai_generated_code)+ print('Code execution finished!')++ # First let's check if the code ran successfully.+ if execution.error:+ print('AI-generated code had an error.')+ print(execution.error.name)+ print(execution.error.value)+ print(execution.error.traceback)+ sys.exit(1)++ # Iterate over all the results and specifically check for png files that will represent the chart.+ result_idx = 0+ for result in execution.results:+ if result.png:+ # Save the png to a file+ # The png is in base64 format.+ with open(f'chart-{result_idx}.png', 'wb') as f:+ f.write(base64.b64decode(result.png))+ print(f'Chart saved to chart-{result_idx}.png')+ result_idx += 1++prompt = f"""+I have a CSV file about movies. It has about 10k rows. It's saved in the sandbox at {dataset_path_in_sandbox.path}.+These are the columns:+- 'id': number, id of the movie+- 'original_language': string like "eng", "es", "ko", etc+- 'original_title': string that's name of the movie in the original language+- 'overview': string about the movie+- 'popularity': float, from 0 to 9137.939. It's not normalized at all and there are outliers+- 'release_date': date in the format yyyy-mm-dd+- 'title': string that's the name of the movie in english+- 'vote_average': float number between 0 and 10 that's representing viewers voting average+- 'vote_count': int for how many viewers voted++I want to better understand how the vote average has changed over the years.+Write Python code that analyzes the dataset based on my request and produces right chart accordingly"""++anthropic = Anthropic()+print("Waiting for model response...")+msg = anthropic.messages.create(+ model='claude-3-5-sonnet-20240620',+ max_tokens=1024,+ messages=[+ {"role": "user", "content": prompt}+ ],+ tools=[+ {+ "name": "run_python_code",+ "description": "Run Python code",+ "input_schema": {+ "type": "object",+ "properties": {+ "code": { "type": "string", "description": "The Python code to run" },+ },+ "required": ["code"]+ }+ }+ ]+)++for content_block in msg.content:+ if content_block.type == "tool_use":+ if content_block.name == "run_python_code":+ code = content_block.input["code"]+ print("Will run following code in the sandbox", code)+ # Execute the code in the sandbox+ run_ai_generated_code(code)++```+</CodeGroup>diff --git a/apps/web/src/app/(docs)/docs/quickstart/page.mdx b/apps/web/src/app/(docs)/docs/quickstart/page.mdxindex 6242b3767..51a10361a 100644--- a/apps/web/src/app/(docs)/docs/quickstart/page.mdx+++ b/apps/web/src/app/(docs)/docs/quickstart/page.mdx@@ -25,7 +25,7 @@ Install the E2B SDK to your project by running the following command in your ternpm i @e2b/code-interpreter dotenv``````bash {{ language: 'python' }}-pip install e2b_code_interpreter python-dotenv+pip install e2b-code-interpreter python-dotenv```</CodeGroup>