Skip to content
Snippets Groups Projects
Commit c85f0c91 authored by Simonas's avatar Simonas
Browse files

function calling with gpt model

parent 418a0c8b
No related branches found
No related tags found
No related merge requests found
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# https://platform.openai.com/docs/guides/function-calling # https://platform.openai.com/docs/guides/function-calling
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import json
import openai import openai
from semantic_router.utils.logger import logger
def llm_openai(prompt: str, model: str = "gpt-4") -> str:
try:
response = openai.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": f"{prompt}"},
],
)
ai_message = response.choices[0].message.content
if not ai_message:
raise Exception("AI message is empty", ai_message)
logger.info(f"AI message: {ai_message}")
return ai_message
except Exception as e:
raise Exception("Failed to call OpenAI API", e)
```
%% Cell type:code id: tags:
``` python
import json
from semantic_router.utils.logger import logger
def generate_config(specification: dict) -> dict: def generate_config(specification: dict) -> dict:
print("Generating config...") logger.info("Generating config...")
example_specification = ( example_specification = (
{ {
"type": "function", "type": "function",
"function": { "function": {
"name": "get_current_weather", "name": "get_current_weather",
"description": "Get the current weather", "description": "Get the current weather",
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": { "properties": {
"location": { "location": {
"type": "string", "type": "string",
"description": "The city and state, e.g. San Francisco, CA", "description": "The city and state, e.g. San Francisco, CA",
}, },
"format": { "format": {
"type": "string", "type": "string",
"enum": ["celsius", "fahrenheit"], "enum": ["celsius", "fahrenheit"],
"description": "The temperature unit to use. Infer this " "description": "The temperature unit to use. Infer this "
" from the users location.", " from the users location.",
}, },
}, },
"required": ["location", "format"], "required": ["location", "format"],
}, },
}, },
}, },
) )
example_config = { example_config = {
"name": "get_weather", "name": "get_weather",
"utterances": [ "utterances": [
"What is the weather like in SF?", "What is the weather like in SF?",
"What is the weather in Cyprus?", "What is the weather in Cyprus?",
"weather in London?", "weather in London?",
"Tell me the weather in New York", "Tell me the weather in New York",
"what is the current weather in Paris?", "what is the current weather in Paris?",
], ],
} }
prompt = f""" prompt = f"""
Given the following specification, generate a config in a valid JSON format, Given the following specification, generate a config in a valid JSON format
enclosed in double quotes,
Example: Example:
SPECIFICATION: SPECIFICATION:
{example_specification} {example_specification}
CONFIG: CONFIG:
{example_config} {example_config}
GIVEN SPECIFICATION: GIVEN SPECIFICATION:
{specification} {specification}
GENERATED CONFIG: GENERATED CONFIG:
""" """
ai_message = llm_openai(prompt)
try: try:
response = openai.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": f"{prompt}"},
],
)
ai_message = response.choices[0].message.content
print("AI message:", ai_message)
route_config = json.loads(ai_message) route_config = json.loads(ai_message)
function_description = specification["function"]["description"]
route_config["utterances"].append(function_description)
logger.info(f"Generated config: {route_config}")
return route_config return route_config
except json.JSONDecodeError as json_error:
raise Exception("JSON parsing error", json_error)
```
%% Cell type:code id: tags:
``` python
def extract_parameters(query: str, specification: dict) -> dict:
logger.info("Extracting parameters...")
example_query = "what is the weather in London?"
example_specification = {
"type": "function",
"function": {
"name": "get_time",
"description": "Get the current time",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Example of city and state",
},
},
"required": ["location"],
},
},
}
example_parameters = {
"location": "London",
}
prompt = f"""
Given the following specification and query, extract the parameters from the query,
in a valid JSON format enclosed in double quotes.
Example:
SPECIFICATION:
{example_specification}
QUERY:
{example_query}
PARAMETERS:
{example_parameters}
GIVEN SPECIFICATION:
{specification}
GIVEN QUERY:
{query}
EXTRACTED PARAMETERS:
"""
ai_message = llm_openai(prompt)
try:
parameters = json.loads(ai_message)
logger.info(f"Extracted parameters: {parameters}")
return parameters
except json.JSONDecodeError as json_error: except json.JSONDecodeError as json_error:
raise Exception("JSON parsing error", json_error) raise Exception("JSON parsing error", json_error)
except Exception as e:
raise Exception("Error generating config from Openai", e)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from semantic_router.schema import Route from semantic_router.schema import Route
from semantic_router.encoders import CohereEncoder from semantic_router.encoders import CohereEncoder
from semantic_router.layer import RouteLayer from semantic_router.layer import RouteLayer
from semantic_router.utils.logger import logger
def get_route_layer(config: list[dict]) -> RouteLayer: def get_route_layer(config: list[dict]) -> RouteLayer:
print("Getting route layer...") logger.info("Getting route layer...")
encoder = CohereEncoder() encoder = CohereEncoder()
routes = [ routes = [
Route(name=route["name"], utterances=route["utterances"]) for route in config Route(name=route["name"], utterances=route["utterances"]) for route in config
] ]
return RouteLayer(encoder=encoder, routes=routes) return RouteLayer(encoder=encoder, routes=routes)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def validate_parameters(function_parameters, specification):
required_params = specification["function"]["parameters"]["required"]
missing_params = [
param for param in required_params if param not in function_parameters
]
if missing_params:
raise ValueError(f"Missing required parameters: {missing_params}")
return True
```
%% Cell type:code id: tags:
``` python
def get_time(location: str) -> str:
print(f"Calling get_time function with location: {location}")
return "get_time"
specification = { specification = {
"type": "function", "type": "function",
"function": { "function": {
"name": "get_time", "name": "get_time",
"description": "Get the current time", "description": "Get the current time",
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": { "properties": {
"location": { "location": {
"type": "string", "type": "string",
"description": "The city and state", "description": "The city and state",
}, },
}, },
"required": ["location"], "required": ["location"],
}, },
}, },
} }
route_config = generate_config(specification) route_config = generate_config(specification)
route_layer = get_route_layer([route_config]) route_layer = get_route_layer([route_config])
queries = [ queries = [
"What is the weather like in Barcelona?", "What is the weather like in Barcelona?",
"What time is it in Taiwan?", "What time is it in Taiwan?",
"What is happening in the world?", "What is happening in the world?",
"what is the time in Kaunas?", "what is the time in Kaunas?",
"Im bored", "Im bored",
"I want to play a game", "I want to play a game",
"Banana", "Banana",
] ]
print("Getting function name for queries:\n") print("Getting function name for queries:\n")
for query in queries: for query in queries:
function_name = route_layer(query) function_name = route_layer(query)
print((function_name, query))
function_parameters = {}
if function_name:
function_parameters = extract_parameters(query, specification)
print(query, function_name, function_parameters)
if function_name == "get_time":
try:
if validate_parameters(function_parameters, specification):
get_time(**function_parameters)
except ValueError as e:
logger.error(f"Error: {e}")
``` ```
%% Output %% Output
Generating config... 2023-12-14 13:16:49 INFO semantic_router.utils.logger Generating config...
AI message: { 2023-12-14 13:16:54 INFO semantic_router.utils.logger AI message: {"name": "get_time", "utterances": ["What is the current time in London?", "Tell me the time in New York", "What's happening now in Paris?", "time in San Francisco?", "Tell me the time in Sydney"]}
"name": "get_time", 2023-12-14 13:16:54 INFO semantic_router.utils.logger Generated config: {'name': 'get_time', 'utterances': ['What is the current time in London?', 'Tell me the time in New York', "What's happening now in Paris?", 'time in San Francisco?', 'Tell me the time in Sydney', 'Get the current time']}
"utterances": [ 2023-12-14 13:16:54 INFO semantic_router.utils.logger Getting route layer...
"What is the current time in SF?",
"Tell me the time in London",
"Could you tell me the time in New York?",
"May I know the current time in Paris?",
"Can you tell me what time is it in Singapore?"
]
}
Getting route layer...
Getting function name for queries: Getting function name for queries:
(None, 'What is the weather like in Barcelona?') What is the weather like in Barcelona? None {}
('get_time', 'What time is it in Taiwan?')
(None, 'What is happening in the world?') 2023-12-14 13:16:55 INFO semantic_router.utils.logger Extracting parameters...
('get_time', 'what is the time in Kaunas?') 2023-12-14 13:16:56 INFO semantic_router.utils.logger AI message: {"location": "Taiwan"}
(None, 'Im bored') 2023-12-14 13:16:56 INFO semantic_router.utils.logger Extracted parameters: {'location': 'Taiwan'}
(None, 'I want to play a game')
(None, 'Banana') What time is it in Taiwan? get_time {'location': 'Taiwan'}
Calling get_time function with location: Taiwan
2023-12-14 13:16:56 INFO semantic_router.utils.logger Extracting parameters...
2023-12-14 13:16:58 INFO semantic_router.utils.logger AI message: {"location": "the world"}
2023-12-14 13:16:58 INFO semantic_router.utils.logger Extracted parameters: {'location': 'the world'}
What is happening in the world? get_time {'location': 'the world'}
Calling get_time function with location: the world
2023-12-14 13:16:58 INFO semantic_router.utils.logger Extracting parameters...
2023-12-14 13:17:00 INFO semantic_router.utils.logger AI message: {"location": "Kaunas"}
2023-12-14 13:17:00 INFO semantic_router.utils.logger Extracted parameters: {'location': 'Kaunas'}
what is the time in Kaunas? get_time {'location': 'Kaunas'}
Calling get_time function with location: Kaunas
Im bored None {}
I want to play a game None {}
Banana None {}
%% Cell type:code id: tags:
``` python
```
......
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