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

Retesting Notebook.

parent 02c46ca8
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 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
``` ```
%% 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\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-27 02:23:29 INFO semantic_router.utils.logger local 2024-04-28 22:54:05 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
'18:23' '14:54'
%% 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-27 02:23:30 INFO semantic_router.utils.logger Adding `get_time` route 2024-04-28 22:54:06 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-28 22:54:07 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.
tools
[{'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']}}}]
##################################################
##################################################
completion.choices[0].message.tool_calls
[ChatCompletionMessageToolCall(id='call_MS5F6OgeHtULS2OYN1dGSd7C', function=Function(arguments='{"timezone":"America/New_York"}', name='get_time'), type='function')]
##################################################
##################################################
output
[ChatCompletionMessageToolCall(id='call_MS5F6OgeHtULS2OYN1dGSd7C', function=Function(arguments='{"timezone":"America/New_York"}', name='get_time'), type='function')]
##################################################
##################################################
function_inputs
{'timezone': 'America/New_York'}
##################################################
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
'14:07' '14:54'
%% 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:
--- ---
......
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