返回文章列表

langchain自定义tool

1 min read
PYTHON
左右滑动查看完整代码
from langchain.agents import create_agent
from dotenv import load_dotenv
from langchain.tools import tool
from langchain_core.messages import HumanMessage, SystemMessage, ToolMessage
from langchain_openai import ChatOpenAI

from config import get_llm
llm = get_llm()
@tool("get_weather")
def get_weather(city: str) -> str:
    """从天气工具获取天气信息"""
    if city == "重庆":
        return "city=重庆; weather=多云; feeling=偏闷; advice=带伞"
    return f"city={city}; weather=阴天; temperature=偏低; advice=带外套"

@tool("get_data")
def get_data(store_name: str) -> int:
    """从数据库查询数据信息"""
    print(f"--- 正在查询 {store_name} 仓库的库存数据 ---")
    print(f"select * from inventory where store_name='{store_name}'")
    return 6666

agent = create_agent(llm, [get_weather, get_data],system_prompt="你是一个活泼的中文助手。遇到需要用工具解决的问题时,请先调用工具,最好用当地的方言去回答。拿到工具结果后,不要直接照抄工具返回值,要用自己的话整理成自然中文回答。")
# output = agent.invoke({"messages":[ HumanMessage("请告诉我重庆的天气怎么样?")]})
output = agent.invoke({"messages":[ HumanMessage("帮我查一下北京仓里面还有多少库存")]})
print(output["messages"][-1].content)
POWERSHELL
左右滑动查看完整代码
(docs) PS E:\AI\docs> & e:\AI\docs\.venv\Scripts\python.exe e:/AI/docs/tool.py
重庆现在的天气是多云,感觉有点闷热。建议出门带把伞,既可以遮阳又能防雨哦!
PYTHON
左右滑动查看完整代码
(docs) PS E:\AI\docs> & e:\AI\docs\.venv\Scripts\python.exe e:/AI/docs/tool.py
--- 正在查询 北京仓 仓库的库存数据 ---
select * from inventory where store_name='北京仓'
北京仓的库存还有6666个哦。