ROUTERS IN LLM

news/2024/11/14 22:10:43/文章来源:https://www.cnblogs.com/lightsong/p/18546626

LOGIC ROUTER

使用代码逻辑调用子agent

https://github.com/ganeshnehru/RAG-Multi-Modal-Generative-AI-Agent

import re
import logging
from chains.code_assistant import CodeAssistant
from chains.language_assistant import LanguageAssistant
from chains.vision_assistant import VisionAssistantclass AssistantRouter:def __init__(self):self.code_assistant = CodeAssistant()self.language_assistant = LanguageAssistant()self.vision_assistant = VisionAssistant()def route_input(self, user_input='', image_path=None):"""Route the input to the appropriate assistant based on the content of the user input.:param user_input: str, The input text from the user.:param image_path: str, Path to an image file if provided.:return: tuple, The response from the appropriate assistant and the assistant name."""try:if image_path:# Process image and route to VisionAssistantimage_b64 = self.vision_assistant.process_image(image_path)if image_b64 is None:raise ValueError("Failed to process image.")input_string = f"{user_input}|{image_b64}"response = self.vision_assistant.invoke(input_string)return response, 'VisionAssistant'if self.is_code_related(user_input):response = self.code_assistant.invoke(user_input)return response, 'CodeAssistant'else:response = self.language_assistant.invoke(user_input)return response, 'LanguageAssistant'except Exception as e:logging.error(f"Error in AssistantRouter.route_input: {e}")return {"content": f"Error: {str(e)}"}, 'Error'def is_code_related(self, text):"""Determine if the text input is related to coding.:param text: str, The input text.:return: bool, True if the text is code related, False otherwise."""# Basic keyword-based detectioncode_keywords = ['function', 'class', 'def', 'import', 'print', 'variable','loop', 'array', 'list', 'dictionary', 'exception', 'error', 'bug','code', 'compile', 'execute', 'algorithm', 'data structure', 'java', 'python', 'javascript', 'c++','c#', 'ruby', 'php', 'html', 'css', 'sql', 'swift', 'kotlin', 'go', 'rust', 'typescript', 'r', 'perl','scala', 'shell', 'bash', 'powershell', 'objective-c', 'matlab', 'groovy', 'lua', 'dart', 'cobol','fortran', 'haskell', 'lisp', 'pascal', 'prolog', 'scheme', 'smalltalk', 'verilog', 'vhdl','assembly', 'coffeescript', 'f#', 'julia', 'racket', 'scratch', 'solidity', 'vba', 'abap', 'apex','awk', 'clojure', 'd', 'elixir', 'erlang', 'forth', 'hack', 'idris', 'j', 'julia', 'kdb+', 'labview','logtalk', 'lolcode', 'mumps', 'nim', 'ocaml', 'pl/i', 'postscript', 'powershell', 'rpg', 'sas', 'sml','tcl', 'turing', 'unicon', 'x10', 'xquery', 'zsh']pattern = re.compile(r'\b(?:' + '|'.join(re.escape(word) for word in code_keywords) + r')\b', re.IGNORECASE)return bool(pattern.search(text))

 

LANGCHAIN ROUTER

限定 with_structured_output 输出格式,使得langchain决定哪一个子路可以被调用。

https://github.com/MadhanMohanReddy2301/SmartChainAgents/blob/master/router.py

### Routerfrom typing import Literal
from dotenv import load_dotenvload_dotenv()from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Fieldimport os# Data model
class RouteQuery(BaseModel):"""Route a user query to the most relevant datasource."""datasource: Literal["arxiv_search", "wiki_search", "llm_search"] = Field(...,description="Given a user question choose to route it to wikipedia or arxiv_search or llm_search.",)# LLM with function call
from langchain_groq import ChatGroq
import os
groq_api_key=os.getenv('GROQ_API_KEY')
os.environ["GROQ_API_KEY"]=groq_api_key
llm=ChatGroq(groq_api_key=groq_api_key,model_name="Gemma2-9b-It")
structured_llm_router = llm.with_structured_output(RouteQuery)# Prompt
system = """You are an expert at routing a user question to a arxiv_search or wikipedia or llm_search.
The arxiv_search contains documents related to research papers about ai agents and LLMS.
Use the wikipedia for questions on the human related infomation. Otherwise, use llm_search."""route_prompt = ChatPromptTemplate.from_messages([("system", system),("human", "{question}"),]
)question_router = route_prompt | structured_llm_router
"""print(question_router.invoke({"question": "who is Sharukh Khan?"})
)
print(question_router.invoke({"question": "What are the types of agent memory?"}))"""

 

 

