当前位置:   article > 正文

LangChain-Agent自定义Tools类 ——输入参数篇(二)_langchain agent 控制输入参数

langchain agent 控制输入参数

给自定义函数传入输入参数,分别有single-input 参数函数案例和multi-input 参数函数案例: 

  1. from langchain.agents import Tool
  2. from langchain.tools import BaseTool
  3. from math import pi
  4. from typing import Union
  5. from math import pi
  6. from typing import Union
  7. from langchain.agents import initialize_agent
  8. from langchain.agents import AgentType
  9. import os
  10. from langchain.chat_models import ChatOpenAI
  11. from langchain.chains.conversation.memory import ConversationBufferWindowMemory
  12. from typing import Optional
  13. class Calculate_Life(BaseTool):#这里的RUL value 我瞎编的
  14. name = "Calculate Life Tool"
  15. description = "use this tool when you need to calculate the happiness of life using the RUL value"
  16. def _run(self, RUL: Union[int, float]):
  17. return "The happiness of life is {RUL*2}"
  18. def _arun(self, RUL: int):
  19. raise NotImplementedError("This tool does not support async")
  20. class Calculate_volumn(BaseTool):#这里的RUL value 我瞎编的
  21. name = "Calculate Object Volumn"
  22. description = (
  23. "use this tool when you need to calculate the the volumn of object,inputs are multi parameters,need multi input variables,like the length,width,and height."
  24. "To use the tool, you must provide at least three of the following parameters "
  25. "['length', 'width', 'height']."
  26. )
  27. def _run(
  28. self,
  29. length: Optional[Union[int, float]] = None,
  30. width: Optional[Union[int, float]] = None,
  31. height: Optional[Union[int, float]] = None
  32. ):
  33. # check for the values we have been given
  34. if length and width and height:
  35. return length*width*height
  36. else:
  37. return "Could not calculate the size of universe. Need two or more of `length`, `width`,`height`."
  38. def _arun(self, query: str):
  39. raise NotImplementedError("This tool does not support async")
  40. os.environ["OPENAI_API_KEY"] = "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"
  41. llm = ChatOpenAI(
  42. openai_api_key=os.environ["OPENAI_API_KEY"] ,
  43. temperature=0,
  44. model_name='gpt-3.5-turbo'
  45. )
  46. # initialize conversational memory
  47. conversational_memory = ConversationBufferWindowMemory(
  48. memory_key='chat_history',
  49. k=5,
  50. return_messages=True
  51. )
  52. tools = [Calculate_volumn()]
  53. # sys_msg = """Assistant is a large language model trained by OpenAI.
  54. # Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
  55. # Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
  56. # Unfortunately, Assistant is terrible at maths. When provided with math questions, no matter how simple, assistant always refers to it's trusty tools and absolutely does NOT try to answer math questions by itself
  57. # Overall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
  58. # """
  59. # sys_msg = "Do not try to figure math question by yourself, you might be blindly confident about your mathematic capacity,please always refers to it's trusty tools and absolutely does NOT try to answer math questions by itself"
  60. # agent = initialize_agent(
  61. # agent='chat-conversational-react-description',
  62. # # agent='zero-shot-react-description',
  63. # tools=tools,
  64. # llm=llm,
  65. # verbose=True,
  66. # max_iterations=3,
  67. # early_stopping_method='generate',
  68. # memory=conversational_memory
  69. # )
  70. new_prompt = agent.agent.create_prompt(
  71. system_message=sys_msg,
  72. tools=tools
  73. )
  74. agent.agent.llm_chain.prompt = new_prompt
  75. # update the agent tools
  76. agent.tools = tools
  77. # agent("How much is the happiness of life when RUL value is equal to 2")#单个参数提问
  78. agent("Given [length=10000,width=2,height=3],what's the size of this box?")#多个参数提问

运行结果 

后期关注结构化输出,方便作为借口提供给其他下游应用 

相关友情链接:

为 LLM 代理构建自定义工具 |松果 (pinecone.io)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/615642
推荐阅读
相关标签
  

闽ICP备14008679号