agent-tool


Nameagent-tool JSON
Version 0.1.6 PyPI version JSON
download
home_page
SummaryA protocol for AI agent tools
upload_time2024-02-15 00:01:46
maintainer
docs_urlNone
authorPatrick Barker
requires_python>=3.10,<4.0
licenseApache 2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Agent Tools

A common protocol for AI agent tools

## Installation

```
pip install agent-tool
```

## Usage

Let's define a simplified Selenium web browser tool

```python
from agent_tools import Tool, action, observation
from selenium import webdriver


class SeleniumBrowser(Tool):
    """Selenium browser as a tool"""

    def __init__(self, headless: bool = True) -> None:
        super().__init__()
        options = webdriver.ChromeOptions()
        if headless:
            options.add_argument("--headless")
        self.driver = webdriver.Chrome(options=options)

    @action
    def open_url(self, url: str) -> None:
        """Open a URL in the browser

        Args:
            url (str): URL to open
        """
        self.driver.get(url)

    @action
    def click_element(self, selector: str, selector_type: str = "css_selector") -> None:
        """Click an element identified by a CSS selector

        Args:
            selector (str): CSS selector
            selector_type (str, optional): Selector type. Defaults to "css_selector".
        """
        element = self.driver.find_element(selector_type, selector)
        element.click()

    @observation
    def get_html(self) -> str:
        """Get the entire HTML of the current page.

        Returns:
            str: Page HTML
        """
        return self.driver.page_source

    def close(self) -> None:
        """Close the tool"""
        self.driver.quit()

```

We mark the functions to be made available to the agent as `@action` if they mutate the environment, and `@observation` if they are read only.

Now we can use this tool with an agent such as openai function calling

```python
from openai import OpenAI

client = OpenAI()

browser = SeleniumBrowser()
schemas = browser.json_schema()

messages = []
messages.append({"role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous."})
messages.append({"role": "user", "content": "Get the HTML for the front page of wikipedia"})

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + openai.api_key,
}
json_data = {"model": model, "messages": messages, "tools": schemas}
response = requests.post(
    "https://api.openai.com/v1/chat/completions",
    headers=headers,
    json=json_data,
)

assistant_message = response.json()["choices"][0]["message"]
messages.append(assistant_message)
assistant_message
```

```json
{
  "role": "assistant",
  "tool_calls": [
    {
      "id": "call_RYXaDjxpUCfWmpXU7BZEYVqS",
      "type": "function",
      "function": {
        "name": "open_url",
        "arguments": "{\n  \"url\": \"https://wikipedia.org\"}"
      }
    },
    {
      "id": "call_TJIWlknwdoinfWEMFNss",
      "type": "function",
      "function": {
        "name": "get_html",
        "arguments": ""
      }
    }
  ]
}
```

Then to use this action

```python
for tool in assistant_message["tool_calls"]:
    action = browser.find_action(tool["function"]["name"])
    args = json.loads(tool["function"]["arguments"])
    resp = browser.use(action, **args)
```

Tools can be used locally or spun up on a server and used remotely (In progress)

## Share (In progress)

Register a tool with the AgentSea hub so others can find and use it.

```python
pip install agentsea
```

Create a repo to publish

```
agentsea create tool
```

Add your tool to the `tool.py` in the repo, fill in the `README.md` and add your dependencies using Poetry

Publish to the hub

```
agentsea publish .
```

## Roadmap

