跳到主要内容
本指南概述了如何开始使用 WRITER 工具。有关所有 WRITER 功能和配置的详细文档,请访问 WRITER 文档

概览

集成详情

类别本地可序列化JS 支持下载量版本
GraphToollangchain-writerPyPI - DownloadsPyPI - Version
TranslationToollangchain-writerPyPI - DownloadsPyPI - Version
WebSearchToollangchain-writerPyPI - DownloadsPyPI - Version

特性

ChatWriter 支持多种工具类型:functiongraphtranslationweb_search
重要限制:您一次只能使用一个 WRITER 工具(翻译、图谱、网页搜索、LLM、图像、视觉)。虽然您不能组合多个 WRITER 工具,但可以同时使用一个 WRITER 工具和多个自定义函数工具。

函数

函数是最常见的工具类型,它允许 LLM 调用外部 API、从数据库获取数据,并通常执行您想要执行的任何外部操作。访问 WRITER 的工具调用文档以获取更多信息。

图谱

Graph 工具使用 WRITER 的知识图谱,它是一个基于图谱的检索增强生成(RAG)系统。使用此工具时,开发人员提供一个图谱 ID,该 ID 引用他们特定的知识图谱。然后,模型使用此图谱查找相关信息并为提示中的问题生成准确的答案。这使得模型能够在对话期间访问和利用自定义知识库。有关更多详细信息,请参阅 WRITER 的知识图谱 API 文档

翻译

翻译工具允许您在与 Palmyra 模型对话期间翻译文本。虽然 Palmyra X 模型可以执行翻译任务,但它们并未针对这些任务进行优化,并且在没有正确提示的情况下可能表现不佳。有关更多信息,请参阅 WRITER 的翻译 API 文档 网页搜索工具允许您在与 Palmyra 模型对话期间搜索网页以获取当前信息。虽然 Palmyra 模型拥有丰富的知识,但它们可能无法访问最新信息或实时数据。网页搜索工具使您的 AI 助手能够从网络中查找最新信息、新闻和事实。有关更多信息,请参阅 WRITER 的网页搜索 API 文档

设置

注册 WRITER AI Studio 以生成 API 密钥(您可以按照此快速入门进行操作)。然后,设置 WRITER_API_KEY 环境变量。
import getpass
import os

if not os.getenv("WRITER_API_KEY"):
    os.environ["WRITER_API_KEY"] = getpass.getpass("Enter your WRITER API key: ")

用法

您可以将图谱或函数工具绑定到 ChatWriter

图谱工具

要绑定图谱工具,首先使用您要用作源的 graph_ids 创建并初始化一个 GraphTool 实例。
from langchain_writer.chat_models import ChatWriter
from langchain_writer.tools import GraphTool

chat = ChatWriter()

graph_id = getpass.getpass("Enter WRITER Knowledge Graph ID: ")
graph_tool = GraphTool(graph_ids=[graph_id])

翻译工具

翻译工具允许您在与 Palmyra 模型对话期间翻译文本。虽然 Palmyra X 模型可以执行翻译任务,但它们并未针对这些任务进行优化,并且在没有正确提示的情况下可能表现不佳。 要使用翻译工具,请导入并初始化内置的 TranslationTool
from langchain_writer.tools import TranslationTool

# Initialize the translation tool
translation_tool = TranslationTool()

网页搜索工具

网页搜索工具允许您在与 Palmyra 模型对话期间搜索网页以获取当前信息。虽然 Palmyra 模型拥有丰富的知识,但它们可能无法访问最新信息或实时数据。网页搜索工具使您的 AI 助手能够从网络中查找最新信息、新闻和事实。 要使用网页搜索工具,请导入并初始化内置的 WebSearchTool
from langchain_writer.tools import WebSearchTool

# Initialize the web search tool with optional configuration
web_search_tool = WebSearchTool(
    include_domains=["wikipedia.org", "github.com", "techcrunch.com"],
    exclude_domains=["quora.com"]
)

实例化

from langchain.tools import tool
from pydantic import BaseModel, Field


@tool
def get_supercopa_trophies_count(club_name: str) -> int | None:
    """Returns information about supercopa trophies count.

    Args:
        club_name: Club you want to investigate info of supercopa trophies about

    Returns:
        Number of supercopa trophies or None if there is no info about requested club
    """

    if club_name == "Barcelona":
        return 15
    elif club_name == "Real Madrid":
        return 13
    elif club_name == "Atletico Madrid":
        return 2
    else:
        return None


