I have a list of sentences that represent orders for an assistant, such as "turn off the kitchen light", each associated with an order in a machine understandable format (in this example, {"action":"light", "value":"off", "target": "kitchen"}. I will receive text inputs in natural language and I want to find the closest of the orders. Can I use an embedding model to do that?
Assistant
User
Good, but now try to add a layer of complexity. The list of orders should be things like "The user wants to turn on the light". Then there should be a second list, places, with things like "The user is speaking about the kitchen".
Assistant
User
Let's make it even more complex. The user may be speaking about more than one place, like "turn on the light in the kitchen and the living room" or "turn on all the lights", so the result for the places should be a list.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Yes, you can use an embedding model to find the closest order to a given natural language input. The ollama-python library provides an embed function that can generate embeddings for text, which you can then use to compute similarity.
Here's how you can achieve this:
Generate Embeddings for Known Orders: Use the embed function to generate embeddings for each of your known order sentences. Store these embeddings along with their corresponding machine-readable orders.
Generate Embedding for Input Text: When you receive a new natural language input, use the embed function to generate its embedding.
Compute Similarity: Calculate the similarity between the input text's embedding and the embeddings of your known orders. [Redacted Person] similarity is a common metric for this.
Find Closest Order: Select the known order with the highest similarity to the input text. This will be your closest match.
Here's an example using the provided ollama-python library, including calculating the cosine similarity:
python
import numpy as np
from ollama import embed
def cosine_similarity(a, b):
"""Compute cosine similarity between two vectors."""
a = np.array(a)
b = np.array(b)
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def find_closest_order(input_text, known_orders):
"""
Finds the closest order to the input text using embeddings.
Args:
input_text: The natural language input string.
known_orders: A list of tuples, where each tuple contains:
- A natural language order string
- A corresponding machine-readable order dict
Returns:
A tuple:
- The machine readable order dictionary with the closest match
- The similarity score
"""
input_embedding = embed(model='llama3.2', input=input_text).embeddings
closest_order = None
max_similarity = -1
for order_text, order_dict in known_orders:
order_embedding = embed(model='llama3.2', input=order_text).embeddings
similarity = cosine_similarity(input_embedding, order_embedding)
if similarity > max_similarity:
max_similarity = similarity
closest_order = order_dict
return closest_order, max_similarity
# Example usage
known_orders = [
("turn off the kitchen light", {"action":"light", "value":"off", "target": "kitchen"}),
("turn on the living room tv", {"action":"tv", "value":"on", "target": "living room"}),
("set the bedroom temperature to 20", {"action": "temperature", "value": "20", "target": "bedroom"}),
("increase volume in the study", {"action":"volume", "value":"increase", "target": "study"})
]
input_text = "switch the kitchen light off"
closest_order, similarity_score = find_closest_order(input_text, known_orders)
print(f"Input text: {input_text}")
print(f"Closest order: {closest_order}")
print(f"Similarity score: {similarity_score}")
input_text = "make the living room tv louder"
closest_order, similarity_score = find_closest_order(input_text, known_orders)
print(f"Input text: {input_text}")
print(f"Closest order: {closest_order}")
print(f"Similarity score: {similarity_score}")
Explanation:
The code defines a cosine_similarity function to compute the cosine similarity between two embeddings.
The find_closest_order function takes the input text and a list of known orders.
It generates embeddings for the input text and each known order.
It calculates the cosine similarity between the input text's embedding and each known order's embedding.
It returns the machine-readable order that corresponds to the highest similarity score.
Key points:
You'll need to install the numpy package (pip install numpy).
Ensure you have a suitable model pulled with ollama pull <model_name>, such as llama3.2 used in the example.
The embed function returns a dictionary with the embeddings field which is a list of floats representing the embedding.
The accuracy of this approach depends on the quality of your embedding model and the diversity of your known orders.
This example computes the cosine similarity, but you can explore other similarity metrics if needed.
This approach allows you to map natural language input to structured actions for your assistant.
Okay, let's incorporate that additional layer of complexity by having separate lists for "orders" (intent) and "places" (context). This will allow the model to understand both the action the user wants to perform and the location they're referring to, which is often needed in real world scenarios.
Here's how we can modify the code:
Separate Lists: Create two lists: one for "orders" (intent) and one for "places" (context). Each item in the list will have associated machine-readable data.
Embed Separately: Generate embeddings for each order and each place separately.
Combine Embeddings: For the input text, generate its embedding. Then, compute the similarity of the input embedding with both the order embeddings and place embeddings. Select the best matching order and place based on similarity. You can optionally weight the two similarity scores.
Return Combined Order: Construct the final order based on the best matching intent and context.
Here's the modified code:
python
import numpy as np
from ollama import embed
def cosine_similarity(a, b):
"""Compute cosine similarity between two vectors."""
a = np.array(a)
b = np.array(b)
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def find_closest_combined_order(input_text, known_orders, known_places, order_weight=0.6, place_weight=0.4):
"""
Finds the closest combined order (intent + context) to the input text using embeddings.
Args:
input_text: The natural language input string.
known_orders: A list of tuples, where each tuple contains:
- A natural language order string
- A corresponding machine-readable order dict
known_places: A list of tuples, where each tuple contains:
- A natural language place string
- A corresponding machine-readable place dict
order_weight: The weight to give to the order similarity. Default 0.6.
place_weight: The weight to give to the place similarity. Default 0.4.
Returns:
A tuple:
- The machine readable order dictionary with the closest match
- The similarity score
"""
input_embedding = embed(model='llama3.2', input=input_text).embeddings
best_order = None
max_order_similarity = -1
for order_text, order_dict in known_orders:
order_embedding = embed(model='llama3.2', input=order_text).embeddings
similarity = cosine_similarity(input_embedding, order_embedding)
if similarity > max_order_similarity:
max_order_similarity = similarity
best_order = order_dict
best_place = None
max_place_similarity = -1
for place_text, place_dict in known_places:
place_embedding = embed(model='llama3.2', input=place_text).embeddings
similarity = cosine_similarity(input_embedding, place_embedding)
if similarity > max_place_similarity:
max_place_similarity = similarity
best_place = place_dict
combined_similarity = (max_order_similarity * order_weight) + (max_place_similarity * place_weight)
return {**best_order, **best_place}, combined_similarity
# Example usage
known_orders = [
("The user wants to turn on the light", {"action":"light", "value":"on"}),
("The user wants to turn off the light", {"action":"light", "value":"off"}),
("The user wants to increase the temperature", {"action":"temperature", "value":"increase"}),
("The user wants to decrease the volume", {"action":"volume", "value":"decrease"})
]
known_places = [
("The user is speaking about the kitchen", {"target": "kitchen"}),
("The user is speaking about the living room", {"target": "living room"}),
("The user is speaking about the bedroom", {"target": "bedroom"}),
("The user is speaking about the study", {"target": "study"})
]
input_text = "turn the light off in the kitchen"
closest_order, similarity_score = find_closest_combined_order(input_text, known_orders, known_places)
print(f"Input text: {input_text}")
print(f"Closest order: {closest_order}")
print(f"Similarity score: {similarity_score}")
input_text = "make the living room louder"
closest_order, similarity_score = find_closest_combined_order(input_text, known_orders, known_places)
print(f"Input text: {input_text}")
print(f"Closest order: {closest_order}")
print(f"Similarity score: {similarity_score}")
Explanation:
We now have known_orders and known_places lists, each with a natural language description and a corresponding dictionary.
The find_closest_combined_order function calculates the similarities of the input to known orders and known places.
It then combines the results to produce a structured output with both intent (action and value) and context (target).
order_weight and place_weight are used to weigh the two similarities to help in producing a final result.
Key points:
The combined output includes both the "order" and the "place" information.
The weights allow you to prioritize either the order or the place depending on your needs. You might need to tune these weights based on your application requirements.
You could also explore more sophisticated ways of combining the embedding vectors, or using a separate model to combine them.
This revised approach allows you to handle more complex scenarios where both the intent and context of the user's input need to be understood.
Okay, let's tackle the challenge of handling multiple places in the user's input, and returning a list of places. This will require a more flexible approach to place detection and merging the information.
Here's how we can modify the code to handle multiple places:
Place Matching: Instead of picking just one best matching place, we'll find all places that have a similarity score above a certain threshold.
Combine Places: Collect the machine readable representation of all matched places, and ensure they are returned as a list.
Handle edge case: If the user asks for "all the lights", we need to avoid matching a specific place. We will add a special place for this.
Here's the modified code:
python
import numpy as np
from ollama import embed
def cosine_similarity(a, b):
"""Compute cosine similarity between two vectors."""
a = np.array(a)
b = np.array(b)
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
def find_closest_combined_order(input_text, known_orders, known_places, order_weight=0.6, place_weight=0.4, place_threshold=0.5):
"""
Finds the closest combined order (intent + context) to the input text using embeddings,
handling multiple places and a threshold for place matches.
Args:
input_text: The natural language input string.
known_orders: A list of tuples, where each tuple contains:
- A natural language order string
- A corresponding machine-readable order dict
known_places: A list of tuples, where each tuple contains:
- A natural language place string
- A corresponding machine-readable place dict
order_weight: The weight to give to the order similarity. Default 0.6.
place_weight: The weight to give to the place similarity. Default 0.4.
place_threshold: The minimum cosine similarity for a place to be considered a match.
Returns:
A tuple:
- The machine readable order dictionary with the closest match
- The similarity score
"""
input_embedding = embed(model='llama3.2', input=input_text).embeddings
best_order = None
max_order_similarity = -1
for order_text, order_dict in known_orders:
order_embedding = embed(model='llama3.2', input=order_text).embeddings
similarity = cosine_similarity(input_embedding, order_embedding)
if similarity > max_order_similarity:
max_order_similarity = similarity
best_order = order_dict
matched_places = []
for place_text, place_dict in known_places:
place_embedding = embed(model='llama3.2', input=place_text).embeddings
similarity = cosine_similarity(input_embedding, place_embedding)
if similarity > place_threshold:
matched_places.append(place_dict)
combined_similarity = (max_order_similarity * order_weight)
if matched_places:
combined_similarity += (sum([similarity for place_text, place_dict in known_places
if cosine_similarity(input_embedding, embed(model='llama3.2', input=place_text).embeddings)>place_threshold]) * place_weight / len(matched_places) )
return {**best_order, "targets": matched_places if matched_places else []}, combined_similarity
# Example usage
known_orders = [
("The user wants to turn on the light", {"action":"light", "value":"on"}),
("The user wants to turn off the light", {"action":"light", "value":"off"}),
("The user wants to increase the temperature", {"action":"temperature", "value":"increase"}),
("The user wants to decrease the volume", {"action":"volume", "value":"decrease"})
]
known_places = [
("The user is speaking about the kitchen", {"target": "kitchen"}),
("The user is speaking about the living room", {"target": "living room"}),
("The user is speaking about the bedroom", {"target": "bedroom"}),
("The user is speaking about the study", {"target": "study"}),
("The user is speaking about all the places", {"target": "all"})
]
input_text = "turn the light off in the kitchen and the living room"
closest_order, similarity_score = find_closest_combined_order(input_text, known_orders, known_places)
print(f"Input text: {input_text}")
print(f"Closest order: {closest_order}")
print(f"Similarity score: {similarity_score}")
input_text = "turn on all the lights"
closest_order, similarity_score = find_closest_combined_order(input_text, known_orders, known_places)
print(f"Input text: {input_text}")
print(f"Closest order: {closest_order}")
print(f"Similarity score: {similarity_score}")
input_text = "make the bedroom louder"
closest_order, similarity_score = find_closest_combined_order(input_text, known_orders, known_places)
print(f"Input text: {input_text}")
print(f"Closest order: {closest_order}")
print(f"Similarity score: {similarity_score}")
Explanation:
The find_closest_combined_order now has a place_threshold argument, to control which places are selected.
Instead of picking the best place, it collects all places with similarity scores above this threshold into the matched_places list.
The final result has a targets key, which is a list of the places or an empty list if no place is matched.
The combined_similarity score is now adjusted. If there are matched places, it averages the similarity score for these, and uses that weighted by the place_weight.
Key points:
The place_threshold allows you to control how sensitive the place matching is. You might need to adjust it based on your dataset and requirements.
The "all" place has been added.
The code now correctly handles cases with one or more places.
This is still a simplification; you could add more logic to handle cases where places are mentioned implicitly or with more complex wording (e.g. "the room next to the kitchen").
This updated code offers a more robust solution for extracting structured information from natural language, including the ability to identify multiple places and a special case for "all".