Skip to main content

Live components for your LLM

Project description

aiide

aiide facilitates the creation of reinforcement learning (RL)-type environments for large language models (LLMs). It allows you to define and manage live data structures (components) that collectively form the environment (ENV). The LLM can interact with and modify these components by using user provided tools. After each action, along with the tool response, aiide adds the latest snapshot/state of all ENV components and removes all older ENV snapshots from the LLM's memory.

AIIDE Overview

ENV states are made available to the LLM in the following way:
AIIDE Memory updates

Tutorial

Let's build a simple form filling agent. We have a pandas dataframe with field names and we want the LLM to ask the user for answers to a couple of questions at a time and populate the said dataframe.

Here

  • The environment is the dataframe
  • We need a single tool that enables the LLM to add or edit values for any of the fields
  • The library will automatically provide the latest snapshot of the dataframe to the LLM.(aiide will automatically remove older snapshots of the dataframe from the LLM memory to avoid confusing it and saving tokens)
  1. Install the package
pip install aiide
  1. Let's start with defining a simple chat agent
# Import the AIIDE class
from aiide import AIIDE
# Import helper classes for defining functions for the LLM
from aiide.tools import TOOL_DEF, INT, FLOAT, STR, BOOL, LIST, DICT

import pandas as pd
# Define a class and inherit the AIIDE class
class FormFillingAgent(AIIDE):
    def __init__(self):
        # Let's define a dummy dataframe with fields and value as the columns
        self.df = pd.DataFrame({
            "Field":["name","age","gender","email","city","job","married"],
            "Value":["Not yet assigned" for i in range(7)]
        })

        # Here we only have one component and providing it as the element for the reserved ENV array
        self.ENV =[self.df.to_markdown(index=False)]

        # use setup to define the system message, type of model, temperature etc
        self.setup(messages=[{"role":"system","content":"You are a helpful assistant. Fill the form table attached by asking the user to answer a couple of fields from the table at a time."}],model="gpt-3.5-turbo",temperature=0.2)

Set your openai key as OPENAI_API_KEY enviroment variable or pass it in setup as api_key

  1. Let's define the tool. We have to define the tool as a class inside our FormFillingAgent class
class FormFillingAgent(AIIDE):
    def __init__(self):
        ...
    class Tool:
        def __init__(self):
            # we can access the FormFillingAgent instance through .parent
            self.parent.df

            # We now have to define the function definition and assign it to the reserved self.tool_def variable
            self.tool_def = TOOL_DEF(
                name = "add_or_modify_form_values",
                description = "tool to add or modify field values",
                properties = [
                    STR(
                        name = "field_name",
                        enums=self.parent.df["Field"].values.tolist()
                        ),
                    STR(
                        name = "value"
                    )
                ]
            )
        
        # Main function of the tool is called when the tool is invoked by the agent
        def main(self, field_name,value):
            # let's set the value in the master dataframe
            self.parent.df.loc[self.parent.df['Field'] == field_name, 'Value'] = value
            # Update the ENV
            self.parent.ENV[0] = self.parent.df.to_markdown(index=False)
            # response to the agent
            return "Added value '"+str(value) + " to Field '"+field_name+"'"

TOOL_DEF is a helper proxy for the JSON-SCHEMA of OpenAI function calling. You can directly add the json or even use your own pydantic model's model_json(). TOOL_DEF and associated tools.* would make the code less verbose and have the advantage of intellisense.

Checkout
aiide's tool use tutorial

  1. That's it. We can now start using the agent

chat is the function you invoke to start streaming agent response

# create the agent instance
agent = FormFillingAgent()
while True:
    # get the user message
    user_query = input("User: ")
    # you can enable and disable tools as you wish with the tools array
    for each in agent.chat(user_query, tools=["add_or_modify_form_values"]):
        # if the agent is reponding in text
        if each["type"] == "text":
            print(each["delta"],end="")
        # is the agent is calling a tool
        if each["type"] == "tool":
            print("TOOL CALL:",each["tool_name"],each["tool_arguments"])
        # the tool's response to the agent
        if each["type"] == "tool_response":
            print("TOOL RESPONSE",each["tool_response"])
    # for debugging, let's print the table after every turn
    print(agent.df)
  1. What if you want to take user's consent everytime before filling the table? it's incredibly simple!

You simply add a consent bool variable in the Tool class and update it in the chat loop as needed.

Here is the updated code:

# edit the tool to reject is the user rejects
class FormFillingAgent(AIIDE):
    def __init__(self):
        ... previous code
    class Tool:
        def __init__(self):
            # User consent bool 
            self.user_consent = False

            ... previous code

        def main(self, field_name,value):
            if self.user_consent == False:
                return "User has rejected the insert, please try again"

            # let's set the value in the master dataframe
            self.parent.df.loc[self.parent.df['Field'] == field_name, 'Value'] = value
            # Update the ENV
            self.parent.ENV[0] = self.parent.df.to_markdown(index=False)
            # response to the agent
            return "Added value '"+str(value) + " to Field '"+field_name+"'"

agent = FormFillingAgent()
while True:
    user_query = input("User: ")
    for each in agent.chat(user_query, tools=["add_or_modify_form_values"]):
        if each["type"] == "text":
            print(each["delta"],end="")
        if each["type"] == "tool":
            print("TOOL CALL:",each["tool_name"],each["tool_arguments"])
            # ask for user consent
            user_consent = input("do you approve the above tool call?(y/n)")
            if user_consent == 'y:
                # you can access the tool instance like so
                agent.Tool.user_consent = True
            else:
                agent.Tool.user_consent = False
        if each["type"] == "tool_response":
            print("TOOL RESPONSE",each["tool_response"])
  1. Bonus! You can use completions and stop sequences in the chat function's arguments to implement prompting techniques such as ReAct, CoT etc!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aiide-0.0.4.tar.gz (12.7 kB view details)

Uploaded Source

Built Distribution

aiide-0.0.4-py3-none-any.whl (11.8 kB view details)

Uploaded Python 3

File details

Details for the file aiide-0.0.4.tar.gz.

File metadata

  • Download URL: aiide-0.0.4.tar.gz
  • Upload date:
  • Size: 12.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.10.14 Linux/6.5.0-1018-azure

File hashes

Hashes for aiide-0.0.4.tar.gz
Algorithm Hash digest
SHA256 219051e341bae7d7c0aa09380b576528dc6430cb5a6290e49c98a2c50330b40c
MD5 8ccc0f711132dc8a82c93cbe1011560f
BLAKE2b-256 3fd1b84ef655f7f6585ccb277bde1eb117cae00839a491c86c1c2b30dec97640

See more details on using hashes here.

File details

Details for the file aiide-0.0.4-py3-none-any.whl.

File metadata

  • Download URL: aiide-0.0.4-py3-none-any.whl
  • Upload date:
  • Size: 11.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.2 CPython/3.10.14 Linux/6.5.0-1018-azure

File hashes

Hashes for aiide-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 157cf43648e7d6d3cf82069e5163085a2fe63770720d7297a2d0ca81f8300c24
MD5 9b629080400a6e2688f8599ec7ac37e2
BLAKE2b-256 3644973bf6bc85c0e6900b1c5e427955d2db2b059f205fbb2851e8206cf06da8

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page