Skip to content

Add Claude Computer Use Agent #44

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
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions agentstack/templates/crewai/tools/claude_computer_use_tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
from crewai_tools import tool
from dotenv import load_dotenv
import os
import subprocess
import json
import time
import requests

load_dotenv()

api_key = os.getenv('CLAUDE_API_KEY')

def check_docker_running():
"""Check if Docker daemon is running."""
try:
subprocess.run(['docker', 'info'], capture_output=True, check=True)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
return False

def check_container_exists(container_name):
"""Check if a container with the given name already exists."""
try:
result = subprocess.run(
['docker', 'ps', '-a', '--format', '{{.Names}}'],
capture_output=True,
text=True,
check=True
)
return container_name in result.stdout.split('\n')
except subprocess.CalledProcessError:
return False

def check_container_status(container_name):
"""Check if container is running and service is responding."""
try:
# Check if container is running
result = subprocess.run(
['docker', 'inspect', '--format', '{{.State.Running}}', container_name],
capture_output=True,
text=True,
check=True
)
if result.stdout.strip() != 'true':
return False

# Check if service is responding
try:
response = requests.get('http://localhost:8080', timeout=1)
return response.status_code == 200
except requests.RequestException:
return False

except subprocess.CalledProcessError:
return False

def wait_for_service_ready(container_name, timeout=60):
"""Wait for the service to be ready with timeout."""
print(f"Waiting for {container_name} to be ready...")
start_time = time.time()
while time.time() - start_time < timeout:
if check_container_status(container_name):
return True
time.sleep(2)
print(".", end="", flush=True)
print("\nTimeout reached")
return False

@tool("Start claude computer use")
def start_claude_computer_use():
"""
Tool to run Claude computer use using Claude's docker image
"""
container_name = "claude-computer-use"

if not check_docker_running():
print("Docker daemon is not running")
return False

if check_container_exists(container_name):
try:
print(f"Removing existing container '{container_name}'...")
subprocess.run(['docker', 'rm', '-f', container_name],
check=True,
capture_output=True)
except subprocess.CalledProcessError:
print(f"Failed to remove existing container '{container_name}'")
return False

docker_cmd = [
'docker', 'run',
'--name', container_name,
'-e', f'ANTHROPIC_API_KEY={api_key}',
'-v', f'{os.path.expanduser("~")}/.anthropic:/home/computeruse/.anthropic',
'-p', '5900:5900',
'-p', '8501:8501',
'-p', '6080:6080',
'-p', '8080:8080',
'-d', # Run in detached mode
'ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest'
]

try:
print("Starting container...")
subprocess.run(docker_cmd, check=True, capture_output=True)

# Wait for container to be ready
if wait_for_service_ready(container_name):
print("\nContainer is ready! Access Claude at http://localhost:8080")
return True

# If we get here, service didn't come up in time
print("\nContainer started but service is not responding")
return False

except subprocess.CalledProcessError as e:
print(f"Failed to start container: {str(e)}")
return False
except Exception as e:
print(f"Unexpected error: {str(e)}")
return False

if __name__ == "__main__":
start_claude_computer_use()
6 changes: 6 additions & 0 deletions agentstack/tools/claude_computer_use.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "claude_computer_use",
"package": "",
"env": "CLAUDE_API_KEY=...",
"tools": ["start_claude_computer_use"]
}
4 changes: 4 additions & 0 deletions agentstack/tools/tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,9 @@
"web-retrieval": [{
"name": "exa",
"url": "https://exa.ai"
}],
"claude-computer-use": [{
"name": "claude_computer_use",
"url": "https://www.anthropic.com"
}]
}
6 changes: 6 additions & 0 deletions examples/claude_computer_user/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
AGENTOPS_API_KEY=...
OPENAI_API_KEY=...

# Tools

CLAUDE_API_KEY=...
164 changes: 164 additions & 0 deletions examples/claude_computer_user/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

.agentops/
10 changes: 10 additions & 0 deletions examples/claude_computer_user/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

MIT License

Copyright (c) 2024 Kish

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 changes: 38 additions & 0 deletions examples/claude_computer_user/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# claude_computer_user
An AI Agent that can control your OS

~~ Built with AgentStack ~~

## How to build your Crew
### With the CLI
Add an agent using AgentStack with the CLI:
`agentstack generate agent <agent_name>`
You can also shorten this to `agentstack g a <agent_name>`
For wizard support use `agentstack g a <agent_name> --wizard`
Finally for creation in the CLI alone, use `agentstack g a <agent_name> --role/-r <role> --goal/-g <goal> --backstory/-b <backstory> --model/-m <provider/model>`

This will automatically create a new agent in the `agents.yaml` config as well as in your code. Either placeholder strings will be used, or data included in the wizard.

Similarly, tasks can be created with `agentstack g t <tool_name>`

Add tools with `agentstack tools add <tool_name>` and view tools available with `agentstack tools list`

## How to use your Crew
In this directory, run `poetry install`

To run your project, use the following command:
`crewai run` or `python src/main.py`

This will initialize your crew of AI agents and begin task execution as defined in your configuration in the main.py file.

#### Replay Tasks from Latest Crew Kickoff:

CrewAI now includes a replay feature that allows you to list the tasks from the last run and replay from a specific one. To use this feature, run:
`crewai replay <task_id>`
Replace <task_id> with the ID of the task you want to replay.

#### Reset Crew Memory
If you need to reset the memory of your crew before running it again, you can do so by calling the reset memory feature:
`crewai reset-memory`
This will clear the crew's memory, allowing for a fresh start.

6 changes: 6 additions & 0 deletions examples/claude_computer_user/agentstack.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"framework": "crewai",
"tools": [
"claude_computer_use"
]
}
20 changes: 20 additions & 0 deletions examples/claude_computer_user/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[tool.poetry]
name = "claude_computer_user"
version = "0.1.0"
description = "An AI Agent that can control your OS"
authors = ["Kish"]
license = "MIT"

[tool.poetry.dependencies]
python = ">=3.10,<=3.13"
agentops = "^0.3.12"
crewai = "^0.63.6"
crewai-tools= "0.12.1"
python-dotenv="1.0.1"

[project.scripts]
claude_computer_user = "claude_computer_user.main:run"
run_crew = "claude_computer_user.main:run"
train = "claude_computer_user.main:train"
replay = "claude_computer_user.main:replay"
test = "claude_computer_user.main:test"
Empty file.
Loading
Loading