avatarAnkush k Singal

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5822

Abstract

ss_inquiry"</span>, utterances=[ <span class="hljs-string">"how much is an hour training session?"</span>, <span class="hljs-string">"do you do package discounts?"</span>, ], )

product_route = Route( name=<span class="hljs-string">"product"</span>, utterances=[ <span class="hljs-string">"do you have a website?"</span>, <span class="hljs-string">"how can I find more info about your services?"</span>, <span class="hljs-string">"where do I sign up?"</span>, <span class="hljs-string">"how do I get hench?"</span>, <span class="hljs-string">"do you have recommended training programmes?"</span>, ], )

routes = [time_route, supplement_route, business_route, product_route]</pre></div><p id="3be5">Step III: Initialize OpenAI and Import Libraries</p><div id="e316"><pre><span class="hljs-keyword">import</span> os <span class="hljs-keyword">from</span> getpass <span class="hljs-keyword">import</span> getpass

<span class="hljs-comment"># platform.openai.com</span> os.environ[<span class="hljs-string">"OPENAI_API_KEY"</span>] = os.getenv(<span class="hljs-string">"OPENAI_API_KEY"</span>) <span class="hljs-keyword">or</span> getpass( <span class="hljs-string">"Enter OpenAI API Key: "</span> )

<span class="hljs-comment">#Import Libraries</span> <span class="hljs-keyword">from</span> semantic_router <span class="hljs-keyword">import</span> RouteLayer <span class="hljs-keyword">from</span> semantic_router.encoders <span class="hljs-keyword">import</span> OpenAIEncoder

rl = RouteLayer(encoder=OpenAIEncoder(), routes=routes)

rl(<span class="hljs-string">"should I buy ON whey or MP?"</span>)

<span class="hljs-comment">#Output</span> RouteChoice(name=<span class="hljs-string">'supplement_brand'</span>, function_call=<span class="hljs-literal">None</span>)</pre></div><p id="8eb0"><b>Step IV: Link Routes to particular actions or information</b></p><div id="7676"><pre><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime

<span class="hljs-keyword">def</span> <span class="hljs-title function_">get_time</span>(): now = datetime.now() <span class="hljs-keyword">return</span> ( <span class="hljs-string">f"The current time is <span class="hljs-subst">{now.strftime(<span class="hljs-string">'%H:%M'</span>)}</span>, use "</span> <span class="hljs-string">"this information in your response"</span> )

<span class="hljs-keyword">def</span> <span class="hljs-title function_">supplement_brand</span>(): <span class="hljs-keyword">return</span> ( <span class="hljs-string">"Remember you are not affiliated with any supplement "</span> <span class="hljs-string">"brands, you have your own brand 'BigAI' that sells "</span> <span class="hljs-string">"the best products like P100 whey protein"</span> )

<span class="hljs-keyword">def</span> <span class="hljs-title function_">business_inquiry</span>(): <span class="hljs-keyword">return</span> ( <span class="hljs-string">"Your training company, 'BigAI PT', provides premium "</span> <span class="hljs-string">"quality training sessions at just $700 / hour. "</span> <span class="hljs-string">"Users can find out more at www.aurelio.ai/train"</span> )

<span class="hljs-keyword">def</span> <span class="hljs-title function_">product</span>(): <span class="hljs-keyword">return</span> ( <span class="hljs-string">"Remember, users can sign up for a fitness programme "</span> <span class="hljs-string">"at www.aurelio.ai/sign-up"</span> )

<span class="hljs-keyword">def</span> <span class="hljs-title function_">semantic_layer</span>(<span class="hljs-params">query: <span class="hljs-built_in">str</span></span>): route = rl(query) <span class="hljs-keyword">if</span> route.name == <span class="hljs-string">"get_time"</span>: query += <span class="hljs-string">f" (SYSTEM NOTE: <span class="hljs-subst">{get_time()}</span>)"</span> <span class="hljs-keyword">elif</span> route.name == <span class="hljs-string">"supplement_brand"</span>: query += <span class="hljs-string">f" (SYSTEM NOTE: <span class="hljs-subst">{supplement_brand()}</span>)"</span> <span class="hljs-keyword">elif</span> route.name == <span class="hljs-string">"business_inquiry"</span>: query += <span class="hljs-string">f" (SYSTEM NOTE: <span class="hljs-subst">{business_inquiry()}</span>)"</span> <span class="hljs-keyword">elif</span> route.name == <span class="hljs-string">"product"</span>: query += <span class="hljs-string">f" (SYSTEM NOTE: <span class="hljs-subst">{product()}</span>)"</span> <span class="hljs-keyword">else</span>: <span class="hljs-keyword">pass</span> <span class="hljs-keyword">return</span> query

query = <span class="hljs-string">"should I buy ON whey or MP?"</span> sr_query = semantic_layer(query) sr_query

