语义路由器是您的LLM和代理商的超快速决策层。我们没有等待LLM几代做出工具使用决策,而是使用语义向量空间的魔术来做出这些决定,而是使用语义含义来路由我们的请求。
为了开始使用语义 - 路由器,我们会这样安装:
pip install -qU semantic-router
❗️如果想使用完全本地版本的语义路由器,则可以使用HuggingFaceEncoder和LlamaCppLLM ( pip install -qU "semantic-router[local]" ,请参见此处)。要使用HybridRouteLayer您必须pip install -qU "semantic-router[hybrid]" 。
我们首先定义一组Route对象。这些是语义路由器可以决定使用的决策途径,让我们现在尝试两条简单的路线 - 一种用于政治的讨论,另一个用于Chitchat :
from semantic_router import Route
# we could use this as a guide for our chatbot to avoid political conversations
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" ,
"they're going to destroy this country!" ,
"they will save the country!" ,
],
)
# this could be used as an indicator to our chatbot to switch to a more
# conversational prompt
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" ,
],
)
# we place both of our decisions together into single list
routes = [ politics , chitchat ]我们已经准备好路线了,现在我们初始化了嵌入式 /编码器模型。目前,我们支持CohereEncoder和OpenAIEncoder - 将很快添加更多的编码器。为了初始化它们,我们会这样做:
import os
from semantic_router . encoders import CohereEncoder , OpenAIEncoder
# for Cohere
os . environ [ "COHERE_API_KEY" ] = "<YOUR_API_KEY>"
encoder = CohereEncoder ()
# or for OpenAI
os . environ [ "OPENAI_API_KEY" ] = "<YOUR_API_KEY>"
encoder = OpenAIEncoder ()通过定义了我们的routes和encoder我们现在创建一个RouteLayer 。路线层处理我们的语义决策。
from semantic_router . layer import RouteLayer
rl = RouteLayer ( encoder = encoder , routes = routes )现在,我们可以使用路线层根据用户查询做出超快速决策。让我们尝试两个应该触发我们路线决策的查询:
rl ( "don't you love politics?" ). name [Out]: 'politics'
正确的决定,让我们尝试一下:
rl ( "how's the weather today?" ). name [Out]: 'chitchat'
我们将两个决定都正确!现在让我们尝试发送无关的查询:
rl ( "I'm interested in learning about llama 2" ). name [Out]:
在这种情况下,由于我们没有比赛,因此无法做出任何决定 - 因此我们的路线层None返回!
语义路由器的编码器包括与Cohere,Openai,Hugging Face,Fastempembed等的易于使用的集成 - 我们甚至支持多模式!
我们的话语矢量空间也与Pinecone和Qdrant集成了!
| 笔记本 | 描述 |
|---|---|
| 介绍 | 语义路由器和静态路线简介 |
| 动态路线 | 参数生成和函数调用的动态路线 |
| 保存/加载层 | 如何从文件中保存和加载RouteLayer |
| Langchain集成 | 如何将语义路由器与Langchain代理集成 |
| 本地执行 | 具有动态路线的完全本地语义路由器 -在大多数测试中,诸如Mistral 7b之类的本地模型都优于GPT-3.5 |
| 路线优化 | 如何训练路线层阈值以优化性能 |
| 多模式路线 | 使用多模式路线来识别史莱克与非赫里克图片 |

ollama / gemma2:9b热线