RAG_SemanticRouting

https://github.com/UribeAlejandro/RAG_SemanticRouting/blob/main/src/main.py

 

CSV-chat-and-code-Interpreter-agent

以工具的方式调用子agent

https://github.com/FrankAffatigato/CSV-chat-and-code-Interpreter-agent/blob/master/main.py

from typing import Any
from dotenv import load_dotenv
from langchain import hub
from langchain_core.tools import Tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_react_agent, AgentExecutor
from langchain_experimental.tools import PythonREPLTool
from langchain_experimental.agents.agent_toolkits import create_csv_agentload_dotenv()def main():print("Start")instructions = """You are an agent designed to write and execute python code to answer questions.You have access to a python REPL, which you can use to execute python code.If you get an error, debug your code and try again.Only use the output of your code to answer the question. You might know the answer without running any code, but you should still run the code to get the answer.If it does not seem like you can write code to answer the question, just return "I don't know" as the answer."""base_prompt = hub.pull("langchain-ai/react-agent-template")prompt = base_prompt.partial(instructions=instructions)tools = [PythonREPLTool()]python_agent = create_react_agent(prompt=prompt,llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),tools=tools,)python_agent_executor = AgentExecutor(agent=python_agent, tools=tools, verbose=True)# agent_executor.invoke(#     input={#         "input": """generate and save in current working directory 15 QRcodes#                             that point to www.udemy.com/course/langchain, you have qrcode package installed already"""#     }# )
csv_agent_executor = create_csv_agent(llm=ChatOpenAI(temperature=0, model="gpt-4"),path="episode_info.csv",verbose=True,#agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,allow_dangerous_code=True)# csv_agent.invoke(#     input={"input": "print the seasons by ascending order of the number of episodes they have?"#            }# )################################ Router Grand Agent ########################################################def python_agent_executor_wrapper(original_prompt: str) -> dict[str, Any]:return python_agent_executor.invoke({"input": original_prompt})def python_agent_executor_wrapper(original_prompt: str) -> dict[str, Any]:return python_agent_executor.invoke({"input": original_prompt})tools = [Tool(name="Python Agent",func=python_agent_executor_wrapper,description="""useful when you need to transform natural language to python and execute the python code,returning the results of the code executionDOES NOT ACCEPT CODE AS INPUT""",),Tool(name="CSV Agent",func=csv_agent_executor.invoke,description="""useful when you need to answer question over episode_info.csv file,takes an input the entire question and returns the answer after running pandas calculations""",),]prompt = base_prompt.partial(instructions="")#Create router agentgrand_agent = create_react_agent(prompt=prompt,llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),tools=tools,)grand_agent_executor = AgentExecutor(agent=grand_agent, tools=tools, verbose=True)print(grand_agent_executor.invoke({"input": "which season has the most episodes?",}))# print(#     grand_agent_executor.invoke(#         {#             "input": "generate and save in current working directory 15 QR codes that point to www.udemy.com/course/langchain, you have qrcode package installed already",#         }#     )# )if __name__ == "__main__":main()

 

https://smith.langchain.com/hub/langchain-ai/react-agent-template

{instructions}TOOLS:------You have access to the following tools:{tools}To use a tool, please use the following format:```Thought: Do I need to use a tool? YesAction: the action to take, should be one of [{tool_names}]Action Input: the input to the actionObservation: the result of the action```When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:```Thought: Do I need to use a tool? NoFinal Answer: [your response here]```Begin!Previous conversation history:{chat_history}New input: {input}{agent_scratchpad}

 

langchain MultiPromptChain

https://github.com/hyder110/LangChain-Router-Chains-for-PDF-Q-A/blob/master/multi_prompt.py

 

from langchain.chains.router import MultiPromptChain
from langchain.llms import OpenAIphysics_template = """You are a very smart physics professor. \
You are great at answering questions about physics in a concise and easy to understand manner. \
When you don't know the answer to a question you admit that you don't know.Here is a question:
{input}"""math_template = """You are a very good mathematician. You are great at answering math questions. \
You are so good because you are able to break down hard problems into their component parts, \
answer the component parts, and then put them together to answer the broader question.Here is a question:
{input}"""biology_template = """You are a skilled biology professor. \
You are great at explaining complex biological concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""english_template = """You are a skilled english professor. \
You are great at explaining complex literary concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""cs_template = """You are a proficient computer scientist. \
You can explain complex algorithms and data structures in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""python_template = """You are a skilled python programmer. \
You can explain complex algorithms and data structures in simple terms. \
When you don't know the answer to a question, you admit it.here is a question:
{input}"""accountant_template = """You are a skilled accountant. \
You can explain complex accounting concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""lawyer_template = """You are a skilled lawyer. \
You can explain complex legal concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""teacher_template = """You are a skilled teacher. \
You can explain complex educational concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""engineer_template = """You are a skilled engineer. \
You can explain complex engineering concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""psychologist_template = """You are a skilled psychologist. \
You can explain complex psychological concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""scientist_template = """You are a skilled scientist. \
You can explain complex scientific concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""economist_template = """You are a skilled economist. \
You can explain complex economic concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""architect_template = """You are a skilled architect. \
You can explain complex architectural concepts in simple terms. \
When you don't know the answer to a question, you admit it.Here is a question:
{input}"""prompt_infos = [("physics", "Good for answering questions about physics", physics_template),("math", "Good for answering math questions", math_template),("biology", "Good for answering questions about biology", biology_template),("english", "Good for answering questions about english", english_template),("cs", "Good for answering questions about computer science", cs_template),("python", "Good for answering questions about python", python_template),("accountant", "Good for answering questions about accounting", accountant_template),("lawyer", "Good for answering questions about law", lawyer_template),("teacher", "Good for answering questions about education", teacher_template),("engineer", "Good for answering questions about engineering", engineer_template),("psychologist", "Good for answering questions about psychology", psychologist_template),("scientist", "Good for answering questions about science", scientist_template),("economist", "Good for answering questions about economics", economist_template),("architect", "Good for answering questions about architecture", architect_template),
]chain = MultiPromptChain.from_prompts(OpenAI(), *zip(*prompt_infos), verbose=True)# get user question
while True:question = input("Ask a question: ")print(chain.run(question))

 

 

https://python.langchain.com.cn/docs/modules/chains/foundational/router

 

from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATEdestinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]
destinations_str = "\n".join(destinations)
router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)
router_prompt = PromptTemplate(template=router_template,input_variables=["input"],output_parser=RouterOutputParser(),
)
router_chain = LLMRouterChain.from_llm(llm, router_prompt)chain = MultiPromptChain(router_chain=router_chain,destination_chains=destination_chains,default_chain=default_chain,verbose=True,
)print(chain.run("What is black body radiation?"))

https://zhuanlan.zhihu.com/p/642971042

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/833661.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于Java+SpringBoot+Mysql在线课程学习教育系统功能设计与实现九

该系统总共24张表,代码整洁,每个功能、接口上都有注释说明。 运行环境:jdk1.8、mysql5.x、eclipse/idea、maven3.5/3.6 包远程运行的哦。 特色功能:发布课程、学习课程、分享资料、资料讨论等。 部分功能:前台课程评论信息控制器Controller、优惠卷信息控制器Controller、…

SharePoint Online页面的一些奇怪参数

前言最近,在查找资料的时候,偶然间发现了一些非常有意思的参数,如下:?env=Embedded or ?env=WebView&wdStartOn=21.正经的SharePoint Online页面2.加了参数的SharePoint Online 页面3.加了另一个参数的SharePoint Online页面结束语相信大家看效果就已经发现了,参数是…

Alpha冲刺(2/14)——2024.11.13

目录一、团队成员分工与进度二、成员任务问题及处理方式三、冲刺会议内容记录会议内容四、GitHub签入记录及项目运行截图GitHub签入记录项目运行截图五、项目开发进展及燃尽图项目开发进展燃尽图六、团队成员贡献表 一、团队成员分工与进度成员 完成的任务 完成的任务时长 剩余…

