agentai


Nameagentai JSON
Version 0.0.4 PyPI version JSON
download
home_page
SummaryPython library which wraps OpenAI Functions and makes them easier to use
upload_time2023-06-19 04:26:00
maintainer
docs_urlNone
authorNirantK
requires_python>=3.8.16,<4.0
licenseApache
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # AgentAI: OpenAI Functions + Python Functions

It is designed to make it easy to use OpenAI models e.g. GPT3.5-Turbo and GPT4 with existing Python functions by adding a simple decorator.

AgentAI is a simple Python library with these ethos:

1. Let developers write code!
2. Do not invent a new syntax!
3. Make it easy to integrate with existing projects!
4. Make it easy to extend!
5. Have fun and use exclamations!

Unlike some libraries, AgentAI does NOT require you to learn a new syntax. No chains!

Instead, it empowers you to add OpenAI functions using Python decorators and then call them directly from your code.
This makes it easy to integrate AgentAI with your existing projects.

## Colab Notebooks

1. Extract detailed entities using Pydantic: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://githubtocolab.com/NirantK/agentai/blob/main/docs/03_Pydantic.ipynb)

## Features

- **API Calls**: Use AgentAI to decorate your Python functions and make them magical!
- **Nested Pydantic Objects for Extraction**: Use nested Pydantic objects to extract information from the user.
- **SQL Database Interaction**: Seamlessly extract and utilize data from SQL databases.
- **Function Execution**: Generate and execute function calls based on conversation context.
- **Conversation Management**: Effectively manage and track the state of conversations. Easily define your own functions which can use messages, functions, and conversation history.

### Next Week

- _Multiple Functions_: Call multiple functions in a single conversation with a DSL/DAG.
- _Retrieval_: Use AgentAI to retrieve information from a vector Database -- but only when needed!
- _Rich Media_: Support for rich media types e.g. images, audio
- _Function Generation_: Generate Python functions based on conversation context

## Installation

Install AgentAI using pip:

```bash
pip install agentai
```

## Getting Started: Asking User for Missing Inputs till all inputs are available

1. **Import required classes and functions**

```python
from agentai.api import chat_complete, chat_complete_execute_fn
from agentai.openai_function import tool, ToolRegistry
from agentai.conversation import Conversation
from enum import Enum
weather_registry = ToolRegistry()
```

2. **Define a function with `@tool` decorator**

```python
class TemperatureUnit(Enum):
    celsius = "celsius"
    fahrenheit = "fahrenheit"


@tool(regsitry=weather_registry)
def get_current_weather(location: str, format: TemperatureUnit) -> str:
    """
    Get the current weather

    Args:
        location (str): The city and state, e.g. San Francisco, CA
        format (str): The temperature unit to use. Infer this from the users location.

    Returns:
        str: The current weather
    """
    # Your function implementation goes here.
    return ""
```

Note that `agentai` automatically parses the Python Enum type (TemperatureUnit) and passes it to the model as a JSONSchema Enum. This saves you time in writing boilerplate JSONSchema which is required by OpenAI API.

3. **Create a Conversation object and add messages**

```python
conversation = Conversation()
conversation.add_message("user", "what is the weather like today?")
```

4. **Use the `chat_complete` function to get a response from the model**

```python
chat_response = chat_complete(conversation.conversation_history, function_registry=weather_registry, model=GPT_MODEL)
```

Output:

```javascript
{'role': 'assistant',
'content': 'In which city would you like to know the current weather?'}
```

5. **Add user response to conversation and call `chat_complete` again**

Once the user provides the required information, the model can generate the function arguments:

```python
conversation.add_message("user", "I'm in Bengaluru, India")
chat_response = chat_complete(conversation.conversation_history, function_registry=weather_registry, model=GPT_MODEL)

eval(chat_response.json()["choices"][0]["message"]["function_call"]["arguments"])
```

Output:

```python
{'location': 'Bengaluru, India', 'format': 'celsius'}
```

## Example: Doing a Database Query with Generated SQL

