Skip to main content
使用 Prolog 规则生成答案的 LangChain 工具。

概述

PrologTool 类允许生成使用 Prolog 规则来产生答案的 LangChain 工具。

设置

使用以下 Prolog 规则,存储在 family.pl 文件中: 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.messages import HumanMessage
from langchain_openai import ChatOpenAI
将工具绑定到 LLM 模型以使用它:
model = ChatOpenAI(model="gpt-4.1-mini")
model_with_tools = model.bind_tools([prolog_tool])
然后查询模型:
query = "Who are John's children?"
messages = [HumanMessage(query)]
response = model_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 = model_with_tools.invoke(messages)
print(answer.content)
John has two children: Mary and Michael, with Bianca as their mother.

链式调用

将 Prolog 工具与 Agent 结合使用

要在 Agent 中使用 Prolog 工具,将其传入 Agent 的构造函数:
#!pip install langgraph

from langchain.agents import create_agent


agent_executor = create_agent(model, [prolog_tool])
Agent 接收查询并在需要时使用 Prolog 工具:
messages = agent_executor.invoke({"messages": [("human", query)]})
然后 Agent 接收工具响应并生成答案:
messages["messages"][-1].pretty_print()
================================== Ai Message ==================================

John has two children: Mary and Michael, with Bianca as their mother.

API 参考

详细信息请参阅 langchain-prolog.readthedocs.io/en/latest/modules.html