Skip to main content

Support for Unity Catalog functions as CrewAI tools

Project description

Using Unity Catalog AI with CrewAI

You can use functions defined within Unity Catalog (UC) directly as tools within CrewAI with this package.

Installation

Client Library

To use this package with Open Source Unity Catalog, you will need to install:

pip install unitycatalog-ai[oss]

To use this package with Databricks Unity Catalog, you will need to install:

pip install unitycatalog-ai[databricks]

Integration Library

With the appropriate client installed for the AI functionality for Unity Catalog, you can then install the CrewAI integration library:

pip install unitycatalog-crewai

Getting started

Open Source Unity Catalog

Creating a Client

To interact with OSS UC, initialize the UnitycatalogFunctionClient as shown below:

import asyncio
from unitycatalog.ai.core.oss import UnitycatalogFunctionClient
from unitycatalog.client import ApiClient, Configuration

# Configure the Unity Catalog API client
config = Configuration(
    host="http://localhost:8080/api/2.1/unity-catalog"  # Replace with your UC server URL
)

# Initialize the asynchronous ApiClient
api_client = ApiClient(configuration=config)

# Instantiate the UnitycatalogFunctionClient
uc_client = UnitycatalogFunctionClient(api_client=api_client)

# Example catalog and schema names
CATALOG = "my_catalog"
SCHEMA = "my_schema"

Creating a Function in UC OSS

You can create a UC function either by providing a Python callable or by submitting a FunctionInfo object. Below is an example (recommended) of using the create_python_function API that accepts a Python callable (function) as input.

To create a UC function from a Python function, define your function with appropriate type hints and a Google-style docstring:

def add_numbers(a: float, b: float) -> float:
    """
    Adds two numbers and returns the result.

    Args:
        a (float): First number.
        b (float): Second number.

    Returns:
        float: The sum of the two numbers.
    """
    return a + b

# Create the function within the Unity Catalog catalog and schema specified
function_info = uc_client.create_python_function(
    func=add_numbers,
    catalog=CATALOG,
    schema=SCHEMA,
    replace=False,  # Set to True to overwrite if the function already exists
)

print(function_info)

Databricks-managed Unity Catalog

To use Databricks-managed UC with this package, follow the instructions here to authenticate to your workspace and ensure that your access token has workspace-level privilege for managing UC functions.

Client setup

Initialize a client for managing UC functions in a Databricks workspace, and set it as the global client.

from unitycatalog.ai.core.client import set_uc_function_client
from unitycatalog.ai.core.databricks import DatabricksFunctionClient

client = DatabricksFunctionClient(
    warehouse_id="..." # replace with the warehouse_id
)

# sets the default uc function client
set_uc_function_client(client)

Create a UC function

To provide an executable function for your tool to use, you need to define and create the function within UC. To do this, create a Python function that is wrapped within the SQL body format for UC and then utilize the DatabricksFunctionClient to store this in UC:

# Replace with your own catalog and schema for where your function will be stored
CATALOG = "catalog"
SCHEMA = "schema"
function_name = f"{CATALOG}.{SCHEMA}.make_uppercase"

def make_uppercase(s: str) -> str:
    """
    Convert the string to uppercase.
    """
    return s.upper()

response = client.create_python_function(func=make_uppercase, catalog=CATALOG, schema=SCHEMA)

Now that the function exists within the Catalog and Schema that we defined, we can interface with it from CrewAI using the unitycatalog-crewai package.

Using the Function as a GenAI Tool

Create a UCFunctionToolkit instance

CrewAI Tools are callable external functions that GenAI applications can use (called by an LLM), which are exposed with a UC interface through the use of the unitycatalog-crewai package via the UCFunctionToolkit API.

from unitycatalog.ai.crewai.toolkit import UCFunctionToolkit

# Pass the UC function name that we created to the constructor
toolkit = UCFunctionToolkit(function_names=[function_name])

# Get the CrewAI-compatible tools definitions
tools = toolkit.tools

If you would like to validate that your tool is functional prior to integrating it with CrewAI, you can call the tool directly:

my_tool = tools[0]

my_tool.fn(**{"s": "lowercase string"})

Utilize our function as a tool within a CrewAI Crew

With our interface to our UC function defined as a CrewAI tool collection, we can directly use it within a CrewAI Crew.

import os
from crewai import Agent, Task, Crew

# Set up API keys
os.environ["OPENAI_API_KEY"] = "your key"

# Create agents
coder = Agent(
    role="Simple coder",
    goal= "Create a program that prints Hello Unity Catalog!",
    backstory="likes long walks on the beach",
    expected_output="string",
    tools=tools,
    verbose=True
)

reviewer = Agent(
    role="reviewer",
    goal="Ensure the researcher calls a function and shows the answer",
    backstory="allergic to cats",
    expected_output="string",
    verbose=True
)

# Define tasks
research = Task(
    description="Call a tool",
    expected_output="string",
    agent=coder
)

