GithubHelp home page GithubHelp logo

bharat123rox / agentai Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nirantk/agentai

0.0 0.0 0.0 569 KB

Python library which wraps OpenAI Functions and makes them easier to use

License: Apache License 2.0

Shell 0.22% Python 99.78%

agentai's Introduction

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

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:

pip install agentai

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

  1. Import required classes and functions
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()
  1. Define a function with @tool decorator
class TemperatureUnit(Enum):
    celsius = "celsius"
    fahrenheit = "fahrenheit"


@tool(registry=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.

  1. Create a Conversation object and add messages
conversation = Conversation()
conversation.add_message("user", "what is the weather like today?")
  1. Use the chat_complete function to get a response from the model
chat_response = chat_complete(conversation.conversation_history, function_registry=weather_registry, model=GPT_MODEL)

Output:

{'role': 'assistant',
'content': 'In which city would you like to know the current weather?'}
  1. Add user response to conversation and call chat_complete again

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

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:

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

Example: Doing a Database Query with Generated SQL

  1. Define a function with @tool decorator
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}")
  1. Registering the function and using it
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:

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 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 for more details.

Support

If you encounter any issues or require further assistance, please raise an issue on our GitHub repository.

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

agentai's People

Contributors

kshivendu avatar nirantk avatar rishabh-bhargava avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.