<span class="hljs-comment">#Output</span> should I buy ON whey <span class="hljs-keyword">or</span> MP? (SYSTEM NOTE: Remember you are <span class="hljs-keyword">not</span> affiliated <span class="hljs-keyword">with</span> <span class="hljs-built_in">any</span> supplement brands, you have your own brand <span class="hljs-string">'BigAI'</span> that sells the best products like P100 whey protein)</pre></div><p id="982a"><b>Step V: Using Langchain Agent with a Router Layer</b></p><div id="b777"><pre><span class="hljs-keyword">from</span> langchain.agents <span class="hljs-keyword">import</span> AgentType, initialize_agent <span class="hljs-keyword">from</span> langchain.chat_models <span class="hljs-keyword">import</span> ChatOpenAI <span class="hljs-keyword">from</span> langchain.memory <span class="hljs-keyword">import

Options

</span> ConversationBufferWindowMemory

llm = ChatOpenAI(model=<span class="hljs-string">"gpt-3.5-turbo-1106"</span>)

memory1 = ConversationBufferWindowMemory( memory_key=<span class="hljs-string">"chat_history"</span>, k=<span class="hljs-number">5</span>, return_messages=<span class="hljs-literal">True</span>, output_key=<span class="hljs-string">"output"</span> ) memory2 = ConversationBufferWindowMemory( memory_key=<span class="hljs-string">"chat_history"</span>, k=<span class="hljs-number">5</span>, return_messages=<span class="hljs-literal">True</span>, output_key=<span class="hljs-string">"output"</span> )

agent = initialize_agent( agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, tools=[], llm=llm, max_iterations=<span class="hljs-number">3</span>, early_stopping_method=<span class="hljs-string">"generate"</span>, memory=memory1, )

<span class="hljs-comment"># update the system prompt</span> system_message = <span class="hljs-string">"""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."""</span>

new_prompt = agent.agent.create_prompt(system_message=system_message, tools=[]) agent.agent.llm_chain.prompt = new_prompt

agent(query)

<span class="hljs-comment">#Output</span> {<span class="hljs-string">'input'</span>: <span class="hljs-string">'should I buy ON whey or MP?'</span>, <span class="hljs-string">'chat_history'</span>: [], <span class="hljs-string">'output'</span>: <span class="hljs-string">'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.'</span>}</pre></div><div id="a0ec"><pre><span class="hljs-comment"># swap agent memory first</span> agent.memory = memory2 agent(sr_query)

<span class="hljs-comment">#Output</span> {<span class="hljs-string">'input'</span>: <span class="hljs-string">"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)"</span>, <span class="hljs-string">'chat_history'</span>: [], <span class="hljs-string">'output'</span>: <span class="hljs-string">"Why not try the BigAI P100 whey protein? It's the best, just like me."</span>} Adding this reminder allows us to get much more intentional responses — <span class="hljs-keyword">while</span> also unintentionally improving the LLMs following of our original instructions to act <span class="hljs-keyword">as</span> a British gentleman.</pre></div><h2 id="6bcc">Conclusion</h2><p id="029c">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.</p><p id="7e60">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.</p><h2 id="81d3">Resources</h2><ul><li><a href="https://github.com/aurelio-labs/semantic-router/tree/main">Semantic-Router</a></li><li><a href="https://www.linkedin.com/posts/tonyseale_semanticlayer-dataengineering-semanticweb-activity-7027198852701003777-Lby3/">Semantic-Web</a></li><li><a href="https://github.com/JudiniLabs/cookbook/blob/main/API/codegpt_with_semantic_router/app.py">CodeGPT-Semantic-Router</a></li><li><a href="https://github.com/aurelio-labs/semantic-router/blob/main/docs/05-local-execution.ipynb">Semantic Router with Llama.cpp</a></li></ul><p id="a2ed">Stay connected and support my work through various platforms:</p><p id="f2ac"><a href="https://github.com/andysingal">Github</a> <a href="https://www.patreon.com/AndyShanu">Patreon</a> <a href="https://www.kaggle.com/alphasingal">Kaggle</a> <a href="https://huggingface.co/Andyrasika">Hugging-Face</a> <a href="https://www.youtube.com/@andy111007">YouTube</a> <a href="https://rasikasingal.gumroad.com/">GumRoad</a></p><p id="9385">Like my content? Feel free to <a href="https://paypal.me/alphasingal?country.x=US&amp;locale.x=en_US">Buy Me a Coffee ☕</a> !</p><p id="5530">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.</p><p id="3ff1">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!</p><p id="360f">If you enjoyed this story, feel free <a href="https://medium.com/@andysingal">to subscribe</a> 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.</p></article></body>

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

Ankush k Singal

Source: Image created by Author using MidJourney

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.

Source: Semantic-Router

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.

Source: LLM-Semantic-Router

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.

  1. 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.1

Step 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.

Technology
Tech
Software Development
Artificial Intelligence
Langchain
Recommended from ReadMedium