Skip to main content
本指南概述了如何开始使用 WRITER 工具。有关所有 WRITER 功能和配置的详细文档,请访问 WRITER 文档

概述

集成详情

ClassPackageLocalSerializableJS supportDownloadsVersion
GraphToollangchain-writerPyPI - DownloadsPyPI - Version
TranslationToollangchain-writerPyPI - DownloadsPyPI - Version
WebSearchToollangchain-writerPyPI - DownloadsPyPI - Version

功能

ChatWriter 支持以下几种工具类型:functiongraphtranslationweb_search
重要限制:每次只能使用一种 WRITER 工具(translation、graph、web_search、llm、image、vision)。虽然不能同时组合使用多种 WRITER 工具,但可以将一种 WRITER 工具与多个自定义函数工具搭配使用。

Function(函数)

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

Graph(知识图谱)

Graph 工具使用 WRITER 的知识图谱,这是一个基于图的检索增强生成(RAG)系统。使用此工具时,开发者提供一个指向其特定知识图谱的图 ID。模型随后使用该图查找相关信息,并对提示词中的问题生成准确答案。这使模型能够在对话过程中访问和利用自定义知识库。更多详情请参阅 WRITER 的知识图谱 API 文档

Translation(翻译)

翻译工具允许您在与 Palmyra 模型的对话中翻译文本。虽然 Palmyra X 模型可以执行翻译任务,但它们并未针对这些任务进行优化,在没有正确提示的情况下效果可能不佳。更多信息请参阅 WRITER 的翻译 API 文档

Web search(网络搜索)

网络搜索工具允许您在与 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 工具(translation、graph、web_search、llm、image、vision)。不能同时绑定多种 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 工具,有以下几种方案: 方案一:为每次对话重新绑定工具
# 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...")])
方案二:使用独立的 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 Graph 工具与其他工具的工作方式不同;使用时,WRITER 服务器会自动处理知识图谱调用并使用 RAG 生成响应。由于这种自动化的服务端处理机制,您无法独立调用 GraphTool 或将其作为 LangChain 链的一部分使用。必须按照上述示例直接将 GraphToolChatWriter 实例配合使用。

API 参考

有关所有 GraphTool 功能和配置的详细文档,请访问 API 参考