-
Notifications
You must be signed in to change notification settings - Fork 86
Docs/agentcube website #405
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
vanshika2720
wants to merge
4
commits into
volcano-sh:main
Choose a base branch
from
vanshika2720:docs/agentcube-website
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 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c5a941c
docs: add complete AgentCube documentation to website
vanshika2720 03a14d8
docs: address review feedback
vanshika2720 258bc79
docs: fix review issues and improve language
vanshika2720 55af437
docs: clarify env var requirement in LangChain guide
vanshika2720 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
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
311 changes: 311 additions & 0 deletions
311
docs/agentcube/docs/developer-guide/code-interpreter-python-sdk.md
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,311 @@ | ||
| --- | ||
| sidebar_position: 7 | ||
| --- | ||
|
|
||
| # Python SDK Guide | ||
|
|
||
| The `agentcube` Python SDK wraps the Workload Manager and PicoD APIs into a simple client. It manages session lifecycle, RSA key generation, and JWT signing automatically. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| Before you begin, ensure your environment meets the following requirements: | ||
|
|
||
| - **Python**: Version 3.10 or later | ||
| - **Network Access**: Access to the Workload Manager (Control Plane) and Router (Data Plane) | ||
| - **AgentCube deployed**: Follow the [Getting Started Guide](../getting-started.md) to set up AgentCube on your cluster | ||
|
|
||
| ### Install the SDK | ||
|
|
||
| ```bash | ||
| pip install agentcube-sdk | ||
| ``` | ||
|
|
||
| ### Set Up Access | ||
|
|
||
| For local development, use port-forwarding: | ||
|
|
||
| ```bash | ||
| # Terminal 1: Forward the Workload Manager | ||
| kubectl port-forward -n agentcube svc/workloadmanager 8080:8080 | ||
|
|
||
| # Terminal 2: Forward the Router | ||
| kubectl port-forward -n agentcube svc/agentcube-router 8081:8080 | ||
| ``` | ||
|
|
||
| Then set environment variables: | ||
|
|
||
| ```bash | ||
| export WORKLOAD_MANAGER_URL="http://localhost:8080" | ||
| export ROUTER_URL="http://localhost:8081" | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 1. Initialize the Client | ||
|
|
||
| The `CodeInterpreterClient` is the main entry point. Use it as a context manager (recommended) to ensure sessions are automatically cleaned up. | ||
|
|
||
| ### Configuration Parameters | ||
|
|
||
| | Parameter | Type | Default | Description | | ||
| | ---------------------- | ------ | -------------------------- | ---------------------------------------------------------------- | | ||
| | `name` | `str` | `"simple-codeinterpreter"` | Name of the `CodeInterpreter` CRD template | | ||
| | `namespace` | `str` | `"default"` | Kubernetes namespace where the CRD exists | | ||
| | `ttl` | `int` | `3600` | Session time-to-live in seconds | | ||
| | `workload_manager_url` | `str` | `None` | Control Plane URL (falls back to `WORKLOAD_MANAGER_URL` env var) | | ||
| | `router_url` | `str` | `None` | Data Plane Router URL (falls back to `ROUTER_URL` env var) | | ||
|
vanshika2720 marked this conversation as resolved.
|
||
| | `auth_token` | `str` | `None` | Auth token (falls back to Kubernetes ServiceAccount token) | | ||
| | `session_id` | `str` | `None` | Resume an existing session instead of creating a new one | | ||
| | `verbose` | `bool` | `False` | Enable debug logging | | ||
|
|
||
| ### Environment Variables | ||
|
|
||
| | Variable | Description | | ||
| | ---------------------- | ---------------------------------------------------------- | | ||
| | `WORKLOAD_MANAGER_URL` | Control Plane URL (required if not passed as argument) | | ||
| | `ROUTER_URL` | Data Plane Router URL (required if not passed as argument) | | ||
|
|
||
| ### Example: Basic Initialization | ||
|
|
||
| ```python | ||
| from agentcube import CodeInterpreterClient | ||
|
|
||
| # Initialize using a context manager (recommended) | ||
| with CodeInterpreterClient(name="my-interpreter", verbose=True) as client: | ||
| print(f"Session ID: {client.session_id}") | ||
| # ... use the client | ||
| # Session is automatically stopped here | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 2. Execute Commands and Code | ||
|
|
||
| The SDK provides distinct methods for running shell commands and executing code blocks. | ||
|
|
||
| ### Run Shell Commands | ||
|
|
||
| Use `execute_command` to run system operations on the remote agent. | ||
|
|
||
| ```python | ||
| with CodeInterpreterClient(name="my-interpreter") as client: | ||
| # Check current user and working directory | ||
| output = client.execute_command("whoami && pwd") | ||
| print(output) | ||
|
|
||
| # Install a package | ||
| client.execute_command("pip install numpy") | ||
| ``` | ||
|
|
||
| ### Run Code | ||
|
|
||
| Use `run_code` to execute a code block. Supported languages: `"python"` (or `"py"`, `"python3"`) and `"bash"` (or `"sh"`). | ||
|
|
||
| ```python | ||
| with CodeInterpreterClient(name="my-interpreter") as client: | ||
| # Run Python code | ||
| script = """ | ||
| import math | ||
| results = [math.sqrt(i) for i in range(1, 6)] | ||
| print(results) | ||
| """ | ||
| result = client.run_code(language="python", code=script) | ||
| print(result) | ||
| # Output: [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979] | ||
|
|
||
| # Run Bash | ||
| bash_result = client.run_code(language="bash", code="echo 'Hello from Bash!'") | ||
| print(bash_result) | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 3. File Management | ||
|
|
||
| Transfer files between your local environment and the remote sandbox. | ||
|
|
||
| ### Upload Files | ||
|
|
||
| Use `upload_file` to send a local file to the sandbox. | ||
|
|
||
| ```python | ||
| with CodeInterpreterClient(name="my-interpreter") as client: | ||
| # Upload a data file for processing | ||
| client.upload_file( | ||
| local_path="./local_data.csv", | ||
| remote_path="/workspace/data.csv" | ||
| ) | ||
| ``` | ||
|
|
||
| ### Download Files | ||
|
|
||
| Use `download_file` to retrieve results generated by your scripts. | ||
|
|
||
| ```python | ||
| with CodeInterpreterClient(name="my-interpreter") as client: | ||
| # Download the processed report | ||
| client.download_file( | ||
| remote_path="/workspace/report.json", | ||
| local_path="./final_report.json" | ||
| ) | ||
| ``` | ||
|
|
||
| ### Write Content Directly | ||
|
|
||
| Use `write_file` to create text files on the remote sandbox without needing a local source file. | ||
|
|
||
| ```python | ||
| with CodeInterpreterClient(name="my-interpreter") as client: | ||
| client.write_file( | ||
| content="print('Hello World')", | ||
| remote_path="/workspace/hello.py" | ||
| ) | ||
| # Execute the file we just wrote | ||
| output = client.execute_command("python3 /workspace/hello.py") | ||
| print(output) # "Hello World" | ||
| ``` | ||
|
|
||
| ### List Files | ||
|
|
||
| Use `list_files` to list files and directories in a specified path. | ||
|
|
||
| ```python | ||
| with CodeInterpreterClient(name="my-interpreter") as client: | ||
| files = client.list_files("/workspace") | ||
| for f in files: | ||
| print(f"{f['name']} - {f['size']} bytes") | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 4. Best Practices: Using Context Managers | ||
|
|
||
| To ensure that remote resources are terminated and local connections are closed properly, it is **strongly recommended** to use the `with` statement. | ||
|
|
||
| **Complete Example:** | ||
|
|
||
| ```python | ||
| from agentcube import CodeInterpreterClient | ||
|
|
||
| def process_data_task(): | ||
| with CodeInterpreterClient(name="my-interpreter", ttl=600) as sandbox: | ||
| print(f"Session ID: {sandbox.session_id}") | ||
|
|
||
| # 1. Create a Python script remotely | ||
| script_content = """ | ||
| import json | ||
| data = {"status": "processed", "value": 42} | ||
| with open('/workspace/result.json', 'w') as f: | ||
| json.dump(data, f) | ||
| print("Data processed.") | ||
| """ | ||
| # 2. Execute the script | ||
| logs = sandbox.run_code("python", script_content) | ||
| print(f"Remote Logs: {logs}") | ||
|
|
||
| # 3. Download the result | ||
| sandbox.download_file("/workspace/result.json", "./result.json") | ||
| print("File downloaded to ./result.json") | ||
|
|
||
| # Session automatically stops (sandbox deleted) here | ||
|
|
||
| process_data_task() | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 5. Manual Lifecycle Management | ||
|
|
||
| If you cannot use a context manager (e.g., in a long-running web server), you must manually call `stop()` to free resources. | ||
|
|
||
| ```python | ||
| from agentcube import CodeInterpreterClient | ||
|
|
||
| client = CodeInterpreterClient(name="my-interpreter", ttl=3600) | ||
|
|
||
| try: | ||
| output = client.execute_command("echo 'Running long task...'") | ||
| print(output) | ||
| # ... more operations | ||
| finally: | ||
| # Critical: deletes the remote sandbox and closes connections | ||
| client.stop() | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 6. Session Reuse | ||
|
|
||
| You can reuse an existing session by passing its `session_id` to a new client. This is useful for multi-step workflows where you want to preserve filesystem state across multiple scripts or processes. | ||
|
|
||
| :::important | ||
| Session reuse preserves **filesystem state only**. Each `run_code` call spawns a new process, so **Python variables do NOT persist** across calls. Use files to pass state between calls. | ||
| ::: | ||
|
|
||
| ```python | ||
| from agentcube import CodeInterpreterClient | ||
|
|
||
| # Step 1: Create session and write a file | ||
| client1 = CodeInterpreterClient(name="my-interpreter") | ||
| session_id = client1.session_id | ||
| client1.write_file("42", "/workspace/value.txt") | ||
| # Do NOT call stop() — we want the session to persist | ||
|
|
||
| # Step 2: Reuse the session in a new client instance | ||
| client2 = CodeInterpreterClient(name="my-interpreter", session_id=session_id) | ||
| result = client2.run_code("python", "print(open('/workspace/value.txt').read())") | ||
| print(result) # "42" | ||
|
|
||
| client2.stop() # Clean up when done | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 7. Machine Learning Workflow Example | ||
|
|
||
| Here is a complete example demonstrating a multi-step ML workflow using the SDK: | ||
|
|
||
| ```python | ||
| from agentcube import CodeInterpreterClient | ||
|
|
||
| with CodeInterpreterClient(name="ml-interpreter", ttl=3600) as ci: | ||
|
|
||
| # Step 1: Write requirements | ||
| ci.write_file( | ||
| content="pandas\nnumpy\nscikit-learn", | ||
| remote_path="/workspace/requirements.txt" | ||
| ) | ||
|
|
||
| # Step 2: Install dependencies | ||
| ci.execute_command("pip install -r /workspace/requirements.txt") | ||
|
|
||
| # Step 3: Upload training data | ||
| ci.upload_file( | ||
| local_path="./data/train.csv", | ||
| remote_path="/workspace/train.csv" | ||
| ) | ||
|
|
||
| # Step 4: Train model | ||
| training_code = """ | ||
| import pandas as pd | ||
| from sklearn.linear_model import LinearRegression | ||
| import pickle | ||
|
|
||
| df = pd.read_csv('/workspace/train.csv') | ||
| X, y = df[['feature1', 'feature2']], df['target'] | ||
|
|
||
| model = LinearRegression().fit(X, y) | ||
| pickle.dump(model, open('/workspace/model.pkl', 'wb')) | ||
| print(f'Model R² score: {model.score(X, y):.4f}') | ||
| """ | ||
| result = ci.run_code("python", training_code) | ||
| print(result) | ||
|
|
||
| # Step 5: Download the trained model | ||
| ci.download_file( | ||
| remote_path="/workspace/model.pkl", | ||
| local_path="./models/model.pkl" | ||
| ) | ||
|
|
||
| print("Workflow complete! Model saved to ./models/model.pkl") | ||
| ``` | ||
Oops, something went wrong.
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.