#!/usr/bin/env python # coding: utf-8 # [![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/01-save-load-from-file.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/01-save-load-from-file.ipynb) # # Route Layers from File # # Here we will show how to save routers to YAML or JSON files, and how to load a route layer from file. # ## Getting Started # We start by installing the library: # In[ ]: get_ipython().system('pip install -qU "semantic-router>=0.1.3"') # ## Define Route # First let's create a list of routes: # In[1]: 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] # We define a route layer using these routes and using the Cohere encoder. # In[4]: import os from getpass import getpass from semantic_router.encoders import CohereEncoder from semantic_router.routers import SemanticRouter # dashboard.cohere.ai os.environ["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY") or getpass( "Enter Cohere API Key: " ) encoder = CohereEncoder() rl = SemanticRouter(encoder=encoder, routes=routes, auto_sync="local") # ## Test Route # In[5]: rl("isn't politics the best thing ever") # In[6]: rl("how's the weather today?") # ## Save To JSON # To save our route layer we call the `to_json` method: # In[7]: rl.to_json("layer.json") # ## Loading from JSON # We can view the router file we just saved to see what information is stored. # In[8]: import json with open("layer.json", "r") as f: layer_json = json.load(f) print(layer_json) # It tells us our encoder type, encoder name, and routes. This is everything we need to initialize a new router. To do so, we use the `from_json` method. # In[9]: rl = SemanticRouter.from_json("layer.json") # We can confirm that our layer has been initialized with the expected attributes by viewing the `RouteLayer` object: # In[10]: print( f"""{rl.encoder.type=} {rl.encoder.name=} {rl.routes=}""" ) # In[15]: new_rl = SemanticRouter(encoder=rl.encoder, routes=rl.routes, auto_sync="local") # --- # ## Test Route Again # In[13]: new_rl("isn't politics the best thing ever") # In[14]: new_rl("how's the weather today?")