1. **Define a function with `@tool` decorator**

```python
db_registry = ToolRegistry()

@tool(registry=db_registry)
def ask_database(query: str) -> List[Tuple[str, str]]:
    """
    Use this function to answer user questions about music. Input should be a fully formed SQL query.

    Args:
        query (str): SQL query extracting info to answer the user's question.
                    SQL should be written using this database schema: <database_schema_string>
                    IMPORTANT: Please return a fixed SQL in PLAIN TEXT.
                    Your response should consist of ONLY the SQL query.
    """
    try:
        results = conn.execute(query).fetchall()
        return results
    except Exception as e:
        raise Exception(f"SQL error: {e}")
```

2. **Registering the function and using it**

```python
agentai_functions = [json.loads(func.json_info) for func in [ask_database]]

from agentai.api import chat_complete_execute_fn
agent_system_message = """You are ChinookGPT, a helpful assistant who gets answers to user questions from the Chinook Music Database.
Provide as many details as possible to your users
Begin!"""

sql_conversation = Conversation()
sql_conversation.add_message(role="system", content=agent_system_message)
sql_conversation.add_message("user", "Hi, who are the top 5 artists by number of tracks")
assistant_message = chat_complete_execute_fn(
    conversation=sql_conversation, functions=agentai_functions, model=GPT_MODEL, callable_function=ask_database
)

sql_conversation.display_conversation(detailed=True)
```

Output:

```traceback
system: You are ChinookGPT, a helpful assistant who gets answers to user questions from the Chinook Music Database.
Provide as many details as possible to your users
Begin!


user: Hi, who are the top 5 artists by number of tracks


function: [('Iron Maiden', 213), ('U2', 135), ('Led Zeppelin', 114), ('Metallica', 112), ('Lost', 92)]


assistant: The top 5 artists by number of tracks are:

1. Iron Maiden - 213 tracks
2. U2 - 135 tracks
3. Led Zeppelin - 114 tracks
4. Metallica - 112 tracks
5. Lost - 92 tracks
```

## Detailed Examples

Check out our detailed [notebooks with examples](./docs/) where we demonstrate how to integrate AgentAI with a chatbot to create a powerful conversational assistant that can answer questions using a SQLite database.

## Contributing

We welcome contributions! Please see our [contributing guidelines](./.github/CONTRIBUTING.md) for more details.

## Support

