首页 > 其他分享 >Langchain ReAct

Langchain ReAct

时间:2024-11-10 22:43:44浏览次数:1  
标签:tool agent langchain ReAct Langchain input import tools

official

https://python.langchain.com/v0.1/docs/modules/agents/agent_types/react/

https://python.langchain.com/v0.2/api_reference/langchain/agents/langchain.agents.react.agent.create_react_agent.html

from langchain import hub
from langchain_community.llms import OpenAI
from langchain.agents import AgentExecutor, create_react_agent

prompt = hub.pull("hwchase17/react")
model = OpenAI()
tools = ...

agent = create_react_agent(model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)

agent_executor.invoke({"input": "hi"})

# Use with chat history
from langchain_core.messages import AIMessage, HumanMessage
agent_executor.invoke(
    {
        "input": "what's my name?",
        # Notice that chat_history is a string
        # since this prompt is aimed at LLMs, not chat models
        "chat_history": "Human: My name is Bob\nAI: Hello Bob!",
    }
)

 

from langchain_core.prompts import PromptTemplate

template = '''Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}'''

prompt = PromptTemplate.from_template(template)

 

demo

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

# You need to set the environmental variable OPENAI_API_KEY
from langchain_openai import ChatOpenAI
from langchain.tools import tool
from langchain import hub


# Custom tool for the Agent 
@tool
def get_employee_id(name):
  """
  To get employee id, it takes employee name as arguments
  name(str): Name of the employee
  """
  fake_employees = {
    "Alice": "E001",
    "Bob": "E002",
    "Charlie": "E003",
    "Diana": "E004",
    "Evan": "E005",
    "Fiona": "E006",
    "George": "E007",
    "Hannah": "E008",
    "Ian": "E009",
    "Jasmine": "E010"}
  
  return fake_employees.get(name,"Employee not found")

# Custom tool for the Agent 
@tool
def get_employee_salary(employee_id):
  """
  To get the salary of an employee, it takes employee_id as input and return salary
  """
  employee_salaries = {
    "E001": 56000,
    "E002": 47000,
    "E003": 52000,
    "E004": 61000,
    "E005": 45000,
    "E006": 58000,
    "E007": 49000,
    "E008": 53000,
    "E009": 50000,
    "E010": 55000
    }
  return employee_salaries.get(employee_id,"Employee not found")

# Saved React Prompt in langchain hub, we could manually type the prompt as well.
prompt = hub.pull("hwchase17/react")
model = ChatOpenAI(model='gpt-4-0125-preview')

tools = [get_employee_salary, get_employee_id]
agent = create_react_agent(model,tools, prompt)
agent_executor = AgentExecutor(agent=agent,tools=tools,verbose=True)
agent_executor.invoke({"input":"What is the Salary of Evan?"})

 

https://www.cnblogs.com/mangod/p/18230328

from langchain import hub
from langchain.agents import create_structured_chat_agent, AgentExecutor
from langchain.memory import ConversationBufferMemory
from langchain.schema import HumanMessage
from langchain.tools import BaseTool
from langchain_openai import ChatOpenAI

# 模型
model = ChatOpenAI(model="gpt-3.5-turbo",
                   openai_api_key="sk-XXXXXXXXXX",
                   openai_api_base="https://api.aigc369.com/v1")
# 直接让模型计算数字,模型会算错
model.invoke([HumanMessage(content="你帮我算下,3.941592623412424+4.3434532535353的结果")])


# 下面开始使用ReAct机制,定义工具,让LLM使用工具做专业的事情。

# 定义工具,要继承自LangChain的BaseTool
class SumNumberTool(BaseTool):
    name = "数字相加计算工具"
    description = "当你被要求计算2个数字相加时,使用此工具"

    def _run(self, a, b):
        return a.value + b.value
        
# 工具合集
tools = [SumNumberTool()]
# 提示词,直接从langchain hub上下载,因为写这个ReAct机制的prompt比较复杂,直接用现成的。
prompt = hub.pull("hwchase17/structured-chat-agent")
# 定义AI Agent
agent = create_structured_chat_agent(
    llm=model,
    tools=tools,
    prompt=prompt
)
# 使用Memory记录上下文
memory = ConversationBufferMemory(
    memory_key='chat_history',
    return_messages=True
)
# 定义AgentExecutor,必须使用AgentExecutor,才能执行代理定义的工具
agent_executor = AgentExecutor.from_agent_and_tools(
    agent=agent, tools=tools, memory=memory, verbose=True, handle_parsing_errors=True
)
# 测试使用到工具的场景
agent_executor.invoke({"input": "你帮我算下3.941592623412424+4.3434532535353的结果"})

# 测试不使用工具的场景
agent_executor.invoke({"input": "请你充当稿件审核师,帮我看看'''号里的内容有没有错别字,如果有的话帮我纠正下。'''今天班级里的学生和老实要去哪里玩'''"})        

 

autoCOT 理解

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

 

 

langchain react理解

https://github.com/Papakobina/Langchain-React-Agent/blob/main/react-langchain/main.py

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

from typing import Union, List
from dotenv import load_dotenv
from langchain.agents import tool
from langchain.agents.format_scratchpad import format_log_to_str
from langchain.agents.output_parsers import ReActSingleInputOutputParser
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.schema import AgentAction, AgentFinish
from langchain.tools import Tool
from langchain.tools.render import render_text_description


load_dotenv()


@tool
def get_text_length(text: str) -> int:
    """Returns the length of a text by characters"""
    print(f"get_text_length enter with {text=}")
    text = text.strip("'\n").strip(
        '"'
    )  # stripping away non-alphabetic characters just in case

    return len(text)


def find_tool_by_name(tools: List[Tool], tool_name: str) -> Tool:
    for tool in tools:
        if tool.name == tool_name:
            return tool
    raise ValueError(f"Tool wtih name {tool_name} not found")


if __name__ == "__main__":
    print("Hello ReAct LangChain!")
    tools = [get_text_length]

    template = """
    Answer the following questions as best you can. You have access to the following tools:

    {tools}
    
    Use the following format:
    
    Question: the input question you must answer
    Thought: you should always think about what to do
    Action: the action to take, should be one of [{tool_names}]
    Action Input: the input to the action
    Observation: the result of the action
    ... (this Thought/Action/Action Input/Observation can repeat N times)
    Thought: I now know the final answer
    Final Answer: the final answer to the original input question
    
    Begin!
    
    Question: {input}
    Thought: {agent_scratchpad}
    """

    prompt = PromptTemplate.from_template(template=template).partial(
        tools=render_text_description(tools),
        tool_names=", ".join([t.name for t in tools]),
    )

    llm = ChatOpenAI(
        temperature=0,
        model_kwargs={"stop": ["\nObservation", "Observation"]},
    )
    intermediate_steps = []
    agent = (
        {
            "input": lambda x: x["input"],
            "agent_scratchpad": lambda x: format_log_to_str(x["agent_scratchpad"]),
        }
        | prompt
        | llm
        | ReActSingleInputOutputParser()
    )

    agent_step: Union[AgentAction, AgentFinish] = agent.invoke(
        {
            "input": "What is the length of the word: DOG",
            "agent_scratchpad": intermediate_steps,
        }
    )
    print(agent_step)
    if isinstance(agent_step, AgentAction):
        tool_name = agent_step.tool
        tool_to_use = find_tool_by_name(tools, tool_name)
        tool_input = agent_step.tool_input
        observation = tool_to_use.func(str(tool_input))
        print(f"{observation=}")
        intermediate_steps.append((agent_step, str(observation)))

    agent_step: Union[AgentAction, AgentFinish] = agent.invoke(
        {
            "input": "What is the length of the word: DOG",
            "agent_scratchpad": intermediate_steps,
        }
    )
    print(agent_step)
    if isinstance(agent_step, AgentFinish):
        print("### AgentFinish ###")
        print(agent_step.return_values)

 