class GetWeather(BaseModel):
    """Get the current weather in a given location"""

    location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


get_product_info = {
    "type": "function",
    "function": {
        "name": "get_product_info",
        "description": "Get information about a product by its id",
        "parameters": {
            "type": "object",
            "properties": {
                "product_id": {
                    "type": "number",
                    "description": "The unique identifier of the product to retrieve information for",
                }
            },
            "required": ["product_id"],
        },
    },
}

绑定工具

重要提示:WRITER 一次只允许绑定一个 WRITER 工具(翻译、图谱、网页搜索、LLM、图像、视觉)。您不能同时绑定多个 WRITER 工具。但是,您可以绑定多个自定义函数工具以及一个 WRITER 工具。
# ✅ Correct: One WRITER tool + multiple function tools
llm_with_tools = chat.bind_tools(
    [graph_tool, get_supercopa_trophies_count, GetWeather, get_product_info]
)

# ✅ Correct: Different WRITER tool + function tools
llm_with_tools = chat.bind_tools(
    [translation_tool, get_supercopa_trophies_count, GetWeather]
)

# ❌ Incorrect: Multiple WRITER tools (will cause BadRequestError)
llm_with_tools = chat.bind_tools(
    [graph_tool, translation_tool, web_search_tool]  # This will fail
)
如果您需要使用不同的 WRITER 工具,您有以下几个选项: 选项 1:为每个对话重新绑定工具
# Use graph tool for one conversation
llm_with_tools = chat.bind_tools([graph_tool, get_supercopa_trophies_count])
response1 = llm_with_tools.invoke([HumanMessage("Use the knowledge graph to answer...")])

# Switch to translation tool for another conversation
llm_with_tools = chat.bind_tools([translation_tool, get_supercopa_trophies_count])
response2 = llm_with_tools.invoke([HumanMessage("Translate this text...")])
选项 2:使用单独的 ChatWriter 实例:
# Create separate ChatWriter instances for different tools
chat_with_graph = ChatWriter()
llm_with_graph_tool = chat_with_graph.bind_tools([graph_tool])

chat_with_translation = ChatWriter()
llm_with_translation_tool = chat_with_translation.bind_tools([translation_tool])

调用

模型将在所有模式(流式/非流式,同步/异步)的调用过程中自动选择工具。
from langchain.messages import HumanMessage

# Example with graph tool and function tools
llm_with_tools = chat.bind_tools([graph_tool, get_supercopa_trophies_count])
messages = [
    HumanMessage(
        "Use knowledge graph tool to compose this answer. Tell me what the first line of documents stored in your KG. Also I want to know: how many SuperCopa trophies have Barcelona won?"
    )
]

response = llm_with_tools.invoke(messages)
messages.append(response)

# Example with translation tool
llm_with_translation = chat.bind_tools([translation_tool])
translation_messages = [
    HumanMessage("Translate 'Hello, world!' to Spanish")
]

translation_response = llm_with_translation.invoke(translation_messages)
print(translation_response.content)  # Output: "¡Hola, mundo!"

# Example with web search tool
llm_with_search = chat.bind_tools([web_search_tool])
search_messages = [
    HumanMessage("What are the latest developments in AI technology? Please search the web for current information.")
]

search_response = llm_with_search.invoke(search_messages)
print(search_response.content)  # Output: Current AI developments based on web search
对于函数工具,您将收到一条包含工具调用请求的助手消息。
print(response.tool_calls)
然后您可以手动处理工具调用请求,发送给模型并接收最终响应。
for tool_call in response.tool_calls:
    selected_tool = {
        "get_supercopa_trophies_count": get_supercopa_trophies_count,
    }[tool_call["name"].lower()]
    tool_msg = selected_tool.invoke(tool_call)
    messages.append(tool_msg)

response = llm_with_tools.invoke(messages)
print(response.content)
使用 GraphTool 时,模型将远程调用它,并在 additional_kwargsgraph_data 键下返回使用信息。
print(response.additional_kwargs["graph_data"])
content 属性包含最终响应。
print(response.content)

链接

WRITER 图谱工具与其他工具的工作方式不同;使用时,WRITER 服务器会自动处理调用知识图谱并使用 RAG 生成响应。由于这种自动化的服务器端处理,您不能独立调用 GraphTool 或将其用作 LangChain 链的一部分。您必须直接将 GraphToolChatWriter 实例一起使用,如上述示例所示。

API 参考

有关所有 GraphTool 功能和配置的详细文档,请参阅API 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.