- Integrate with langchain, babyagi, autogpt, etc

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "agent-tool",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10,<4.0",
    "maintainer_email": "",
    "keywords": "",
    "author": "Patrick Barker",
    "author_email": "patrickbarkerco@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/be/0d/3d7bca58ae5c8b54462afcb74ff984bf5710785ad7d01fda275c413db7ed/agent_tool-0.1.6.tar.gz",
    "platform": null,
    "description": "# Agent Tools\n\nA common protocol for AI agent tools\n\n## Installation\n\n```\npip install agent-tool\n```\n\n## Usage\n\nLet's define a simplified Selenium web browser tool\n\n```python\nfrom agent_tools import Tool, action, observation\nfrom selenium import webdriver\n\n\nclass SeleniumBrowser(Tool):\n    \"\"\"Selenium browser as a tool\"\"\"\n\n    def __init__(self, headless: bool = True) -> None:\n        super().__init__()\n        options = webdriver.ChromeOptions()\n        if headless:\n            options.add_argument(\"--headless\")\n        self.driver = webdriver.Chrome(options=options)\n\n    @action\n    def open_url(self, url: str) -> None:\n        \"\"\"Open a URL in the browser\n\n        Args:\n            url (str): URL to open\n        \"\"\"\n        self.driver.get(url)\n\n    @action\n    def click_element(self, selector: str, selector_type: str = \"css_selector\") -> None:\n        \"\"\"Click an element identified by a CSS selector\n\n        Args:\n            selector (str): CSS selector\n            selector_type (str, optional): Selector type. Defaults to \"css_selector\".\n        \"\"\"\n        element = self.driver.find_element(selector_type, selector)\n        element.click()\n\n    @observation\n    def get_html(self) -> str:\n        \"\"\"Get the entire HTML of the current page.\n\n        Returns:\n            str: Page HTML\n        \"\"\"\n        return self.driver.page_source\n\n    def close(self) -> None:\n        \"\"\"Close the tool\"\"\"\n        self.driver.quit()\n\n```\n\nWe mark the functions to be made available to the agent as `@action` if they mutate the environment, and `@observation` if they are read only.\n\nNow we can use this tool with an agent such as openai function calling\n\n```python\nfrom openai import OpenAI\n\nclient = OpenAI()\n\nbrowser = SeleniumBrowser()\nschemas = browser.json_schema()\n\nmessages = []\nmessages.append({\"role\": \"system\", \"content\": \"Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.\"})\nmessages.append({\"role\": \"user\", \"content\": \"Get the HTML for the front page of wikipedia\"})\n\nheaders = {\n    \"Content-Type\": \"application/json\",\n    \"Authorization\": \"Bearer \" + openai.api_key,\n}\njson_data = {\"model\": model, \"messages\": messages, \"tools\": schemas}\nresponse = requests.post(\n    \"https://api.openai.com/v1/chat/completions\",\n    headers=headers,\n    json=json_data,\n)\n\nassistant_message = response.json()[\"choices\"][0][\"message\"]\nmessages.append(assistant_message)\nassistant_message\n```\n\n```json\n{\n  \"role\": \"assistant\",\n  \"tool_calls\": [\n    {\n      \"id\": \"call_RYXaDjxpUCfWmpXU7BZEYVqS\",\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"open_url\",\n        \"arguments\": \"{\\n  \\\"url\\\": \\\"https://wikipedia.org\\\"}\"\n      }\n    },\n    {\n      \"id\": \"call_TJIWlknwdoinfWEMFNss\",\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"get_html\",\n        \"arguments\": \"\"\n      }\n    }\n  ]\n}\n```\n\nThen to use this action\n\n```python\nfor tool in assistant_message[\"tool_calls\"]:\n    action = browser.find_action(tool[\"function\"][\"name\"])\n    args = json.loads(tool[\"function\"][\"arguments\"])\n    resp = browser.use(action, **args)\n```\n\nTools can be used locally or spun up on a server and used remotely (In progress)\n\n## Share (In progress)\n\nRegister a tool with the AgentSea hub so others can find and use it.\n\n```python\npip install agentsea\n```\n\nCreate a repo to publish\n\n```\nagentsea create tool\n```\n\nAdd your tool to the `tool.py` in the repo, fill in the `README.md` and add your dependencies using Poetry\n\nPublish to the hub\n\n```\nagentsea publish .\n```\n\n## Roadmap\n\n- Integrate with langchain, babyagi, autogpt, etc\n",
    "bugtrack_url": null,
    "license": "Apache 2.0",
    "summary": "A protocol for AI agent tools",
    "version": "0.1.6",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "499d6039b3c0d2abf9316c4f52d6b261ef1b89f6227755dcbbc1077af7831768",
                "md5": "ca15850b3278eda0ad66006ad3b437b6",
                "sha256": "b0e3dedde2c4ddaa2a114b067315e24ea50a66c5f18123e96ffbac75e5128d26"
            },
            "downloads": -1,
            "filename": "agent_tool-0.1.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ca15850b3278eda0ad66006ad3b437b6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10,<4.0",
            "size": 16914,
            "upload_time": "2024-02-15T00:01:45",
            "upload_time_iso_8601": "2024-02-15T00:01:45.533252Z",
            "url": "https://files.pythonhosted.org/packages/49/9d/6039b3c0d2abf9316c4f52d6b261ef1b89f6227755dcbbc1077af7831768/agent_tool-0.1.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "be0d3d7bca58ae5c8b54462afcb74ff984bf5710785ad7d01fda275c413db7ed",
                "md5": "b687be5c8c545748205d043c69000ed2",
                "sha256": "4449d11a6a53462bc05848878b547f46f4d991c045e599211d7d7effb64c9f6b"
            },
            "downloads": -1,
            "filename": "agent_tool-0.1.6.tar.gz",
            "has_sig": false,
            "md5_digest": "b687be5c8c545748205d043c69000ed2",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10,<4.0",
            "size": 11046,
            "upload_time": "2024-02-15T00:01:46",
            "upload_time_iso_8601": "2024-02-15T00:01:46.866731Z",
            "url": "https://files.pythonhosted.org/packages/be/0d/3d7bca58ae5c8b54462afcb74ff984bf5710785ad7d01fda275c413db7ed/agent_tool-0.1.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-15 00:01:46",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "agent-tool"
}
        
Elapsed time: 0.21950s