If you encounter any issues or require further assistance, please raise an issue on our [GitHub repository](https://github.com/NirantK/agentai/issues).

We hope you enjoy using AgentAI and find it helpful in powering up your AI models. Happy coding!

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "agentai",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8.16,<4.0",
    "maintainer_email": "",
    "keywords": "",
    "author": "NirantK",
    "author_email": "nirant.bits@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/45/76/aa546c7572500c435270651888b241bfa13d7365f83f6acd398e84a9fcd9/agentai-0.0.4.tar.gz",
    "platform": null,
    "description": "# AgentAI: OpenAI Functions + Python Functions\n\nIt is designed to make it easy to use OpenAI models e.g. GPT3.5-Turbo and GPT4 with existing Python functions by adding a simple decorator.\n\nAgentAI is a simple Python library with these ethos:\n\n1. Let developers write code!\n2. Do not invent a new syntax!\n3. Make it easy to integrate with existing projects!\n4. Make it easy to extend!\n5. Have fun and use exclamations!\n\nUnlike some libraries, AgentAI does NOT require you to learn a new syntax. No chains!\n\nInstead, it empowers you to add OpenAI functions using Python decorators and then call them directly from your code.\nThis makes it easy to integrate AgentAI with your existing projects.\n\n## Colab Notebooks\n\n1. Extract detailed entities using Pydantic: [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://githubtocolab.com/NirantK/agentai/blob/main/docs/03_Pydantic.ipynb)\n\n## Features\n\n- **API Calls**: Use AgentAI to decorate your Python functions and make them magical!\n- **Nested Pydantic Objects for Extraction**: Use nested Pydantic objects to extract information from the user.\n- **SQL Database Interaction**: Seamlessly extract and utilize data from SQL databases.\n- **Function Execution**: Generate and execute function calls based on conversation context.\n- **Conversation Management**: Effectively manage and track the state of conversations. Easily define your own functions which can use messages, functions, and conversation history.\n\n### Next Week\n\n- _Multiple Functions_: Call multiple functions in a single conversation with a DSL/DAG.\n- _Retrieval_: Use AgentAI to retrieve information from a vector Database -- but only when needed!\n- _Rich Media_: Support for rich media types e.g. images, audio\n- _Function Generation_: Generate Python functions based on conversation context\n\n## Installation\n\nInstall AgentAI using pip:\n\n```bash\npip install agentai\n```\n\n## Getting Started: Asking User for Missing Inputs till all inputs are available\n\n1. **Import required classes and functions**\n\n```python\nfrom agentai.api import chat_complete, chat_complete_execute_fn\nfrom agentai.openai_function import tool, ToolRegistry\nfrom agentai.conversation import Conversation\nfrom enum import Enum\nweather_registry = ToolRegistry()\n```\n\n2. **Define a function with `@tool` decorator**\n\n```python\nclass TemperatureUnit(Enum):\n    celsius = \"celsius\"\n    fahrenheit = \"fahrenheit\"\n\n\n@tool(regsitry=weather_registry)\ndef get_current_weather(location: str, format: TemperatureUnit) -> str:\n    \"\"\"\n    Get the current weather\n\n    Args:\n        location (str): The city and state, e.g. San Francisco, CA\n        format (str): The temperature unit to use. Infer this from the users location.\n\n    Returns:\n        str: The current weather\n    \"\"\"\n    # Your function implementation goes here.\n    return \"\"\n```\n\nNote that `agentai` automatically parses the Python Enum type (TemperatureUnit) and passes it to the model as a JSONSchema Enum. This saves you time in writing boilerplate JSONSchema which is required by OpenAI API.\n\n3. **Create a Conversation object and add messages**\n\n```python\nconversation = Conversation()\nconversation.add_message(\"user\", \"what is the weather like today?\")\n```\n\n4. **Use the `chat_complete` function to get a response from the model**\n\n```python\nchat_response = chat_complete(conversation.conversation_history, function_registry=weather_registry, model=GPT_MODEL)\n```\n\nOutput:\n\n```javascript\n{'role': 'assistant',\n'content': 'In which city would you like to know the current weather?'}\n```\n\n5. **Add user response to conversation and call `chat_complete` again**\n\nOnce the user provides the required information, the model can generate the function arguments:\n\n```python\nconversation.add_message(\"user\", \"I'm in Bengaluru, India\")\nchat_response = chat_complete(conversation.conversation_history, function_registry=weather_registry, model=GPT_MODEL)\n\neval(chat_response.json()[\"choices\"][0][\"message\"][\"function_call\"][\"arguments\"])\n```\n\nOutput:\n\n```python\n{'location': 'Bengaluru, India', 'format': 'celsius'}\n```\n\n## Example: Doing a Database Query with Generated SQL\n\n1. **Define a function with `@tool` decorator**\n\n```python\ndb_registry = ToolRegistry()\n\n@tool(registry=db_registry)\ndef ask_database(query: str) -> List[Tuple[str, str]]:\n    \"\"\"\n    Use this function to answer user questions about music. Input should be a fully formed SQL query.\n\n    Args:\n        query (str): SQL query extracting info to answer the user's question.\n                    SQL should be written using this database schema: <database_schema_string>\n                    IMPORTANT: Please return a fixed SQL in PLAIN TEXT.\n                    Your response should consist of ONLY the SQL query.\n    \"\"\"\n    try:\n        results = conn.execute(query).fetchall()\n        return results\n    except Exception as e:\n        raise Exception(f\"SQL error: {e}\")\n```\n\n2. **Registering the function and using it**\n\n```python\nagentai_functions = [json.loads(func.json_info) for func in [ask_database]]\n\nfrom agentai.api import chat_complete_execute_fn\nagent_system_message = \"\"\"You are ChinookGPT, a helpful assistant who gets answers to user questions from the Chinook Music Database.\nProvide as many details as possible to your users\nBegin!\"\"\"\n\nsql_conversation = Conversation()\nsql_conversation.add_message(role=\"system\", content=agent_system_message)\nsql_conversation.add_message(\"user\", \"Hi, who are the top 5 artists by number of tracks\")\nassistant_message = chat_complete_execute_fn(\n    conversation=sql_conversation, functions=agentai_functions, model=GPT_MODEL, callable_function=ask_database\n)\n\nsql_conversation.display_conversation(detailed=True)\n```\n\nOutput:\n\n```traceback\nsystem: You are ChinookGPT, a helpful assistant who gets answers to user questions from the Chinook Music Database.\nProvide as many details as possible to your users\nBegin!\n\n\nuser: Hi, who are the top 5 artists by number of tracks\n\n\nfunction: [('Iron Maiden', 213), ('U2', 135), ('Led Zeppelin', 114), ('Metallica', 112), ('Lost', 92)]\n\n\nassistant: The top 5 artists by number of tracks are:\n\n1. Iron Maiden - 213 tracks\n2. U2 - 135 tracks\n3. Led Zeppelin - 114 tracks\n4. Metallica - 112 tracks\n5. Lost - 92 tracks\n```\n\n## Detailed Examples\n\nCheck out our detailed [notebooks with examples](./docs/) where we demonstrate how to integrate AgentAI with a chatbot to create a powerful conversational assistant that can answer questions using a SQLite database.\n\n## Contributing\n\nWe welcome contributions! Please see our [contributing guidelines](./.github/CONTRIBUTING.md) for more details.\n\n## Support\n\nIf you encounter any issues or require further assistance, please raise an issue on our [GitHub repository](https://github.com/NirantK/agentai/issues).\n\nWe hope you enjoy using AgentAI and find it helpful in powering up your AI models. Happy coding!\n",
    "bugtrack_url": null,
    "license": "Apache",
    "summary": "Python library which wraps OpenAI Functions and makes them easier to use",
    "version": "0.0.4",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0438dcb9756a4ce66f07a97e4d378b39f3477150992834d9688443e9b6c6836c",
                "md5": "94e36f117bf61479f3a31da9ed4c35ae",
                "sha256": "c64fb8abd040a44408a847c9156212906ef6e13ad4ea4edf4272e143009cbeb4"
            },
            "downloads": -1,
            "filename": "agentai-0.0.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "94e36f117bf61479f3a31da9ed4c35ae",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8.16,<4.0",
            "size": 13618,
            "upload_time": "2023-06-19T04:25:59",
            "upload_time_iso_8601": "2023-06-19T04:25:59.260816Z",
            "url": "https://files.pythonhosted.org/packages/04/38/dcb9756a4ce66f07a97e4d378b39f3477150992834d9688443e9b6c6836c/agentai-0.0.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4576aa546c7572500c435270651888b241bfa13d7365f83f6acd398e84a9fcd9",
                "md5": "0d8b09c8dbaf71fb2f997f2b488b0880",
                "sha256": "ae8de288400c0fc9e0f3c53760674ecec2d4d048f0a1d1d898ace2eaecdbf2a4"
            },
            "downloads": -1,
            "filename": "agentai-0.0.4.tar.gz",
            "has_sig": false,
            "md5_digest": "0d8b09c8dbaf71fb2f997f2b488b0880",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8.16,<4.0",
            "size": 14254,
            "upload_time": "2023-06-19T04:26:00",
            "upload_time_iso_8601": "2023-06-19T04:26:00.688582Z",
            "url": "https://files.pythonhosted.org/packages/45/76/aa546c7572500c435270651888b241bfa13d7365f83f6acd398e84a9fcd9/agentai-0.0.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-19 04:26:00",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "agentai"
}
        
Elapsed time: 0.07754s