Spaces:
Sleeping
Sleeping
Update scripts/router_chain.py
Browse files- scripts/router_chain.py +32 -33
scripts/router_chain.py
CHANGED
|
@@ -1,33 +1,32 @@
|
|
| 1 |
-
|
| 2 |
-
from
|
| 3 |
-
from langchain.
|
| 4 |
-
from
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
text
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
result
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
return Router()
|
|
|
|
| 1 |
+
from typing import Dict, Any
|
| 2 |
+
from langchain.chat_models import ChatOpenAI
|
| 3 |
+
from langchain.prompts import ChatPromptTemplate
|
| 4 |
+
from scripts.rag_chat import build_general_qa_chain
|
| 5 |
+
|
| 6 |
+
def build_router_chain(model_name=None):
|
| 7 |
+
general_qa = build_general_qa_chain(model_name=model_name)
|
| 8 |
+
llm = ChatOpenAI(model_name=model_name or "gpt-4o-mini", temperature=0.0)
|
| 9 |
+
|
| 10 |
+
class Router:
|
| 11 |
+
def invoke(self, input_dict: Dict[str, Any]):
|
| 12 |
+
text = input_dict.get("input", "").lower()
|
| 13 |
+
if "code" in text or "program" in text or "debug" in text:
|
| 14 |
+
prompt = ChatPromptTemplate.from_template(
|
| 15 |
+
"As a coding assistant, help with this Python question.\nQuestion: {input}\nAnswer:"
|
| 16 |
+
)
|
| 17 |
+
chain = prompt | llm
|
| 18 |
+
return {"result": chain.invoke({"input": input_dict["input"]}).content}
|
| 19 |
+
elif "summarize" in text or "summary" in text:
|
| 20 |
+
prompt = ChatPromptTemplate.from_template(
|
| 21 |
+
"Provide a concise summary about: {input}\nSummary:"
|
| 22 |
+
)
|
| 23 |
+
chain = prompt | llm
|
| 24 |
+
return {"result": chain.invoke({"input": input_dict["input"]}).content}
|
| 25 |
+
elif "calculate" in text or any(char.isdigit() for char in text):
|
| 26 |
+
return {"result": "For calculations, please ask a specific calculation or provide more context."}
|
| 27 |
+
else:
|
| 28 |
+
# Use RAG chain
|
| 29 |
+
result = general_qa({"query": input_dict["input"]})
|
| 30 |
+
return result
|
| 31 |
+
|
| 32 |
+
return Router()
|
|
|