Skip to content
Snippets Groups Projects
Unverified Commit 30a52599 authored by Siraj R Aizlewood's avatar Siraj R Aizlewood
Browse files

Simplified layer and route code.

We don't have OpenAI Function Calling Dynamic Routes as an alternative to regular dynamic routes any more, it is now the default.
parent 9de379b2
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/aurelio-labs/semantic-router/blob/main/docs/02-dynamic-routes.ipynb) [![Open nbviewer](https://raw.githubusercontent.com/pinecone-io/examples/master/assets/nbviewer-shield.svg)](https://nbviewer.org/github/aurelio-labs/semantic-router/blob/main/docs/02-dynamic-routes.ipynb)
%% Cell type:markdown id: tags:
# Dynamic Routes
%% Cell type:markdown id: tags:
In semantic-router there are two types of routes that can be chosen. Both routes belong to the `Route` object, the only difference between them is that _static_ routes return a `Route.name` when chosen, whereas _dynamic_ routes use an LLM call to produce parameter input values.
For example, a _static_ route will tell us if a query is talking about mathematics by returning the route name (which could be `"math"` for example). A _dynamic_ route does the same thing, but it also extracts key information from the input utterance to be used in a function associated with that route.
For example we could provide a dynamic route with associated utterances:
```
"what is x to the power of y?"
"what is 9 to the power of 4?"
"calculate the result of base x and exponent y"
"calculate the result of base 10 and exponent 3"
"return x to the power of y"
```
and we could also provide the route with a schema outlining key features of the function:
```
def power(base: float, exponent: float) -> float:
"""Raise base to the power of exponent.
Args:
base (float): The base number.
exponent (float): The exponent to which the base is raised.
Returns:
float: The result of base raised to the power of exponent.
"""
return base ** exponent
```
Then, if the users input utterance is "What is 2 to the power of 3?", the route will be triggered, as the input utterance is semantically similar to the route utterances. Furthermore, the route utilizes an LLM to identify that `base=2` and `expoenent=3`. These values are returned in such a way that they can be used in the above `power` function. That is, the dynamic router automates the process of calling relevant functions from natural language inputs.
***⚠️ Note: We have a fully local version of dynamic routes available at [docs/05-local-execution.ipynb](https://github.com/aurelio-labs/semantic-router/blob/main/docs/05-local-execution.ipynb). The local 05 version tends to outperform the OpenAI version we demo in this notebook, so we'd recommend trying [05](https://github.com/aurelio-labs/semantic-router/blob/main/docs/05-local-execution.ipynb)!***
%% Cell type:markdown id: tags:
## Installing the Library
%% Cell type:code id: tags:
``` python
!pip install tzdata
!pip install -qU semantic-router
```
%% Output
Requirement already satisfied: tzdata in c:\users\siraj\documents\personal\work\aurelio\virtual environments\semantic_router_3\lib\site-packages (2024.1)
[notice] A new release of pip is available: 23.1.2 -> 24.0
[notice] To update, run: python.exe -m pip install --upgrade pip
[notice] A new release of pip is available: 23.1.2 -> 24.0
[notice] To update, run: python.exe -m pip install --upgrade pip
%% Cell type:markdown id: tags:
## Initializing Routes and RouteLayer
%% Cell type:markdown id: tags:
Dynamic routes are treated in the same way as static routes, let's begin by initializing a `RouteLayer` consisting of static routes.
%% Cell type:code id: tags:
``` python
from semantic_router import Route
politics = Route(
name="politics",
utterances=[
"isn't politics the best thing ever",
"why don't you tell me about your political opinions",
"don't you just love the president" "don't you just hate the president",
"they're going to destroy this country!",
"they will save the country!",
],
)
chitchat = Route(
name="chitchat",
utterances=[
"how's the weather today?",
"how are things going?",
"lovely weather today",
"the weather is horrendous",
"let's go to the chippy",
],
)
routes = [politics, chitchat]
```
%% Output
c:\Users\Siraj\Documents\Personal\Work\Aurelio\Virtual Environments\semantic_router_3\Lib\site-packages\tqdm\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm
%% Cell type:markdown id: tags:
We initialize our `RouteLayer` with our `encoder` and `routes`. We can use popular encoder APIs like `CohereEncoder` and `OpenAIEncoder`, or local alternatives like `FastEmbedEncoder`.
%% Cell type:code id: tags:
``` python
import os
from getpass import getpass
from semantic_router import RouteLayer
from semantic_router.encoders import CohereEncoder, OpenAIEncoder
# dashboard.cohere.ai
# os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass(
# "Enter Cohere API Key: "
# )
# platform.openai.com
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass(
"Enter OpenAI API Key: "
)
# encoder = CohereEncoder()
encoder = OpenAIEncoder()
rl = RouteLayer(encoder=encoder, routes=routes)
```
%% Output
2024-04-30 02:22:00 INFO semantic_router.utils.logger local
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 1 length: 34
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 1 trunc length: 34
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 2 length: 51
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 2 trunc length: 51
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 3 length: 66
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 3 trunc length: 66
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 4 length: 38
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 4 trunc length: 38
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 5 length: 27
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 5 trunc length: 27
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 6 length: 24
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 6 trunc length: 24
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 7 length: 21
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 7 trunc length: 21
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 8 length: 20
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 8 trunc length: 20
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 9 length: 25
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 9 trunc length: 25
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 10 length: 22
2024-04-30 02:22:00 INFO semantic_router.utils.logger Document 10 trunc length: 22
2024-04-30 03:58:34 INFO semantic_router.utils.logger local
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 1 length: 34
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 1 trunc length: 34
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 2 length: 51
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 2 trunc length: 51
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 3 length: 66
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 3 trunc length: 66
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 4 length: 38
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 4 trunc length: 38
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 5 length: 27
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 5 trunc length: 27
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 6 length: 24
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 6 trunc length: 24
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 7 length: 21
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 7 trunc length: 21
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 8 length: 20
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 8 trunc length: 20
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 9 length: 25
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 9 trunc length: 25
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 10 length: 22
2024-04-30 03:58:34 INFO semantic_router.utils.logger Document 10 trunc length: 22
%% Cell type:markdown id: tags:
We run the solely static routes layer:
%% Cell type:code id: tags:
``` python
rl("how's the weather today?")
```
%% Output
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 1 length: 24
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 1 trunc length: 24
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 1 length: 24
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 1 trunc length: 24
RouteChoice(name='chitchat', function_call=None, similarity_score=None)
%% Cell type:markdown id: tags:
## Creating a Dynamic Route
%% Cell type:markdown id: tags:
As with static routes, we must create a dynamic route before adding it to our route layer. To make a route dynamic, we need to provide a `function_schema`. The function schema provides instructions on what a function is, so that an LLM can decide how to use it correctly.
%% Cell type:code id: tags:
``` python
from datetime import datetime
from zoneinfo import ZoneInfo
def get_time(timezone: str) -> str:
"""Finds the current time in a specific timezone.
:param timezone: The timezone to find the current time in, should
be a valid timezone from the IANA Time Zone Database like
"America/New_York" or "Europe/London". Do NOT put the place
name itself like "rome", or "new york", you must provide
the IANA format.
:type timezone: str
:return: The current time in the specified timezone."""
now = datetime.now(ZoneInfo(timezone))
return now.strftime("%H:%M")
```
%% Cell type:code id: tags:
``` python
get_time("America/New_York")
```
%% Output
'18:22'
'19:58'
%% Cell type:markdown id: tags:
To get the function schema we can use the `get_schema` function from the `function_call` module.
%% Cell type:code id: tags:
``` python
from semantic_router.utils.function_call import get_schema_openai
schema = get_schema_openai(get_time)
schema
```
%% Output
{'type': 'function',
'function': {'name': 'get_time',
'description': 'Finds the current time in a specific timezone.\n\n:param timezone: The timezone to find the current time in, should\n be a valid timezone from the IANA Time Zone Database like\n "America/New_York" or "Europe/London". Do NOT put the place\n name itself like "rome", or "new york", you must provide\n the IANA format.\n:type timezone: str\n:return: The current time in the specified timezone.',
'parameters': {'type': 'object',
'properties': {'timezone': {'type': 'string',
'description': 'The timezone to find the current time in, should\n be a valid timezone from the IANA Time Zone Database like\n "America/New_York" or "Europe/London". Do NOT put the place\n name itself like "rome", or "new york", you must provide\n the IANA format.'}},
'required': ['timezone']}}}
%% Cell type:markdown id: tags:
We use this to define our dynamic route:
%% Cell type:code id: tags:
``` python
time_route = Route(
name="get_time",
utterances=[
"what is the time in new york city?",
"what is the time in london?",
"I live in Rome, what time is it?",
],
function_schema=schema,
)
```
%% Cell type:code id: tags:
``` python
time_route.llm
```
%% Cell type:markdown id: tags:
Add the new route to our `layer`:
%% Cell type:code id: tags:
``` python
rl.add(time_route)
```
%% Output
2024-04-30 02:22:01 INFO semantic_router.utils.logger Adding `get_time` route
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 1 length: 34
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 1 trunc length: 34
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 2 length: 27
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 2 trunc length: 27
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 3 length: 32
2024-04-30 02:22:01 INFO semantic_router.utils.logger Document 3 trunc length: 32
2024-04-30 03:58:35 INFO semantic_router.utils.logger Adding `get_time` route
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 1 length: 34
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 1 trunc length: 34
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 2 length: 27
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 2 trunc length: 27
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 3 length: 32
2024-04-30 03:58:35 INFO semantic_router.utils.logger Document 3 trunc length: 32
%% Cell type:code id: tags:
``` python
time_route.llm
```
%% Cell type:markdown id: tags:
Now we can ask our layer a time related question to trigger our new dynamic route.
%% Cell type:code id: tags:
``` python
out = rl("what is the time in new york city?")
out
```
%% Output
2024-04-30 02:22:02 INFO semantic_router.utils.logger Document 1 length: 34
2024-04-30 02:22:02 INFO semantic_router.utils.logger Document 1 trunc length: 34
2024-04-30 02:22:02 WARNING semantic_router.utils.logger No LLM provided for dynamic route, will use OpenAI LLM default. Ensure API key is set in OPENAI_API_KEY environment variable.
2024-04-30 03:58:36 INFO semantic_router.utils.logger Document 1 length: 34
2024-04-30 03:58:36 INFO semantic_router.utils.logger Document 1 trunc length: 34
2024-04-30 03:58:36 WARNING semantic_router.utils.logger No LLM provided for dynamic route, will use OpenAI LLM default. Ensure API key is set in OPENAI_API_KEY environment variable.
RouteChoice(name='get_time', function_call={'timezone': 'America/New_York'}, similarity_score=None)
%% Cell type:code id: tags:
``` python
get_time(**out.function_call)
```
%% Output
'18:22'
'19:58'
%% Cell type:markdown id: tags:
Our dynamic route provides both the route itself _and_ the input parameters required to use the route.
%% Cell type:markdown id: tags:
---
......
......@@ -244,15 +244,10 @@ class RouteLayer:
passed = self._check_threshold(top_class_scores, route)
if passed and route is not None and not simulate_static:
if text is None:
if route.function_schema:
raise ValueError(
"Route has a function schema, but no text was provided."
)
if route.openai_function_schema:
raise ValueError(
"Route has an OpenAI function schema, but no text was provided."
)
if route.function_schema and text is None:
raise ValueError(
"Route has a function schema, but no text was provided."
)
if route.function_schema and not isinstance(route.llm, BaseLLM):
if not self.llm:
logger.warning(
......@@ -265,22 +260,6 @@ class RouteLayer:
route.llm = self.llm
else:
route.llm = self.llm
if route.openai_function_schema and not isinstance(route.llm, BaseLLM):
if not self.llm:
logger.warning(
"No LLM provided for dynamic route, will use OpenAI LLM "
"default. Ensure API key is set in OPENAI_API_KEY environment "
"variable."
)
self.llm = OpenAILLM()
route.llm = self.llm
else:
if not isinstance(self.llm, OpenAILLM):
raise TypeError(
"LLM must be an instance of OpenAILLM for openai_function_schema."
)
route.llm = self.llm
return route(text)
elif passed and route is not None and simulate_static:
return RouteChoice(
......
......@@ -48,7 +48,6 @@ class Route(BaseModel):
utterances: Union[List[str], List[Union[Any, "Image"]]]
description: Optional[str] = None
function_schema: Optional[Dict[str, Any]] = None
openai_function_schema: Optional[Dict[str, Any]] = None
llm: Optional[BaseLLM] = None
score_threshold: Optional[float] = None
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment