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

Linting (MyPy fixes) and testing.

parent 0bb4f975
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% 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) [![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: %% Cell type:markdown id: tags:
# Dynamic Routes # Dynamic Routes
%% Cell type:markdown id: tags: %% 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. 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, 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: For example we could provide a dynamic route with associated utterances:
``` ```
"what is x to the power of y?" "what is x to the power of y?"
"what is 9 to the power of 4?" "what is 9 to the power of 4?"
"calculate the result of base x and exponent y" "calculate the result of base x and exponent y"
"calculate the result of base 10 and exponent 3" "calculate the result of base 10 and exponent 3"
"return x to the power of y" "return x to the power of y"
``` ```
and we could also provide the route with a schema outlining key features of the function: and we could also provide the route with a schema outlining key features of the function:
``` ```
def power(base: float, exponent: float) -> float: def power(base: float, exponent: float) -> float:
"""Raise base to the power of exponent. """Raise base to the power of exponent.
Args: Args:
base (float): The base number. base (float): The base number.
exponent (float): The exponent to which the base is raised. exponent (float): The exponent to which the base is raised.
Returns: Returns:
float: The result of base raised to the power of exponent. float: The result of base raised to the power of exponent.
""" """
return base ** 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. 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)!*** ***⚠️ 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: %% Cell type:markdown id: tags:
## Installing the Library ## Installing the Library
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
!pip install -qU semantic-router==0.0.34 !pip install -qU semantic-router==0.0.34
!pip install tzdata !pip install tzdata
``` ```
%% Output %% Output
[notice] A new release of pip is available: 23.1.2 -> 24.0 [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] To update, run: python.exe -m pip install --upgrade pip
Requirement already satisfied: tzdata in c:\users\siraj\documents\personal\work\aurelio\virtual environments\semantic_router\lib\site-packages (2024.1) Requirement already satisfied: tzdata in c:\users\siraj\documents\personal\work\aurelio\virtual environments\semantic_router_2\lib\site-packages (2024.1)
[notice] A new release of pip is available: 23.1.2 -> 24.0 [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] To update, run: python.exe -m pip install --upgrade pip
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Initializing Routes and RouteLayer ## Initializing Routes and RouteLayer
%% Cell type:markdown id: tags: %% 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. 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: %% Cell type:code id: tags:
``` python ``` python
from semantic_router import Route from semantic_router import Route
politics = Route( politics = Route(
name="politics", name="politics",
utterances=[ utterances=[
"isn't politics the best thing ever", "isn't politics the best thing ever",
"why don't you tell me about your political opinions", "why don't you tell me about your political opinions",
"don't you just love the president" "don't you just hate the president", "don't you just love the president" "don't you just hate the president",
"they're going to destroy this country!", "they're going to destroy this country!",
"they will save the country!", "they will save the country!",
], ],
) )
chitchat = Route( chitchat = Route(
name="chitchat", name="chitchat",
utterances=[ utterances=[
"how's the weather today?", "how's the weather today?",
"how are things going?", "how are things going?",
"lovely weather today", "lovely weather today",
"the weather is horrendous", "the weather is horrendous",
"let's go to the chippy", "let's go to the chippy",
], ],
) )
routes = [politics, chitchat] routes = [politics, chitchat]
``` ```
%% Output %% Output
c:\Users\Siraj\Documents\Personal\Work\Aurelio\Virtual Environments\semantic_router\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 c:\Users\Siraj\Documents\Personal\Work\Aurelio\Virtual Environments\semantic_router_2\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 from .autonotebook import tqdm as notebook_tqdm
%% Cell type:markdown id: tags: %% 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`. 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: %% Cell type:code id: tags:
``` python ``` python
import os import os
from getpass import getpass from getpass import getpass
from semantic_router import RouteLayer from semantic_router import RouteLayer
from semantic_router.encoders import CohereEncoder, OpenAIEncoder from semantic_router.encoders import CohereEncoder, OpenAIEncoder
# dashboard.cohere.ai # dashboard.cohere.ai
# os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass( # os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass(
# "Enter Cohere API Key: " # "Enter Cohere API Key: "
# ) # )
# platform.openai.com # platform.openai.com
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass( os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass(
"Enter OpenAI API Key: " "Enter OpenAI API Key: "
) )
# encoder = CohereEncoder() # encoder = CohereEncoder()
encoder = OpenAIEncoder() encoder = OpenAIEncoder()
rl = RouteLayer(encoder=encoder, routes=routes) rl = RouteLayer(encoder=encoder, routes=routes)
``` ```
%% Output %% Output
2024-04-29 01:53:55 INFO semantic_router.utils.logger local 2024-04-29 14:34:53 INFO semantic_router.utils.logger local
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We run the solely static routes layer: We run the solely static routes layer:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
rl("how's the weather today?") rl("how's the weather today?")
``` ```
%% Output %% Output
RouteChoice(name='chitchat', function_call=None, similarity_score=None) RouteChoice(name='chitchat', function_call=None, similarity_score=None)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Creating a Dynamic Route ## Creating a Dynamic Route
%% Cell type:markdown id: tags: %% 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. 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: %% Cell type:code id: tags:
``` python ``` python
from datetime import datetime from datetime import datetime
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
def get_time(timezone: str) -> str: def get_time(timezone: str) -> str:
"""Finds the current time in a specific timezone. """Finds the current time in a specific timezone.
:param timezone: The timezone to find the current time in, should :param timezone: The timezone to find the current time in, should
be a valid timezone from the IANA Time Zone Database like be a valid timezone from the IANA Time Zone Database like
"America/New_York" or "Europe/London". Do NOT put the place "America/New_York" or "Europe/London". Do NOT put the place
name itself like "rome", or "new york", you must provide name itself like "rome", or "new york", you must provide
the IANA format. the IANA format.
:type timezone: str :type timezone: str
:return: The current time in the specified timezone.""" :return: The current time in the specified timezone."""
now = datetime.now(ZoneInfo(timezone)) now = datetime.now(ZoneInfo(timezone))
return now.strftime("%H:%M") return now.strftime("%H:%M")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
get_time("America/New_York") get_time("America/New_York")
``` ```
%% Output %% Output
'17:53' '06:34'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To get the function schema we can use the `get_schema` function from the `function_call` module. To get the function schema we can use the `get_schema` function from the `function_call` module.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from semantic_router.utils.function_call import get_schema from semantic_router.utils.function_call import get_schema
schema = get_schema(get_time) schema = get_schema(get_time)
schema schema
``` ```
%% Output %% Output
{'name': 'get_time', {'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.', '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.',
'signature': '(timezone: str) -> str', 'signature': '(timezone: str) -> str',
'output': "<class 'str'>"} 'output': "<class 'str'>"}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We use this to define our dynamic route: We use this to define our dynamic route:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
time_route = Route( time_route = Route(
name="get_time", name="get_time",
utterances=[ utterances=[
"what is the time in new york city?", "what is the time in new york city?",
"what is the time in london?", "what is the time in london?",
"I live in Rome, what time is it?", "I live in Rome, what time is it?",
], ],
function_schema=schema, function_schema=schema,
) )
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
time_route.llm time_route.llm
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Add the new route to our `layer`: Add the new route to our `layer`:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
rl.add(time_route) rl.add(time_route)
``` ```
%% Output %% Output
2024-04-29 01:53:56 INFO semantic_router.utils.logger Adding `get_time` route 2024-04-29 14:34:54 INFO semantic_router.utils.logger Adding `get_time` route
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
time_route.llm time_route.llm
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we can ask our layer a time related question to trigger our new dynamic route. Now we can ask our layer a time related question to trigger our new dynamic route.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
out = rl("what is the time in new york city?") out = rl("what is the time in new york city?")
get_time(**out.function_call) out
``` ```
%% Output %% Output
2024-04-29 01:53:57 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-29 14:34:55 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-29 01:53:57 INFO semantic_router.utils.logger Extracting function input... 2024-04-29 14:34:55 INFO semantic_router.utils.logger Extracting function input...
2024-04-29 01:53:58 INFO semantic_router.utils.logger LLM output: { 2024-04-29 14:34:56 INFO semantic_router.utils.logger LLM output: {
"timezone": "America/New_York" "timezone": "America/New_York"
} }
2024-04-29 01:53:58 INFO semantic_router.utils.logger Function inputs: {'timezone': 'America/New_York'} 2024-04-29 14:34:56 INFO semantic_router.utils.logger Function inputs: {'timezone': 'America/New_York'}
'17:53' RouteChoice(name='get_time', function_call={'timezone': 'America/New_York'}, similarity_score=None)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
time_route.llm get_time(**out.function_call)
``` ```
%% Output %% Output
OpenAILLM(name='gpt-3.5-turbo', client=<openai.OpenAI object at 0x0000024DD8AEAF10>, temperature=0.01, max_tokens=200) '06:34'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Our dynamic route provides both the route itself _and_ the input parameters required to use the route. Our dynamic route provides both the route itself _and_ the input parameters required to use the route.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
--- ---
......
%% Cell type:markdown id: tags: %% 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) [![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: %% Cell type:markdown id: tags:
# Dynamic Routes via OpenAI Function Calling # Dynamic Routes via OpenAI Function Calling
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
In this Notebook we showcase an alternative to dynamic routes where an `openai_function_schema` is specified or the Route, and in doing so, OpenAIs "Function Calling" API is utilized. In this Notebook we showcase an alternative to dynamic routes where an `openai_function_schema` is specified or the Route, and in doing so, OpenAIs "Function Calling" API is utilized.
The usual Semantic Router procedure is used to determine which Route is most appropriate for the input utterance. Then, rather than using a regular LLM call with careful prompt engineering to allow the LLM to extract function arguments from the input, OpenAIs Function Calling is leveraged to try and obtain function arguments more reliably. The usual Semantic Router procedure is used to determine which Route is most appropriate for the input utterance. Then, rather than using a regular LLM call with careful prompt engineering to allow the LLM to extract function arguments from the input, OpenAIs Function Calling is leveraged to try and obtain function arguments more reliably.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Installing the Library ## Installing the Library
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
!pip install -qU semantic-router==0.0.34 !pip install -qU semantic-router==0.0.34
!pip install tzdata !pip install tzdata
``` ```
%% Output %% Output
[notice] A new release of pip is available: 23.1.2 -> 24.0 [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] To update, run: python.exe -m pip install --upgrade pip
Requirement already satisfied: tzdata in c:\users\siraj\documents\personal\work\aurelio\virtual environments\semantic_router_2\lib\site-packages (2024.1) Requirement already satisfied: tzdata in c:\users\siraj\documents\personal\work\aurelio\virtual environments\semantic_router_2\lib\site-packages (2024.1)
[notice] A new release of pip is available: 23.1.2 -> 24.0 [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] To update, run: python.exe -m pip install --upgrade pip
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Initializing Routes and RouteLayer ## Initializing Routes and RouteLayer
%% Cell type:markdown id: tags: %% 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. 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: %% Cell type:code id: tags:
``` python ``` python
from semantic_router import Route from semantic_router import Route
politics = Route( politics = Route(
name="politics", name="politics",
utterances=[ utterances=[
"isn't politics the best thing ever", "isn't politics the best thing ever",
"why don't you tell me about your political opinions", "why don't you tell me about your political opinions",
"don't you just love the president" "don't you just hate the president", "don't you just love the president" "don't you just hate the president",
"they're going to destroy this country!", "they're going to destroy this country!",
"they will save the country!", "they will save the country!",
], ],
) )
chitchat = Route( chitchat = Route(
name="chitchat", name="chitchat",
utterances=[ utterances=[
"how's the weather today?", "how's the weather today?",
"how are things going?", "how are things going?",
"lovely weather today", "lovely weather today",
"the weather is horrendous", "the weather is horrendous",
"let's go to the chippy", "let's go to the chippy",
], ],
) )
routes = [politics, chitchat] routes = [politics, chitchat]
``` ```
%% Output %% Output
c:\Users\Siraj\Documents\Personal\Work\Aurelio\Virtual Environments\semantic_router_2\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 c:\Users\Siraj\Documents\Personal\Work\Aurelio\Virtual Environments\semantic_router_2\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 from .autonotebook import tqdm as notebook_tqdm
%% Cell type:markdown id: tags: %% 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`. 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: %% Cell type:code id: tags:
``` python ``` python
import os import os
from getpass import getpass from getpass import getpass
from semantic_router import RouteLayer from semantic_router import RouteLayer
from semantic_router.encoders import CohereEncoder, OpenAIEncoder from semantic_router.encoders import CohereEncoder, OpenAIEncoder
# dashboard.cohere.ai # dashboard.cohere.ai
# os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass( # os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass(
# "Enter Cohere API Key: " # "Enter Cohere API Key: "
# ) # )
# platform.openai.com # platform.openai.com
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass( os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass(
"Enter OpenAI API Key: " "Enter OpenAI API Key: "
) )
# encoder = CohereEncoder() # encoder = CohereEncoder()
encoder = OpenAIEncoder() encoder = OpenAIEncoder()
rl = RouteLayer(encoder=encoder, routes=routes) rl = RouteLayer(encoder=encoder, routes=routes)
``` ```
%% Output %% Output
2024-04-29 01:53:43 INFO semantic_router.utils.logger local 2024-04-29 14:35:09 INFO semantic_router.utils.logger local
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We run the solely static routes layer: We run the solely static routes layer:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
rl("how's the weather today?") rl("how's the weather today?")
``` ```
%% Output %% Output
RouteChoice(name='chitchat', function_call=None, similarity_score=None) RouteChoice(name='chitchat', function_call=None, similarity_score=None)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Creating a Dynamic Route ## Creating a Dynamic Route
%% Cell type:markdown id: tags: %% 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. 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: %% Cell type:code id: tags:
``` python ``` python
from datetime import datetime from datetime import datetime
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
def get_time(timezone: str) -> str: def get_time(timezone: str) -> str:
"""Finds the current time in a specific timezone. """Finds the current time in a specific timezone.
:param timezone: The timezone to find the current time in, should :param timezone: The timezone to find the current time in, should
be a valid timezone from the IANA Time Zone Database like be a valid timezone from the IANA Time Zone Database like
"America/New_York" or "Europe/London". Do NOT put the place "America/New_York" or "Europe/London". Do NOT put the place
name itself like "rome", or "new york", you must provide name itself like "rome", or "new york", you must provide
the IANA format. the IANA format.
:type timezone: str :type timezone: str
:return: The current time in the specified timezone.""" :return: The current time in the specified timezone."""
now = datetime.now(ZoneInfo(timezone)) now = datetime.now(ZoneInfo(timezone))
return now.strftime("%H:%M") return now.strftime("%H:%M")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
get_time("America/New_York") get_time("America/New_York")
``` ```
%% Output %% Output
'17:53' '06:35'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To get the function schema we can use the `get_schema` function from the `function_call` module. To get the function schema we can use the `get_schema` function from the `function_call` module.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from semantic_router.utils.function_call import get_schema from semantic_router.utils.function_call import get_schema
schema = get_schema(get_time) schema = get_schema(get_time)
schema schema
``` ```
%% Output %% Output
{'name': 'get_time', {'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.', '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.',
'signature': '(timezone: str) -> str', 'signature': '(timezone: str) -> str',
'output': "<class 'str'>"} 'output': "<class 'str'>"}
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from semantic_router.utils.function_call import get_schema_openai_func_calling from semantic_router.utils.function_call import get_schema_openai_func_calling
openai_function_schema = get_schema_openai_func_calling(get_time) openai_function_schema = get_schema_openai_func_calling(get_time)
openai_function_schema openai_function_schema
``` ```
%% Output %% Output
{'type': 'function', {'type': 'function',
'function': {'name': 'get_time', '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.', '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', 'parameters': {'type': 'object',
'properties': {'timezone': {'type': 'string', '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.'}}, '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']}}} 'required': ['timezone']}}}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We use this to define our dynamic route: We use this to define our dynamic route:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
time_route = Route( time_route = Route(
name="get_time", name="get_time",
utterances=[ utterances=[
"what is the time in new york city?", "what is the time in new york city?",
"what is the time in london?", "what is the time in london?",
"I live in Rome, what time is it?", "I live in Rome, what time is it?",
], ],
# function_schema=schema, # function_schema=schema,
openai_function_schema=openai_function_schema, openai_function_schema=openai_function_schema,
) )
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Add the new route to our `layer`: Add the new route to our `layer`:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
rl.add(time_route) rl.add(time_route)
``` ```
%% Output %% Output
2024-04-29 01:53:44 INFO semantic_router.utils.logger Adding `get_time` route 2024-04-29 14:35:10 INFO semantic_router.utils.logger Adding `get_time` route
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now we can ask our layer a time related question to trigger our new dynamic route. Now we can ask our layer a time related question to trigger our new dynamic route.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
out = rl("what is the time in new york city?") out = rl("what is the time in new york city?")
out out
``` ```
%% Output %% Output
2024-04-29 01:53:45 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-29 14:35:11 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) RouteChoice(name='get_time', function_call={'timezone': 'America/New_York'}, similarity_score=None)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
get_time(**out.function_call) get_time(**out.function_call)
``` ```
%% Output %% Output
'17:53' '06:35'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Our dynamic route provides both the route itself _and_ the input parameters required to use the route. Our dynamic route provides both the route itself _and_ the input parameters required to use the route.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now let's just verify that the other route selection still work correctly, starting with chitchat. Now let's just verify that the other route selection still work correctly, starting with chitchat.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
out = rl("What's the weather like?") out = rl("What's the weather like?")
out out
``` ```
%% Output %% Output
RouteChoice(name='chitchat', function_call=None, similarity_score=None) RouteChoice(name='chitchat', function_call=None, similarity_score=None)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now, an utterance that shouldn't fall into any of the routes defined above. Now, an utterance that shouldn't fall into any of the routes defined above.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
out = rl("Tell me how to bake cake?") out = rl("Tell me how to bake cake?")
out out
``` ```
%% Output %% Output
RouteChoice(name=None, function_call=None, similarity_score=None) RouteChoice(name=None, function_call=None, similarity_score=None)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
--- ---
......
...@@ -49,6 +49,7 @@ class OpenAILLM(BaseLLM): ...@@ -49,6 +49,7 @@ class OpenAILLM(BaseLLM):
tools = [openai_function_schema] tools = [openai_function_schema]
else: else:
tools = None tools = None
completion = self.client.chat.completions.create( completion = self.client.chat.completions.create(
model=self.name, model=self.name,
messages=[m.to_openai() for m in messages], messages=[m.to_openai() for m in messages],
...@@ -57,12 +58,21 @@ class OpenAILLM(BaseLLM): ...@@ -57,12 +58,21 @@ class OpenAILLM(BaseLLM):
tools=tools, # type: ignore # MyPy expecting Iterable[ChatCompletionToolParam] | NotGiven, but dict is accepted by OpenAI. tools=tools, # type: ignore # MyPy expecting Iterable[ChatCompletionToolParam] | NotGiven, but dict is accepted by OpenAI.
) )
output = completion.choices[0].message.content
if openai_function_schema: if openai_function_schema:
return completion.choices[0].message.tool_calls tool_calls = completion.choices[0].message.tool_calls
if not output: if tool_calls is None:
raise Exception("No output generated") raise ValueError("Invalid output, expected a tool call.")
if len(tool_calls) != 1:
raise ValueError("Invalid output, expected a single tool to be specified.")
arguments = tool_calls[0].function.arguments
if arguments is None:
raise ValueError("Invalid output, expected arguments to be specified.")
output = str(arguments) # str to keep MyPy happy.
else:
content = completion.choices[0].message.content
if content is None:
raise ValueError("Invalid output, expected content.")
output = str(content) # str to keep MyPy happy.
return output return output
except Exception as e: except Exception as e:
logger.error(f"LLM error: {e}") logger.error(f"LLM error: {e}")
...@@ -75,12 +85,6 @@ class OpenAILLM(BaseLLM): ...@@ -75,12 +85,6 @@ class OpenAILLM(BaseLLM):
system_prompt = "You are an intelligent AI. Given a command or request from the user, call the function to complete the request." system_prompt = "You are an intelligent AI. Given a command or request from the user, call the function to complete the request."
messages.append(Message(role="system", content=system_prompt)) messages.append(Message(role="system", content=system_prompt))
messages.append(Message(role="user", content=query)) messages.append(Message(role="user", content=query))
output = self(messages=messages, openai_function_schema=openai_function_schema) function_inputs_str = self(messages=messages, openai_function_schema=openai_function_schema)
if not output: function_inputs = json.loads(function_inputs_str)
raise Exception("No output generated for extract function input")
if len(output) != 1:
raise ValueError("Invalid output, expected a single tool to be called")
tool_call = output[0]
arguments_json = tool_call.function.arguments
function_inputs = json.loads(arguments_json)
return function_inputs return function_inputs
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