Add python hello world

This commit is contained in:
Vasek Mlejnsky 2024-04-26 17:24:54 -07:00
parent 33fab48bdf
commit 58a6bb4d80
6 changed files with 372 additions and 126 deletions

View File

@ -0,0 +1,244 @@
import Image from 'next/image'
import imgChart from '@/images/hello-world-chart.png'
# Hello World
This short Python guide will show you basics of E2B:
- Connect the code interpreter to an LLM
- Prompt the LLM to generate the Python code
- Execute the AI-generated Python code in a secure E2B sandbox
### Get full code
Check out the [full code in our cookbook](/todo).
### Overview
1. Install Code Interpreter SDK
1. Prepare the prompt and tools for LLM
1. Prepare code interpreting
1. Call LLM and parse response with tools
1. Create code interpreter and run everything
1. Save generated chart
## 1. Install Code Interpreter SDK
The Code Interpreter SDK allows you to run AI-generated code in a secure small VM - **E2B sandbox** - made for AI code execution.
Inside the sandbox is a Jupyter server running that you can control from our SDK through the `notebook.execCell()` method.
Check out the [SDK's repository on GitHub](https://github.com/e2b-dev/code-interpreter).
<CodeGroup isRunnable={false}>
```bash {{ language: 'python' }}
pip install e2b_code_interpreter python-dotenv
```
</CodeGroup>
Get your E2B API key [here](/getting-started/api-key) and save it to `.env` in your root directory.
<CodeGroup isFileName title=".env" isRunnable={false}>
```bash
E2B_API_KEY="e2b-api-key"
```
</CodeGroup>
## 2. Prepare the prompt and tools for LLM
We'll be using Anthropic's [Claude 3 Opus](https://www.anthropic.com/news/claude-3-family) model but E2B works with any LLM so feel free to pick any you want!
<Note>
Usually, all you need from the model is just support for tool use. If the LLM doesn't support tool use, you can ask the LLM to respond with Markdown or XML and parse the LLM's output on your own. Then just pass the parsed code from code blocks to the code interpreter.
</Note>
Create the `model.py` file and paste the following code.
<CodeGroup isFileName title="model.py" isRunnable={false}>
```python
MODEL_NAME = "claude-3-opus-20240229"
SYSTEM_PROMPT = """
## your job & context
you are a python data scientist. you are given tasks to complete and you run python code to solve them.
- the python code runs in jupyter notebook.
- every time you call `execute_python` tool, the python code is executed in a separate cell. it's okay to multiple calls to `execute_python`.
- display visualizations using matplotlib or any other visualization library directly in the notebook. don't worry about saving the visualizations to a file.
- you have access to the internet and can make api requests.
- you also have access to the filesystem and can read/write files.
- you can install any pip package (if it exists) if you need to but the usual packages for data analysis are already preinstalled.
- you can run any python code you want, everything is running in a secure sandbox environment.
"""
tools = [
{
"name": "execute_python",
"description": "Execute python code in a Jupyter notebook cell and returns any result, stdout, stderr, display_data, and error.",
"input_schema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "The python code to execute in a single cell."
}
},
"required": ["code"]
}
}
]
```
</CodeGroup>
This defines our system prompt and the `tools` dictionary with available tools for the LLM - namely the `"execute_python"` tool.
A little bit later, we'll connect `"execute_python"` to the E2B's code interpretrer.
## 3. Prepare code interpreting
We'll create a new function called `code_interpret()` in a separate file `code_interpreter.py`.
<CodeGroup isFileName title="code_interpreter.py" isRunnable={false}>
```python {{ language: 'python' }}
from e2b_code_interpreter import CodeInterpreter
def code_interpret(code_interpreter: CodeInterpreter, code: str):
print(f"\n{'='*50}\n> Running following AI-generated code:\n{code}\n{'='*50}")
exec = code_interpreter.notebook.exec_cell(
code,
# You can stream logs from the code interpreter
# on_stderr=lambda stderr: print("\n[Code Interpreter stdout]", stderr),
# on_stdout=lambda stdout: print("\n[Code Interpreter stderr]", stdout),
#
# You can also stream additional results like charts, images, etc.
# on_result=...
)
if exec.error:
print("[Code Interpreter error]", exec.error) # Runtime error
else:
return exec.results, exec.logs
```
</CodeGroup>
This function takes the `CodeInterpreter` object from our SDK, and `code` as paramaters.
The `code` parameter is the code generated by the LLM.
Inside the function, we call the `code_interpreter.notebook.exec_cell()` method. The `exec_cell()` takes `code` argument, and executes this `code` inside E2B sandbox.
## 4. Call LLM and parse response with tools
We're using Claude 3 Opus. Get your [Anthropic API key](https://console.anthropic.com/), save it to `.env` file, and install the [Anthropic SDK](https://docs.anthropic.com/claude/reference/client-sdks).
<CodeGroup isFileName title=".env" isRunnable={false}>
```bash
ANTHROPIC_API_KEY="anthropic-api-key"
```
</CodeGroup>
<CodeGroup isRunnable={false}>
```bash {{ language: 'python' }}
pip install anthropic
```
</CodeGroup>
Now we'll put everything together.
Create the `main.py` file, import dependencies, and create the `chat()` function that will do the LLM calling and tool parsing.
<CodeGroup isFileName title="main.py" isRunnable={false}>
```python {{ language: 'python' }}
from dotenv import load_dotenv
from anthropic import Anthropic
from typing import List
from e2b_code_interpreter import CodeInterpreter, Result
from e2b_hello_world.model import MODEL_NAME, SYSTEM_PROMPT, tools
from e2b_hello_world.code_interpreter import code_interpret
# Load the .env file
load_dotenv()
client = Anthropic()
def chat(code_interpreter: CodeInterpreter, user_message: str) -> List[Result]:
print(f"\n{'='*50}\nUser Message: {user_message}\n{'='*50}")
message = client.beta.tools.messages.create(
model=MODEL_NAME,
system=SYSTEM_PROMPT,
max_tokens=4096,
messages=[{"role": "user", "content": user_message}],
tools=tools,
)
print(f"\n{'='*50}\nModel response: {message.content}\n{'='*50}")
if message.stop_reason == "tool_use":
tool_use = next(block for block in message.content if block.type == "tool_use")
tool_name = tool_use.name
tool_input = tool_use.input
print(f"\n{'='*50}\nUsing tool: {tool_name}\n{'='*50}")
if tool_name == "execute_python":
return code_interpret(code_interpreter, tool_input["code"])
return []
```
</CodeGroup>
## 5. Create code interpreter and run everything
Now we put all together, and run our program. In the end of `main.py` add following code prompting the LLM to visualize a distribution of height of men and print the median.
<CodeGroup isFileName title="main.py" isRunnable={false}>
```python {{ language: 'python' }}
def main():
user_message = "Visualize a distribution of height of men based on the latest data you know. Also print the median value."
# Create the CodeInterpreter object and save it as code_interpreter
with CodeInterpreter() as code_interpreter:
code_interpreter_results, code_interpreter_logs = chat(
code_interpreter,
user_message,
)
print(code_interpreter_logs)
first_result= code_interpreter_results[0]
print(first_result)
```
</CodeGroup>
You should see similar results to this:
```sh
stdout=['The median male height is 175.5 cm\n'] stderr=[]
<Figure size 800x400 with 1 Axes>
```
We got our median in the logs (`stdout`, and `stderr`) but we also something intering in `first_result`. It looks like a chart.
```sh
<Figure size 800x400 with 1 Axes>
```
6. Save generated chart
This looks like a plot. Let's save it to a file. Add the following to the end of `main.py`.
<CodeGroup isFileName title="main.py" isRunnable={false}>
```python {{ language: 'python' }}
# If we received a chart in PNG form, we can visualize it
if first_result.png:
# Decode the base64 encoded PNG data
png_data = base64.b64decode(first_result.png)
# Generate a unique filename for the PNG
filename = f"chart.png"
# Save the decoded PNG data to a file
with open(filename, "wb") as f:
f.write(png_data)
print(f"Saved chart to {filename}")
```
</CodeGroup>
The chart got saved to the `chart.png` file and it should look similar to this:
<Image
src={imgChart}
className="rounded w-full"
alt="Chart visualizing distribution height of men"
unoptimized
/>

View File

@ -1,10 +1,18 @@
// import { useRouter } from 'next/navigation'
// export default function Page() {
// redirect('/')
// }
import { Button } from '@/components/Button'
import { HeroPattern } from '@/components/HeroPattern'
export default function NotFound() {
return (
<>
<HeroPattern/>
<HeroPattern />
<div className="mx-auto flex h-full max-w-xl flex-col items-center justify-center py-16 text-center">
<p className="text-sm font-semibold text-zinc-900 dark:text-white">404</p>
<h1 className="mt-2 text-2xl font-bold text-zinc-900 dark:text-white">

View File

@ -5,81 +5,25 @@ import { Button } from '@/components/Button'
<HeroPattern />
# Sandbox for AI Apps & Agents
# Code interpreting for your AI app
E2B's [Code Interpreter SDK](https://github.com/e2b-dev/code-interpreter) allows you to add code interpreting capabilities to your AI apps. {{ className: 'lead' }}
The E2B Sandbox is a secure way to run your AI app. It is a long-running cloud environment where you can let any LLM (GPTs, Claude, local LLMs, etc) use tools exactly like you would do locally. {{ className: 'lead' }}
## How Sandboxes Work
Under the hood, the sandboxes are general purpose machines powered by Ubuntu. Learn more about all features and comparison to other services [here](/sandbox/overview).
## What Can You Build with Sandboxes
The sandboxes can do majority of the things your AI app or agent can do locally. A few popular use cases are:
- **AI data analysis**
- **Code interpreter**
- **Run LLM-generated code**
- **Coding copilots**
- **AI-powered browsers in the cloud**
## Quick start
### 1. Create an account
[Sign in](/sign-in) with your GitHub acccount.
### 2. Get your API key
After sign in, get [your API key](/getting-started/api-key) and set it in the `E2B_API_KEY` environment variable.
### 3. Install the E2B SDK
We offer both JS and Python SDK.
With code interpreting, you can build apps like:
- AI code execution
- Data analysis with AI
- AI tutors
- Reasoning modules for LLM
## Install Code Interpreter SDK
<CodeGroup isRunnable={false}>
```bash {{ language: 'js' }}
npm install e2b
npm i @e2b/code-interpreter
```
```bash {{ language: 'python' }}
pip install e2b
pip install e2b_code_interpreter python-dotenv
```
</CodeGroup>
### 4. Start up the sandbox
Sandbox is an isolated cloud environment for your AI app, agent, assistant, etc.
## Hello World example
Check out the [JavaScript](/hello-world/js) and [Python](/hello-world/py) Hello World guides to get started. {{ className: 'lead' }}
<CodeGroup isRunnable={false}>
```js {{ language: 'js' }}
// 1. Import E2B
import { Sandbox } from 'e2b'
// 2. Get your Sandbox session
const sandbox = await Sandbox.create()
// 3. Close the sandbox once done
await sandbox.close()
```
```python {{ language: 'python' }}
# 1. Import E2B
from e2b import Sandbox
# 2. Get your Sandbox session
sandbox = Sandbox()
# 3. Close the sandbox once done
sandbox.close()
```
</CodeGroup>
{/* <Note>
By default the `base` sandbox supports NodeJS 20 and Python 3.10. If you want customize your sandbox (copy files, install dependencies, etc), check out [Sandbox Templates](/sandbox/templates/custom).
</Note> */}
### Custom sandboxes
You can create a custom sandbox with preinstalled libraries and prepared files by creating your own [Sandbox Template](/sandbox/templates/overview).
{/* We offer a few [premade sandbox templates](/sandbox/template/prebuilt) for common use cases such as building code interpreters or AI browser assistans. */}
### 🎉 Build your AI app
Now you can let your AI app control the sandbox by using [Sandbox API](/sandbox/api/envs).

View File

@ -0,0 +1,4 @@
# Supported LLMs and AI frameworks
<Note>
E2B is LLM agnostic - it supports any LLM models and any AI frameworks.
</Note>

View File

@ -14,7 +14,6 @@ import {
FolderTree,
Hammer,
HardDrive,
HeartHandshake,
KeyRound,
Link,
PencilRuler,
@ -31,9 +30,35 @@ import {
export const routes = [
{
title: 'Overview',
title: 'Getting Started',
links: [
{ title: 'Introduction', href: '/' },
{
title: 'Installation',
href: '/',
},
{
title: 'helloWorld.[js|ts]',
href: '/hello-world/js',
isFontMono: true,
},
{
title: 'hello_world.py',
href: '/hello-world/py',
isFontMono: true,
},
{
title: 'Supported LLMs and AI frameworks',
href: '/supported',
},
{
title: 'What\'s Code Interpreting?',
href: '/code-interpreting',
},
{
icon: <KeyRound strokeWidth={1} size={20} />,
title: 'API Key',
href: '/getting-started/api-key',
},
{
icon: <DollarSign strokeWidth={1} size={20} />,
title: 'Pricing',
@ -44,11 +69,11 @@ export const routes = [
title: 'Track usage',
href: '/usage',
},
{
icon: <HeartHandshake strokeWidth={1} size={20} />,
title: 'Open source',
href: '/open-source',
},
// {
// icon: <HeartHandshake strokeWidth={1} size={20} />,
// title: 'Open source',
// href: '/open-source',
// },
{
icon: <ShieldQuestion strokeWidth={1} size={20} />,
title: 'Getting help',
@ -57,43 +82,64 @@ export const routes = [
],
},
{
title: 'Getting Started',
title: 'Guides',
links: [
{
icon: <Settings strokeWidth={1} size={20} />,
title: 'Installation',
href: '/getting-started/installation',
},
{
icon: <KeyRound strokeWidth={1} size={20} />,
title: 'API Key',
href: '/getting-started/api-key',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Custom Code Interpreter',
title: 'E2B Cookbook',
href: '/guide/simple-gpt4-code-interpreter',
//
// title: 'Hello World: Simple AI Junior Developer',
// href: '/guide/simple-ai-junior-developer',
},
// {
// icon: (
// <Hammer
// strokeWidth={1}
// size={20}
// />
// ),
// title: 'Guide: Run LLM-generated code',
// href: '/guide/simple-gpt4-code-interpreter',
// //
// // title: 'Hello World: Simple AI Junior Developer',
// // href: '/guide/simple-ai-junior-developer',
// },
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Code Interpreter with Llama-3',
href: '/guide/simple-gpt4-code-interpreter',
//
// title: 'Hello World: Simple AI Junior Developer',
// href: '/guide/simple-ai-junior-developer',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Code Interpreter with OpenAI models',
href: '/guide/simple-gpt4-code-interpreter',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Code Interpreter with Claude 3 Opus',
href: '/guide/simple-gpt4-code-interpreter',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Secure Sandbox for Devin-like agent',
href: '/guide/simple-gpt4-code-interpreter',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Generative UI with Next.js',
href: '/guide/simple-gpt4-code-interpreter',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Usage with LangChain',
href: '/guide/simple-gpt4-code-interpreter',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Upload and analyze CSV files with AI',
href: '/guide/simple-gpt4-code-interpreter',
},
{
icon: <Hammer strokeWidth={1} size={20} />,
title: 'Guide: Customize sandbox compute (TODO: Move this away from guides?)',
href: '/guide/simple-gpt4-code-interpreter',
},
],
},
{
title: 'Code Interpreter API',
title: 'E2B SDK: Code Interpreter',
links: [
{
icon: <FileCode strokeWidth={1} size={20} />,
@ -102,7 +148,7 @@ export const routes = [
},
{
icon: <Terminal strokeWidth={1} size={20} />,
title: 'Code Execution',
title: 'AI Code Execution',
href: '/code-interpreter/execution',
},
{
@ -112,7 +158,12 @@ export const routes = [
},
{
icon: <Wrench strokeWidth={1} size={20} />,
title: 'Extending Code Interpreter',
title: 'Supported languages',
href: '/code-interpreter/template',
},
{
icon: <Wrench strokeWidth={1} size={20} />,
title: 'Customization',
href: '/code-interpreter/template',
},
{
@ -123,8 +174,22 @@ export const routes = [
],
},
{
title: 'Sandbox API',
title: 'E2B SDK: Core Sandbox',
links: [
{
title: 'Overview',
href: '/sandbox/overview',
},
{
icon: <Cpu strokeWidth={1} size={20} />,
title: 'Compute',
href: '/sandbox/compute',
},
{
icon: <PencilRuler strokeWidth={1} size={20} />,
title: 'Customization',
href: '/sandbox/custom',
},
{
icon: <Variable strokeWidth={1} size={20} />,
title: 'Environment Variables',
@ -178,7 +243,7 @@ export const routes = [
],
},
{
title: 'CLI API',
title: 'CLI',
links: [
{
icon: <Settings strokeWidth={1} size={20} />,
@ -192,25 +257,6 @@ export const routes = [
},
],
},
{
title: 'Sandbox',
links: [
{
title: 'Overview',
href: '/sandbox/overview',
},
{
icon: <Cpu strokeWidth={1} size={20} />,
title: 'Compute',
href: '/sandbox/compute',
},
{
icon: <PencilRuler strokeWidth={1} size={20} />,
title: 'Customization',
href: '/sandbox/custom',
},
],
},
{
title: 'Custom Sandboxes',
links: [

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB