Skip to main content

This package is an SDK for building secure AI-powered applications using Auth0, Okta FGA and LlamaIndex.

Project description

Auth0 AI for LlamaIndex

auth0-ai-llamaindex is an SDK for building secure AI-powered applications using Auth0, Okta FGA and LlamaIndex.

Release Downloads License

Installation

⚠️ WARNING: auth0-ai-llamaindex is currently under development and it is not intended to be used in production, and therefore has no official support.

pip install auth0-ai-llamaindex

Async User Confirmation

Auth0AI uses CIBA (Client Initiated Backchannel Authentication) to handle user confirmation asynchronously. This is useful when you need to confirm a user action before proceeding with a tool execution.

Full Example of Async User Confirmation.

Define a tool with the proper authorizer specifying a function to resolve the user id:

from auth0_ai_llamaindex.auth0_ai import Auth0AI, set_ai_context
from auth0_ai_llamaindex.ciba import get_ciba_credentials
from llama_index.core.tools import FunctionTool

# If not provided, Auth0 settings will be read from env variables: `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET`
auth0_ai = Auth0AI()

with_async_user_confirmation = auth0_ai.with_async_user_confirmation(
    scope="stock:trade",
    audience=os.getenv("AUDIENCE"),
    binding_message=lambda ticker, qty: f"Authorize the purchase of {qty} {ticker}",
    user_id=lambda *_, **__: session["user"]["userinfo"]["sub"],
    # Optional:
    # store=InMemoryStore()
)

def tool_function(ticker: str, qty: int) -> str:
    credentials = get_ciba_credentials()
    headers = {
        "Authorization": f"{credentials["token_type"]} {credentials["access_token"]}",
        # ...
    }
    # Call API

trade_tool = with_async_user_confirmation(
    FunctionTool.from_defaults(
        name="trade_tool",
        description="Use this function to trade a stock",
        fn=tool_function,
        # ...
    )
)

# Set the thread ID to associate with the retrieved credentials
set_ai_context("<thread-id>")

Authorization for Tools

The FGAAuthorizer can leverage Okta FGA to authorize tools executions. The FGAAuthorizer.create function can be used to create an authorizer that checks permissions before executing the tool.

Full Example of Authorization for Tools.

  1. Create an instance of FGA Authorizer:
from auth0_ai_llamaindex.fga import FGAAuthorizer

# If not provided, FGA settings will be read from env variables: `FGA_STORE_ID`, `FGA_CLIENT_ID`, `FGA_CLIENT_SECRET`, etc.
fga = FGAAuthorizer.create()
  1. Define the FGA query (build_query) and, optionally, the on_unauthorized handler:
def build_fga_query(tool_input):
    return {
        "user": f"user:{context.get("user_id")}",
        "object": f"asset:{tool_input["ticker"]}",
        "relation": "can_buy",
        "context": {"current_time": datetime.now(timezone.utc).isoformat()}
    }

def on_unauthorized(tool_input):
    return f"The user is not allowed to buy {tool_input["qty"]} shares of {tool_input["ticker"]}."

use_fga = fga(
    build_query=build_fga_query,
    on_unauthorized=on_unauthorized,
)

Note: The parameters given to the build_query and on_unauthorized functions are the same as those provided to the tool function.

  1. Wrap the tool:
from llama_index.core.tools import FunctionTool

async def buy_tool_function(ticker: str, qty: int) -> str:
        # TODO: implement buy operation
        return f"Purchased {qty} shares of {ticker}"

func=use_fga(buy_tool_function)

return FunctionTool.from_defaults(
    fn=func,
    async_fn=func,
    name="buy",
    description="Use this function to buy stocks",
)

Calling APIs On User's Behalf

The Auth0AI.with_federated_connection function exchanges user's refresh token for a Federated Connection API access token.

Full Example of Calling APIs On User's Behalf.

Define a tool with the proper authorizer specifying a function to resolve the user's refresh token:

from auth0_ai_llamaindex.auth0_ai import Auth0AI, set_ai_context
from auth0_ai_llamaindex.federated_connections import get_credentials_for_connection
from llama_index.core.tools import FunctionTool