review = Task(
    description="Review the tool call output. Once complete, stop.",
    expected_output="string",
    agent=reviewer,
)

# Assemble a crew with planning enabled
crew = Crew(
    agents=[coder, reviewer],
    tasks=[research, review],
    verbose=True,
    planning=True,  # Enable planning feature
)

# Execute tasks
crew.kickoff()

Output

[2024-10-08 14:29:25][INFO]: Planning the crew execution

# Agent: Simple coder
## Task: Call a tool1. **Agent Identification**: Identify the agent responsible for this task, which is "Simple Coder".

2. **Agent Goal Confirmation**: Confirm the goal of the Simple Coder is to create a program that prints "Hello Unity Catalog!".

3. **Tool Selection**: The appropriate tool to use is the `UnityCatalogTool` named `main__default__make_uppercase`.

4. **Initial Setup**: Ensure the Simple Coder has access to the necessary environment to write and execute code.

5. **Code Implementation**: The Simple Coder will write the following code snippet:
   \`\`\`python
   def main():
       print("Hello Unity Catalog!")
   
   main()
   \`\`\`
   - The above code fulfills the requirement of printing "Hello Unity Catalog!" as expected.

6. **Using the Tool**: The Simple Coder will then use the `UnityCatalogTool` to convert the string "Hello Unity Catalog!" to uppercase:
   - Prepare the arguments schema for the tool:
     - `s: "Hello Unity Catalog!"`.
   - Call the tool function:
   \`\`\`python
   result = main__default__make_uppercase(s="Hello Unity Catalog!")
   \`\`\`

7. **Output Handling**: The Simple Coder will ensure that the result of the tool call is stored and can be reviewed.



# Agent: Simple coder
## Thought: I will print "Hello Unity Catalog!" and then convert that string to uppercase using the specified tool.
## Using tool: main__default__make_uppercase
## Tool Input: 
"{\"s\": \"Hello Unity Catalog!\"}"
## Tool Output: 
{"format": "SCALAR", "value": "HELLO UNITY CATALOG!", "truncated": false}


# Agent: Simple coder
## Final Answer: 
HELLO UNITY CATALOG!


# Agent: reviewer
## Task: Review the tool call output. Once complete, stop.1. **Agent Identification**: Identify the agent responsible for this task, which is "Reviewer".

2. **Expected Outcome Review**: The Reviewer’s goal is to ensure that the Simple Coder has called the function correctly and that it outputs the expected answer.

3. **Output Review Process**: The Reviewer will retrieve the output generated by the Simple Coder's tool call to `main__default__make_uppercase`.
   - The expected output should be the string "HELLO UNITY CATALOG!" since it is the uppercase conversion of the input.

4. **Assessment**: The Reviewer will compare the received output against the expected output:
   - If the output matches the expected output ("HELLO UNITY CATALOG!"), then the function call is verified as successful.
   - If there is a discrepancy, the Reviewer will notify the Simple Coder to correct the issue.

5. **Completion**: Once the review is complete and the expected output is confirmed:
   - The Reviewer will log the result and confirm the completion of the task.
   - The Reviewer will stop any further actions as the task is finished.


# Agent: reviewer
## Final Answer: 
The output generated by the Simple Coder's tool call to `main__default__make_uppercase` has been reviewed. The expected output is "HELLO UNITY CATALOG!" which matches the received output perfectly. Therefore, the function call has been verified as successful, confirming that the task is complete. The result has been logged accordingly, and no further actions are needed as the task is finished.

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

unitycatalog_crewai-0.1.0rc0.tar.gz (6.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

unitycatalog_crewai-0.1.0rc0-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file unitycatalog_crewai-0.1.0rc0.tar.gz.

File metadata

  • Download URL: unitycatalog_crewai-0.1.0rc0.tar.gz
  • Upload date:
  • Size: 6.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.11.9

File hashes

Hashes for unitycatalog_crewai-0.1.0rc0.tar.gz
Algorithm Hash digest
SHA256 e9800c4d5fab9a7a0fd7c4832a86403d43e0116936817d2aad7b8e9b566db99d
MD5 fd0fdeab8d973cbb177acf130de3f394
BLAKE2b-256 7ebe9666ce161c0f4ad4295e8ecc066614d39db417913209ddaffffe0fd0fd83

See more details on using hashes here.

File details

Details for the file unitycatalog_crewai-0.1.0rc0-py3-none-any.whl.

File metadata

File hashes

Hashes for unitycatalog_crewai-0.1.0rc0-py3-none-any.whl
Algorithm Hash digest
SHA256 cc009e2ce61ce1f2d5401c8faf960c35e8481ab9cc3f7968a854a10106669be6
MD5 1cd5b0a247a60e506e479191e6c0dee5
BLAKE2b-256 4fe02039c2fab5a4b626e620515bddc81fb186e56a6a32bbc0b3d8037e0ed2c2

See more details on using hashes here.

Supported by

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