cheshire-cat-ai / core

Production ready AI agent framework
https://cheshirecat.ai
GNU General Public License v3.0
2.38k stars 327 forks source link

Forms model getter #970

Closed lucagobbi closed 1 week ago

lucagobbi commented 2 weeks ago

Description

I'll try this even if it had not that much success.

This PR to add the model_getter feature to the conversational forms. Basically, it is a straightforward method to allow developers define the extraction schema in a dynamic way. This opens the way for so many use cases: multi tenant app with schema based on the tenant, schemas dynamically load from an external source that might change frequently, schema that changes dynamically based on the information gathered in the previous round of the form (this one is pretty cool), etc.

Here's an example of that:


class PizzaOrder(BaseModel):
    pizza_type: str
    phone: int
    address: str

class PepperoniPizza(PizzaOrder):
    with_extra_cheese: bool

@form
class PizzaForm(CatForm):
    description = "Pizza Order"
    model_class = PizzaOrder
    start_examples = [
        "order a pizza!",
        "I want pizza"
    ]
    stop_examples = [
        "stop pizza order",
        "not hungry anymore",
    ]
    ask_confirm = True

    def model_getter(self):
        if "pizza_type" in self._model and self._model["pizza_type"] == "pepperoni":
            self.model_class = PepperoniPizza
        return self.model_class

    def submit(self, form_data):
        return {
            "output": f"Pizza order on its way: {form_data}"
        }

In action:

image

I needed to refactor the update and validate methods since they were a lil bit messy and were blocking the full potential of the model_getter on validation, which otherwise would have used the model_class from the previous form round.

Hope you like this!

Type of change

Checklist:

pieroit commented 1 week ago

Thanks @lucagobbi agree on self._model