語義路由器是您的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熱線