Prolog
使用 Prolog 規則產生答案的 LangChain 工具。
概述
PrologTool 類別允許產生使用 Prolog 規則來產生答案的 langchain 工具。
設定
讓我們在 family.pl 檔案中使用以下 Prolog 規則
parent(john, bianca, mary).
parent(john, bianca, michael).
parent(peter, patricia, jennifer).
partner(X, Y) :- parent(X, Y, _).
#!pip install langchain-prolog
from langchain_prolog import PrologConfig, PrologRunnable, PrologTool
TEST_SCRIPT = "family.pl"
實例化
首先建立 Prolog 工具
schema = PrologRunnable.create_schema("parent", ["men", "women", "child"])
config = PrologConfig(
rules_file=TEST_SCRIPT,
query_schema=schema,
)
prolog_tool = PrologTool(
prolog_config=config,
name="family_query",
description="""
Query family relationships using Prolog.
parent(X, Y, Z) implies only that Z is a child of X and Y.
Input can be a query string like 'parent(john, X, Y)' or 'john, X, Y'"
You have to specify 3 parameters: men, woman, child. Do not use quotes.
""",
)
調用
將 Prolog 工具與 LLM 和函數呼叫一起使用
#!pip install python-dotenv
from dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv(), override=True)
#!pip install langchain-openai
from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI
API 參考:HumanMessage | ChatOpenAI
若要使用該工具,請將其繫結到 LLM 模型
llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools([prolog_tool])
然後查詢模型
query = "Who are John's children?"
messages = [HumanMessage(query)]
response = llm_with_tools.invoke(messages)
LLM 將會回應用工具呼叫請求
messages.append(response)
response.tool_calls[0]
{'name': 'family_query',
'args': {'men': 'john', 'women': None, 'child': None},
'id': 'call_gH8rWamYXITrkfvRP2s5pkbF',
'type': 'tool_call'}
該工具會接收此請求並查詢 Prolog 資料庫
tool_msg = prolog_tool.invoke(response.tool_calls[0])
該工具會傳回一個列表,其中包含查詢的所有解決方案
messages.append(tool_msg)
tool_msg
ToolMessage(content='[{"Women": "bianca", "Child": "mary"}, {"Women": "bianca", "Child": "michael"}]', name='family_query', tool_call_id='call_gH8rWamYXITrkfvRP2s5pkbF')
然後我們將其傳遞給 LLM,而 LLM 會使用工具回應來回答原始查詢
answer = llm_with_tools.invoke(messages)
print(answer.content)
John has two children: Mary and Michael, with Bianca as their mother.
鏈接
將 Prolog 工具與代理程式一起使用
若要將 prolog 工具與代理程式一起使用,請將其傳遞給代理程式的建構子
#!pip install langgraph
from langgraph.prebuilt import create_react_agent
agent_executor = create_react_agent(llm, [prolog_tool])
API 參考:create_react_agent
代理程式會接收查詢,並在需要時使用 Prolog 工具
messages = agent_executor.invoke({"messages": [("human", query)]})
然後代理程式會接收工具回應並產生答案
messages["messages"][-1].pretty_print()
==================================[1m Ai Message [0m==================================
John has two children: Mary and Michael, with Bianca as their mother.
API 參考
請參閱 https://langchain-prolog.readthedocs.io/en/latest/modules.html 以取得詳細資訊。