From 6f40f65d7045b3c92b9a88a39d2f5edf3631a547 Mon Sep 17 00:00:00 2001 From: kish Date: Sun, 10 Nov 2024 04:38:14 -0800 Subject: [PATCH 1/5] update claude computer use --- .../crewai/tools/claude_computer_use_tool.py | 35 +++++++++++++++++++ .../tools/claude_computer_use_tool.json | 6 ++++ agentstack/tools/tools.json | 4 +++ 3 files changed, 45 insertions(+) create mode 100644 agentstack/templates/crewai/tools/claude_computer_use_tool.py create mode 100644 agentstack/tools/claude_computer_use_tool.json diff --git a/agentstack/templates/crewai/tools/claude_computer_use_tool.py b/agentstack/templates/crewai/tools/claude_computer_use_tool.py new file mode 100644 index 00000000..373b8f38 --- /dev/null +++ b/agentstack/templates/crewai/tools/claude_computer_use_tool.py @@ -0,0 +1,35 @@ +from crewai_tools import tool +from dotenv import load_dotenv +import os +import subprocess + +load_dotenv() + +api_key = os.getenv('CLAUDE_API_KEY') + +@tool("Start claude computer use") +def start_claude_computer_use(): + """ + Tool to run Claude computer use using Claude's docker image + """ + + # Docker command as a list of arguments + docker_cmd = [ + 'docker', 'run', + '-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', + '-it', 'ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest' + ] + + try: + # Run docker command + subprocess.run(docker_cmd, check=True) + print('Running docker') + except subprocess.CalledProcessError as e: + print(f'Error running docker: {e}') + except Exception as e: + print(f'Unexpected error: {e}') \ No newline at end of file diff --git a/agentstack/tools/claude_computer_use_tool.json b/agentstack/tools/claude_computer_use_tool.json new file mode 100644 index 00000000..c33a1dc9 --- /dev/null +++ b/agentstack/tools/claude_computer_use_tool.json @@ -0,0 +1,6 @@ +{ + "name": "claude_computer_use", + "package": "", + "env": "CLAUDE_API_KEY=...", + "tools": ["start_claude_computer_use"] + } \ No newline at end of file diff --git a/agentstack/tools/tools.json b/agentstack/tools/tools.json index 15e6bfbe..07f4bd28 100644 --- a/agentstack/tools/tools.json +++ b/agentstack/tools/tools.json @@ -42,5 +42,9 @@ "web-retrieval": [{ "name": "exa", "url": "https://exa.ai" + }], + "claude-computer-use": [{ + "name": "claude_computer_use", + "url": "https://www.anthropic.com" }] } From 65b5ee08eb85eeb940ab9677ab79085086f94022 Mon Sep 17 00:00:00 2001 From: kish Date: Sun, 10 Nov 2024 05:12:34 -0800 Subject: [PATCH 2/5] add claude computer user --- examples/claude_computer_user/.env.example | 6 + examples/claude_computer_user/.gitignore | 164 ++++++++++++++++++ examples/claude_computer_user/LICENSE.md | 10 ++ examples/claude_computer_user/README.md | 38 ++++ examples/claude_computer_user/agentstack.json | 6 + examples/claude_computer_user/pyproject.toml | 20 +++ examples/claude_computer_user/src/__init__.py | 0 .../src/config/agents.yaml | 7 + .../src/config/tasks.yaml | 8 + examples/claude_computer_user/src/crew.py | 36 ++++ examples/claude_computer_user/src/main.py | 65 +++++++ .../src/tools/__init__.py | 4 + .../src/tools/claude_computer_use_tool.py | 35 ++++ 13 files changed, 399 insertions(+) create mode 100644 examples/claude_computer_user/.env.example create mode 100644 examples/claude_computer_user/.gitignore create mode 100644 examples/claude_computer_user/LICENSE.md create mode 100644 examples/claude_computer_user/README.md create mode 100644 examples/claude_computer_user/agentstack.json create mode 100644 examples/claude_computer_user/pyproject.toml create mode 100644 examples/claude_computer_user/src/__init__.py create mode 100644 examples/claude_computer_user/src/config/agents.yaml create mode 100644 examples/claude_computer_user/src/config/tasks.yaml create mode 100644 examples/claude_computer_user/src/crew.py create mode 100644 examples/claude_computer_user/src/main.py create mode 100644 examples/claude_computer_user/src/tools/__init__.py create mode 100644 examples/claude_computer_user/src/tools/claude_computer_use_tool.py diff --git a/examples/claude_computer_user/.env.example b/examples/claude_computer_user/.env.example new file mode 100644 index 00000000..49c4a170 --- /dev/null +++ b/examples/claude_computer_user/.env.example @@ -0,0 +1,6 @@ +AGENTOPS_API_KEY=... +OPENAI_API_KEY=... + +# Tools + +CLAUDE_API_KEY=... diff --git a/examples/claude_computer_user/.gitignore b/examples/claude_computer_user/.gitignore new file mode 100644 index 00000000..8ce42678 --- /dev/null +++ b/examples/claude_computer_user/.gitignore @@ -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/ diff --git a/examples/claude_computer_user/LICENSE.md b/examples/claude_computer_user/LICENSE.md new file mode 100644 index 00000000..6489a38d --- /dev/null +++ b/examples/claude_computer_user/LICENSE.md @@ -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. \ No newline at end of file diff --git a/examples/claude_computer_user/README.md b/examples/claude_computer_user/README.md new file mode 100644 index 00000000..0ccecc7d --- /dev/null +++ b/examples/claude_computer_user/README.md @@ -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 ` +You can also shorten this to `agentstack g a ` +For wizard support use `agentstack g a --wizard` +Finally for creation in the CLI alone, use `agentstack g a --role/-r --goal/-g --backstory/-b --model/-m ` + +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 ` + +Add tools with `agentstack tools add ` 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 ` +Replace 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. + diff --git a/examples/claude_computer_user/agentstack.json b/examples/claude_computer_user/agentstack.json new file mode 100644 index 00000000..de6fc25a --- /dev/null +++ b/examples/claude_computer_user/agentstack.json @@ -0,0 +1,6 @@ +{ + "framework": "crewai", + "tools": [ + "claude_computer_use" + ] +} \ No newline at end of file diff --git a/examples/claude_computer_user/pyproject.toml b/examples/claude_computer_user/pyproject.toml new file mode 100644 index 00000000..5b53cc6e --- /dev/null +++ b/examples/claude_computer_user/pyproject.toml @@ -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" \ No newline at end of file diff --git a/examples/claude_computer_user/src/__init__.py b/examples/claude_computer_user/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/claude_computer_user/src/config/agents.yaml b/examples/claude_computer_user/src/config/agents.yaml new file mode 100644 index 00000000..5f803b2d --- /dev/null +++ b/examples/claude_computer_user/src/config/agents.yaml @@ -0,0 +1,7 @@ +claude_computer_agent: + role: >- + image retriever + goal: >- + to access a browser and do retrieve a picture of the golden gate bridge + backstory: >- + you are a computer user and need to retrieve a picture of the golden gate bridge \ No newline at end of file diff --git a/examples/claude_computer_user/src/config/tasks.yaml b/examples/claude_computer_user/src/config/tasks.yaml new file mode 100644 index 00000000..e2df722c --- /dev/null +++ b/examples/claude_computer_user/src/config/tasks.yaml @@ -0,0 +1,8 @@ +retrieve_image: + description: >- + retrieve image from google + expected_output: >- + expect output to be a picture of the golden gate bridge + agent: >- + claude_computer_agent + diff --git a/examples/claude_computer_user/src/crew.py b/examples/claude_computer_user/src/crew.py new file mode 100644 index 00000000..862ac0f9 --- /dev/null +++ b/examples/claude_computer_user/src/crew.py @@ -0,0 +1,36 @@ +from crewai import Agent, Crew, Process, Task +from crewai.project import CrewBase, agent, crew, task +import tools + +@CrewBase +class ClaudecomputeruserCrew(): + """claude_computer_user crew""" + + # Agent definitions + @agent + def claude_computer_agent(self) -> Agent: + return Agent( + config=self.agents_config['claude_computer_agent'], + tools=[tools.start_claude_computer_use, ], # add tools here or use `agentstack tools add + verbose=True + ) + + + # Task definitions + @task + def retrieve_image(self) -> Task: + return Task( + config=self.tasks_config['retrieve_image'], + ) + + + @crew + def crew(self) -> Crew: + """Creates the Test crew""" + return Crew( + agents=self.agents, # Automatically created by the @agent decorator + tasks=self.tasks, # Automatically created by the @task decorator + process=Process.sequential, + verbose=True, + # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/ + ) \ No newline at end of file diff --git a/examples/claude_computer_user/src/main.py b/examples/claude_computer_user/src/main.py new file mode 100644 index 00000000..8f287b8f --- /dev/null +++ b/examples/claude_computer_user/src/main.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +import sys +from crew import ClaudecomputeruserCrew +import agentops +from dotenv import load_dotenv +load_dotenv() + +agentops.init() + +# This main file is intended to be a way for your to run your +# crew locally, so refrain from adding necessary logic into this file. +# Replace with inputs you want to test with, it will automatically +# interpolate any tasks and agents information + +def run(): + """ + Run the crew. + """ + inputs = { + 'topic': 'AI LLMs' + } + ClaudecomputeruserCrew().crew().kickoff(inputs=inputs) + + +def train(): + """ + Train the crew for a given number of iterations. + """ + inputs = { + "topic": "AI LLMs" + } + try: + ClaudecomputeruserCrew().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs) + + except Exception as e: + raise Exception(f"An error occurred while training the crew: {e}") + + +def replay(): + """ + Replay the crew execution from a specific task. + """ + try: + ClaudecomputeruserCrew().crew().replay(task_id=sys.argv[1]) + + except Exception as e: + raise Exception(f"An error occurred while replaying the crew: {e}") + + +def test(): + """ + Test the crew execution and returns the results. + """ + inputs = { + "topic": "AI LLMs" + } + try: + ClaudecomputeruserCrew().crew().test(n_iterations=int(sys.argv[1]), openai_model_name=sys.argv[2], inputs=inputs) + + except Exception as e: + raise Exception(f"An error occurred while replaying the crew: {e}") + + +if __name__ == '__main__': + run() \ No newline at end of file diff --git a/examples/claude_computer_user/src/tools/__init__.py b/examples/claude_computer_user/src/tools/__init__.py new file mode 100644 index 00000000..ecba097a --- /dev/null +++ b/examples/claude_computer_user/src/tools/__init__.py @@ -0,0 +1,4 @@ + +# tool import + +from .claude_computer_use_tool import start_claude_computer_use diff --git a/examples/claude_computer_user/src/tools/claude_computer_use_tool.py b/examples/claude_computer_user/src/tools/claude_computer_use_tool.py new file mode 100644 index 00000000..373b8f38 --- /dev/null +++ b/examples/claude_computer_user/src/tools/claude_computer_use_tool.py @@ -0,0 +1,35 @@ +from crewai_tools import tool +from dotenv import load_dotenv +import os +import subprocess + +load_dotenv() + +api_key = os.getenv('CLAUDE_API_KEY') + +@tool("Start claude computer use") +def start_claude_computer_use(): + """ + Tool to run Claude computer use using Claude's docker image + """ + + # Docker command as a list of arguments + docker_cmd = [ + 'docker', 'run', + '-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', + '-it', 'ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest' + ] + + try: + # Run docker command + subprocess.run(docker_cmd, check=True) + print('Running docker') + except subprocess.CalledProcessError as e: + print(f'Error running docker: {e}') + except Exception as e: + print(f'Unexpected error: {e}') \ No newline at end of file From 99f0abf6229f91a445a86dcec134380ac6530f44 Mon Sep 17 00:00:00 2001 From: kish Date: Sun, 10 Nov 2024 05:13:00 -0800 Subject: [PATCH 3/5] add claude computer user --- .../{claude_computer_use_tool.json => claude_computer_use.json} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename agentstack/tools/{claude_computer_use_tool.json => claude_computer_use.json} (100%) diff --git a/agentstack/tools/claude_computer_use_tool.json b/agentstack/tools/claude_computer_use.json similarity index 100% rename from agentstack/tools/claude_computer_use_tool.json rename to agentstack/tools/claude_computer_use.json From 99d50d318a91db8bfb473e15128037c8f69f4205 Mon Sep 17 00:00:00 2001 From: kish Date: Sun, 10 Nov 2024 12:57:09 -0800 Subject: [PATCH 4/5] update agent and task to better reflect what the agent is doing --- .../src/config/agents.yaml | 6 +- .../src/config/tasks.yaml | 6 +- examples/claude_computer_user/src/crew.py | 8 +- .../src/tools/claude_computer_use_tool.py | 103 ++++++++++++++++-- 4 files changed, 106 insertions(+), 17 deletions(-) diff --git a/examples/claude_computer_user/src/config/agents.yaml b/examples/claude_computer_user/src/config/agents.yaml index 5f803b2d..28c46770 100644 --- a/examples/claude_computer_user/src/config/agents.yaml +++ b/examples/claude_computer_user/src/config/agents.yaml @@ -1,7 +1,7 @@ claude_computer_agent: role: >- - image retriever + docker instance starter goal: >- - to access a browser and do retrieve a picture of the golden gate bridge + to start a docker container backstory: >- - you are a computer user and need to retrieve a picture of the golden gate bridge \ No newline at end of file + you are a computer user and need to start a docker container \ No newline at end of file diff --git a/examples/claude_computer_user/src/config/tasks.yaml b/examples/claude_computer_user/src/config/tasks.yaml index e2df722c..8843337f 100644 --- a/examples/claude_computer_user/src/config/tasks.yaml +++ b/examples/claude_computer_user/src/config/tasks.yaml @@ -1,8 +1,8 @@ -retrieve_image: +start_docker_container: description: >- - retrieve image from google + Start a Docker container with Computer Use running expected_output: >- - expect output to be a picture of the golden gate bridge + expect output to be a docker container successfully running agent: >- claude_computer_agent diff --git a/examples/claude_computer_user/src/crew.py b/examples/claude_computer_user/src/crew.py index 862ac0f9..4138c96f 100644 --- a/examples/claude_computer_user/src/crew.py +++ b/examples/claude_computer_user/src/crew.py @@ -18,11 +18,11 @@ def claude_computer_agent(self) -> Agent: # Task definitions @task - def retrieve_image(self) -> Task: - return Task( - config=self.tasks_config['retrieve_image'], + def start_docker_container(self) -> Task: + return Task( + config=self.tasks_config['start_docker_container'], ) - + @crew def crew(self) -> Crew: diff --git a/examples/claude_computer_user/src/tools/claude_computer_use_tool.py b/examples/claude_computer_user/src/tools/claude_computer_use_tool.py index 373b8f38..0abd17d7 100644 --- a/examples/claude_computer_user/src/tools/claude_computer_use_tool.py +++ b/examples/claude_computer_user/src/tools/claude_computer_use_tool.py @@ -2,34 +2,123 @@ 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 command as a list of arguments 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', - '-it', 'ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest' + '-d', # Run in detached mode + 'ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest' ] try: - # Run docker command - subprocess.run(docker_cmd, check=True) - print('Running docker') + 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'Error running docker: {e}') + print(f"Failed to start container: {str(e)}") + return False except Exception as e: - print(f'Unexpected error: {e}') \ No newline at end of file + print(f"Unexpected error: {str(e)}") + return False + +if __name__ == "__main__": + start_claude_computer_use() \ No newline at end of file From 9139f34a331ee53baf009b38542b874ce72cf9ed Mon Sep 17 00:00:00 2001 From: kish Date: Sun, 10 Nov 2024 13:33:21 -0800 Subject: [PATCH 5/5] update claude computer use tool --- .../crewai/tools/claude_computer_use_tool.py | 103 ++++++++++++++++-- 1 file changed, 96 insertions(+), 7 deletions(-) diff --git a/agentstack/templates/crewai/tools/claude_computer_use_tool.py b/agentstack/templates/crewai/tools/claude_computer_use_tool.py index 373b8f38..0abd17d7 100644 --- a/agentstack/templates/crewai/tools/claude_computer_use_tool.py +++ b/agentstack/templates/crewai/tools/claude_computer_use_tool.py @@ -2,34 +2,123 @@ 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 command as a list of arguments 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', - '-it', 'ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest' + '-d', # Run in detached mode + 'ghcr.io/anthropics/anthropic-quickstarts:computer-use-demo-latest' ] try: - # Run docker command - subprocess.run(docker_cmd, check=True) - print('Running docker') + 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'Error running docker: {e}') + print(f"Failed to start container: {str(e)}") + return False except Exception as e: - print(f'Unexpected error: {e}') \ No newline at end of file + print(f"Unexpected error: {str(e)}") + return False + +if __name__ == "__main__": + start_claude_computer_use() \ No newline at end of file