PS端Flash固化

PS端Flash固化Vivado版本:Vivado2020.2 芯片型号:RFSoC XCZU47DR 前提条件:Vitis工程编译完成,拨码开关拨到PS JTAG模式创建引导镜像 首先右键应用工程系统,点击Create Boot Image。检查镜像工程的文件是否为固化需要的工程文件,点击创建镜像的选项即可完成创建,创建完成…

Office Word 文档格式与目录样式(毕业设计论文常用)

调整格式技巧: Word 中点击 “文件”--》"选项"--》“显示”,将高亮部分全部打钩,有利于查看格式字符、 “分页符” 和“分节符” 两个很有用, 其中分节符 前后的页码是独立的。 样式间的关系: 类比 C++ 中类的继承编写的伪代码,“正文”为基类,派生出 “论文…

想不到新版的onenote配色这么好看

原来一直在用office自带的onenote,想不到新版的onenote配色这么好看。

[豪の学习笔记] 计算机网络#001

计算机网络概念、网络协议、计算机网络结构、Internet结构、电路交换、多路复用、报文交换与分组交换1.1.1 - 什么是计算机网络 计算机网络 = 通信技术 + 计算机技术计算机网络就是一种特殊的通信网络 定义:计算机网络就是互联的、自治的计算机集合 自治:无主从关系 互联:互…

第十一次作业

1、RCE:分别实现ThinkPHP、Weblogic、Shiro漏洞的利用过程> ThinkPHP: 环境搭建前端测试是否存在pearcmd,访问路径,存在的话报错就确认存在在根目录下创建magedu3.php这个文件,文件内容为<?=phpinfo()?>,10.0.0.150:8080/public/?lang=../../../../../../../.…

Python并行编程1并行编程简介(上)高频面试题:GIL进程线程协程

1 并行编程简介 首先,我们将讨论允许在新计算机上并行执行的硬件组件,如 CPU 和内核,然后讨论操作系统中真正推动并行的实体:进程和线程。随后,将详细说明并行编程模型,介绍并发性、同步性和异步性等基本概念。 介绍完这些一般概念后,我们将讨论全局解释器锁(GIL)及其…

鸿蒙NEXT开发案例:年龄计算

​ 【引言】 本案例的目标是开发一款年龄计算器应用,该应用能够根据用户输入的出生日期,计算出用户的实际年龄、虚岁、星座、生肖等信息。同时,应用还将提供距离下次公历和农历生日的天数及星期等信息。为了实现这些功能,我们将使用ArkTS和ArkUI作为开发语言,并借助@nutpi…

Dosbox-x安装WinXP——图文教程

很多老游戏只能在win95、98或者XP中运行,因此,很多人尝试将Win95、98安装到Dosbox中,利用Dosbox来玩那些久远的情怀。有Win98自然就有人想在Dosbox中安装更高级的Win系统,于是就有人尝试在Dosnox中安装Win2000、WinXP的,其中2023-07-03在国外的fabulous.systems出现了一篇…

ABB AC900F学习笔记331:使用ST做自定义功能块,计算最近60秒的分钟均值和最近60分钟的小时均值

前面自己学习了在西门子TIA使用SCL编程,施耐德Unity中使用ST编程做分钟均值和小时均值的方法,今晚在家练习了在ABB Freelance中自定义功能块使用ST语言做分钟均值和小时均值。 新建项目、插入硬件、仿真器、操作站等不做介绍。新建一个用户功能块池,下面建一个功能块类。功能…