# If not provided, Auth0 settings will be read from env variables: `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET`
auth0_ai = Auth0AI()

with_google_calendar_access = auth0_ai.with_federated_connection(
    connection="google-oauth2",
    scopes=["https://www.googleapis.com/auth/calendar.freebusy"],
    refresh_token=lambda *_args, **_kwargs: session["user"]["refresh_token"],
    # Optional:
    # store=InMemoryStore()
)

def tool_function(date: datetime):
    credentials = get_credentials_for_connection()
    # Call Google API using credentials["access_token"]

check_calendar_tool = with_google_calendar_access(
    FunctionTool.from_defaults(
        name="check_user_calendar",
        description="Use this function to check if the user is available on a certain date and time",
        fn=tool_function,
        # ...
    )
)

# Set the thread ID to associate with the retrieved credentials
set_ai_context("<thread-id>")

RAG with FGA

The FGARetriever can be used to filter documents based on access control checks defined in Okta FGA. This retriever performs batch checks on retrieved documents, returning only the ones that pass the specified access criteria.

Full Example of RAG Application.

from llama_index.core import VectorStoreIndex, Document
from auth0_ai_llamaindex import FGARetriever
from openfga_sdk.client.models import ClientCheckRequest
from openfga_sdk import ClientConfiguration
from openfga_sdk.credentials import CredentialConfiguration, Credentials

# Define some docs:
documents = [
    Document(text="This is a public doc", doc_id="public-doc"),
    Document(text="This is a private doc", doc_id="private-doc"),
]

# Create a vector store:
vector_store = VectorStoreIndex.from_documents(documents)

# Create a retriever:
base_retriever = vector_store.as_retriever()

# Create the FGA retriever wrapper.
# If not provided, FGA settings will be read from env variables: `FGA_STORE_ID`, `FGA_CLIENT_ID`, `FGA_CLIENT_SECRET`, etc.
retriever = FGARetriever(
    base_retriever,
    build_query=lambda node: ClientCheckRequest(
        user=f'user:{user}',
        object=f'doc:{node.ref_doc_id}',
        relation="viewer",
    )
)

# Create a query engine:
query_engine = RetrieverQueryEngine.from_args(
    retriever=retriever,
    llm=OpenAI()
)

# Query:
response = query_engine.query("What is the forecast for ZEKO?")

print(response)

Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the Apache 2.0 license. See the LICENSE file for more info.

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

auth0_ai_llamaindex-1.0.0b1.tar.gz (11.9 kB view details)

Uploaded Source

Built Distribution

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

auth0_ai_llamaindex-1.0.0b1-py3-none-any.whl (14.1 kB view details)

Uploaded Python 3

File details

Details for the file auth0_ai_llamaindex-1.0.0b1.tar.gz.

File metadata

  • Download URL: auth0_ai_llamaindex-1.0.0b1.tar.gz
  • Upload date:
  • Size: 11.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.2

File hashes

Hashes for auth0_ai_llamaindex-1.0.0b1.tar.gz
Algorithm Hash digest
SHA256 a1cdf6413184afef777c84b9873479528d367b4c1ef6c79d5993868e2814bcfd
MD5 1ca996c68f1587ce2295b570d7fec0d3
BLAKE2b-256 79a948f5a7f3ccee24c92e59830790b1293fdf11c46087d306652cac8bfd8e9f

See more details on using hashes here.

File details

Details for the file auth0_ai_llamaindex-1.0.0b1-py3-none-any.whl.

File metadata

File hashes

Hashes for auth0_ai_llamaindex-1.0.0b1-py3-none-any.whl
Algorithm Hash digest
SHA256 da1f67e487b144c10f4d72e36ad277caa8e2c4c931078ac463fcd5fc82ba0369
MD5 5752d759bdf25a8c5b1229e44aca9085
BLAKE2b-256 88cc2d6fd6ded31b776d1d316b7b6089ee1c812dc09d4733408b7b256e107f12

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