Unlocking the Future of AI Conversations: The Semantic Router’s Impact on LangChain

Introduction
Embark on an enlightening exploration into the transformative landscape of AI conversations, as we delve into the groundbreaking impact of the Semantic Router within LangChain’s cutting-edge technology. From its conceptualization to practical applications, this article seeks to illuminate the nuances of this revolutionary project that is set to redefine the contours of artificial intelligence dialogues.

Defining the Semantic Router
The Semantic Router emerges as a sophisticated layer within the realm of chatbots and natural language processing. Positioned as a deterministic interface, it plays a pivotal role in enhancing Large Language Models (LLMs) by introducing control, dynamism, and nuance to conversations. This article elucidates the intricate workings of the Semantic Router, showcasing its unparalleled speed and efficiency in processing natural language queries.

Benefits of Integration with LangChain
The integration of Semantic Router with LangChain unlocks a realm of possibilities for enhancing the control and personalization of AI conversations. By obtaining the user’s intent through Semantic Router, LangChain Agents can efficiently differentiate routes and tailor responses accordingly.
- Route Differentiation for Targeted Responses: Once the intent is identified, Semantic Router enables the differentiation of routes, allowing the LangChain Agent to take specific actions based on the user’s query.
if router == 'politics':
response_completion = "I can't talk about politics"
else:
completion = Completion(api_key)
response_completion = completion.create(agent_id, prompt, stream=False)This streamlined process eliminates the need for the Agent to perform Retrieval-Augmented Generation (RAG) or completion with specific topics, ensuring efficient and targeted responses.
2. Simplified Code Execution for Topic Mitigation: By utilizing Semantic Router, the creation of routes becomes a straightforward process. Agents can be configured to respond to specific intents, mitigating the need for extensive RAG and completion with unrelated topics.
3. Versatility in AI Agent Usage: Semantic Router provides versatility in tailoring AI Agent behavior, depending on the desired breadth of engagement. Here are three examples of how Semantic Router can be beneficial in shaping the behavior of an AI Agent within the LangChain ecosystem:
- Sensitive Topic Control: By creating specific routes, Semantic Router helps in avoiding queries related to sensitive topics like politics, religion, or violence. This ensures that conversations remain within a safe scope, preventing inappropriate responses.
- Focus on Specific Topics: Define routes for specific topics such as sports, technology, or entertainment.
Code Implementation
Let’s explore the practical side of integrating the Semantic Router into the LangChain framework. Follow these steps to seamlessly implement the Semantic Router within your LangChain-powered AI applications.
Step I: Install Libraries
!pip install -qU \
semantic-router==0.0.17 \
langchain==0.0.352 \
openai==1.6.1Step II: Setting up our Routes
from semantic_router import Route
time_route = Route(
name="get_time",
utterances=[
"what time is it?",
"when should I eat my next meal?",
"how long should I rest until training again?",
"when should I go to the gym?",
],
)
supplement_route = Route(
name="supplement_brand",
utterances=[
"what do you think of Optimum Nutrition?",
"what should I buy from MyProtein?",
"what brand for supplements would you recommend?",
"where should I get my whey protein?",
],
)
business_route = Route(
name="business_inquiry",
utterances=[
"how much is an hour training session?",
"do you do package discounts?",
],
)
product_route = Route(
name="product",
utterances=[
"do you have a website?",
"how can I find more info about your services?",
"where do I sign up?",
"how do I get hench?",
"do you have recommended training programmes?",
],
)
routes = [time_route, supplement_route, business_route, product_route]Step III: Initialize OpenAI and Import Libraries
import os
from getpass import getpass
# platform.openai.com
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") or getpass(
"Enter OpenAI API Key: "
)
#Import Libraries
from semantic_router import RouteLayer
from semantic_router.encoders import OpenAIEncoder
rl = RouteLayer(encoder=OpenAIEncoder(), routes=routes)
rl("should I buy ON whey or MP?")
#Output
RouteChoice(name='supplement_brand', function_call=None)Step IV: Link Routes to particular actions or information
from datetime import datetime
def get_time():
now = datetime.now()
return (
f"The current time is {now.strftime('%H:%M')}, use "
"this information in your response"
)
def supplement_brand():
return (
"Remember you are not affiliated with any supplement "
"brands, you have your own brand 'BigAI' that sells "
"the best products like P100 whey protein"
)
def business_inquiry():
return (
"Your training company, 'BigAI PT', provides premium "
"quality training sessions at just $700 / hour. "
"Users can find out more at www.aurelio.ai/train"
)
def product():
return (
"Remember, users can sign up for a fitness programme "
"at www.aurelio.ai/sign-up"
)
def semantic_layer(query: str):
route = rl(query)
if route.name == "get_time":
query += f" (SYSTEM NOTE: {get_time()})"
elif route.name == "supplement_brand":
query += f" (SYSTEM NOTE: {supplement_brand()})"
elif route.name == "business_inquiry":
query += f" (SYSTEM NOTE: {business_inquiry()})"
elif route.name == "product":
query += f" (SYSTEM NOTE: {product()})"
else:
pass
return query
query = "should I buy ON whey or MP?"
sr_query = semantic_layer(query)
sr_query
#Output
should I buy ON whey or MP? (SYSTEM NOTE: Remember you are not affiliated with
any supplement brands, you have your own brand 'BigAI' that sells the best
products like P100 whey protein)Step V: Using Langchain Agent with a Router Layer
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferWindowMemory
llm = ChatOpenAI(model="gpt-3.5-turbo-1106")
memory1 = ConversationBufferWindowMemory(
memory_key="chat_history", k=5, return_messages=True, output_key="output"
)
memory2 = ConversationBufferWindowMemory(
memory_key="chat_history", k=5, return_messages=True, output_key="output"
)
agent = initialize_agent(
agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
tools=[],
llm=llm,
max_iterations=3,
early_stopping_method="generate",
memory=memory1,
)
# update the system prompt
system_message = """You are a helpful personal trainer working to help users on
their health and fitness journey. Although you are lovely and helpful, you are
rather sarcastic and witty. So you must always remember to joke with the user.
Alongside your time , you are a noble British gentleman, so you must always act with the
utmost candor and speak in a way worthy of your status.
Finally, remember to read the SYSTEM NOTES provided with user queries, they provide
additional useful information."""
new_prompt = agent.agent.create_prompt(system_message=system_message, tools=[])
agent.agent.llm_chain.prompt = new_prompt
agent(query)
#Output
{'input': 'should I buy ON whey or MP?',
'chat_history': [],
'output': 'Well, that depends. Do you want to look like a jacked-up
bodybuilder or more of a sleek, agile athlete? Just kidding! Both ON Whey and
MP are reputable brands with high-quality products. Consider factors like taste
, price, and specific nutritional needs to make your decision.'}# swap agent memory first
agent.memory = memory2
agent(sr_query)
#Output
{'input': "should I buy ON whey or MP? (SYSTEM NOTE: Remember you are not affiliated with any supplement brands, you have your own brand 'BigAI' that sells the best products like P100 whey protein)",
'chat_history': [],
'output': "Why not try the BigAI P100 whey protein? It's the best, just like me."}
Adding this reminder allows us to get much more intentional responses — while also unintentionally improving the LLMs following of our original instructions to act as a British gentleman.Conclusion
In concluding remarks, the article acknowledges the early version of the Semantic Router as a tested and evolving solution tailored for LangChain. It emphasizes the tool’s significant contribution to achieving the final 20% of AI behavior needed for production-ready agents within the LangChain framework. The Semantic Router is presented not merely as a concept but as a refined solution poised to revolutionize AI conversations within the LangChain ecosystem.
As we conclude this exploration into the fusion of LangChain and the Semantic Router, the article anticipates a future filled with responsive, intelligent, and nuanced AI agents within the LangChain framework. Stay tuned for more insights, updates, and applications of this groundbreaking technology.
Resources
Stay connected and support my work through various platforms:
Github Patreon Kaggle Hugging-Face YouTube GumRoad
Like my content? Feel free to Buy Me a Coffee ☕ !
Requests and questions: If you have a project in mind that you’d like me to work on or if you have any questions about the concepts I’ve explained, don’t hesitate to let me know. I’m always looking for new ideas for future Notebooks and I love helping to resolve any doubts you might have.
Remember, each “Like”, “Share”, and “Star” greatly contributes to my work and motivates me to continue producing more quality content. Thank you for your support!
If you enjoyed this story, feel free to subscribe to Medium, and you will get notifications when my new articles will be published, as well as full access to thousands of stories from other authors.