标签:tool,agent,langchain,ReAct,Langchain,input,import,tools
From: https://www.cnblogs.com/lightsong/p/18538670

相关文章

  • 使用react+copy-to-clipboard封装双击复制组件
    前言:最近在公司研发后台系统,用户反馈在双击某些信息时希望可以进行复制的操作,多处使用进而封装为组件首先:安装copy-to-clipboardnpmi--savecopy-to-clipboard其次:封装组件importReact,{memo,useCallback}from'react';import{notification}from"antd";......
  • 小北的字节跳动青训营与LangChain实战课:深入探索Chain的奥秘(上)写一篇完美鲜花推文?用Se
     前言    最近,字节跳动的青训营再次扬帆起航,作为第二次参与其中的小北,深感荣幸能借此机会为那些尚未了解青训营的友友们带来一些详细介绍。青训营不仅是一个技术学习与成长的摇篮,更是一个连接未来与梦想的桥梁~小北的青训营XMarsCode技术训练营——AI加码,字节跳......
  • Redux的基本原理以及其如何在React中使用
    什么是Redux?它有什么用Redux是一个用于JavaScript应用的状态管理库,通常与React一起使用。它帮助开发者管理应用中各个组件之间的状态,使得状态的变化变得更加可预测和易于调试。注意:Redux也可以不和React组合使用的哦(通常一起使用)Redux基本原理所有的状态都以对象树......
  • ReactPress技术揭秘
    ReactPressGithub项目地址:https://github.com/fecommunity/reactpress欢迎Star。一、引言ReactPress是一个基于React构建的开源发布平台,它不仅可以帮助用户在支持React和MySQL数据库的服务器上快速搭建自己的博客或网站,还能作为一个功能强大的内容管理系统(CMS)使用。本......
  • Springboot 的Servlet Web 应用、响应式 Web 应用(Reactive)以及非 Web 应用(None)的特点
    基于Servlet的Web应用(ServletWeb)    特点         使用传统的ServletAPI和SpringMVC框架。         采用阻塞I/O模型,每个请求都会占用一个线程直到请求处理完毕。         适合处理同步请求-......
  • python实战(七)——基于LangChain的RAG实践
    一、任务目标    基于之前的RAG实战,相信大家对RAG的实现已经有了一定的了解了。这篇文章将使用LangChain作为辅助,实现一个高效、便于维护的RAG程序。二、什么是LangChain        LangChain是一个用于构建大模型应用程序的开源框架,它内置了多个模块化组件。......
  • WINDOWS XP ReactOS 4.2 对象类型
    系列文章目录文章目录系列文章目录4.2对象类型OBJECT_TYPE_INITIALIZERExpInitializeTimerImplementation()ObpInsertEntryDirectory()ObInit()IopCreateObjectTypes()4.2对象类型对象是分类的,因而是有“类型(Type)”的,前面列举了许多常用的Windows对象类型。但是要列举......
  • 4.1 WINDOWS XP,ReactOS对象与对象目录----1
    系列文章目录文章目录系列文章目录4.1对象与对象目录OBJECT_HEADERObpLookupEntryDirectory()NtCreateTimer()4.1对象与对象目录“对象(Object)”这个词现在大家都已耳熟能详了,但是对象到底是什么呢?广义地说,对象就是“目标”,行为的目标,或者说行为的受体。所以,广......
  • react 组件应用
    文章目录react组件react中组件hook函数应用useMemo技术细节(useMemo钩子函数和useCallback钩子函数)小结(依赖性数组应用)react组件函数式组件实例及应用场景实例:以下是一个简单的函数式组件,用于显示一个欢迎消息。importReactfrom'react';con......
  • ReactPress 是什么?
    ReactPressGithub项目地址:https://github.com/fecommunity/reactpress欢迎Star。ReactPress是什么?ReactPress是使用React开发的开源发布平台,用户可以在支持React和MySQL数据库的服务器上架设属于自己的博客、网站。也可以把ReactPress当作一个内容管理系统(CMS)来使......