langchain_community.chains.graph_qa.arangodb.ArangoGraphQAChain

注意

ArangoGraphQAChain 实现了标准的 Runnable 接口。 🏃

Runnable 接口 具有在 runnables 上可用的附加方法,例如 with_types, with_retry, assign, bind, get_graph, 等等。

class langchain_community.chains.graph_qa.arangodb.ArangoGraphQAChain[source]

基类: Chain

用于通过生成 AQL 语句来回答关于图的问题的链。

安全注意事项: 确保数据库连接使用的凭据

具有狭窄的范围,仅包含必要的权限。未能这样做可能会导致数据损坏或丢失,因为调用代码可能会尝试导致删除、数据突变(如果适当提示)或读取敏感数据(如果此类数据存在于数据库中)的命令。防止此类负面结果的最佳方法是(在适当的情况下)限制授予与此工具一起使用的凭据的权限。

有关更多信息,请参阅 https://python.langchain.ac.cn/docs/security

param aql_examples: str = ''
param aql_fix_chain: LLMChain [必需]
param aql_generation_chain: LLMChain [必需]
param callback_manager: Optional[BaseCallbackManager] = None

[已弃用] 请使用 callbacks 代替。

param callbacks: Callbacks = None

回调处理程序(或回调管理器)的可选列表。默认为 None。回调处理程序在链调用的整个生命周期中被调用,从 on_chain_start 开始,到 on_chain_end 或 on_chain_error 结束。每个自定义链可以选择调用其他回调方法,有关完整详细信息,请参阅回调文档。

param graph: ArangoGraph [必需]
param max_aql_generation_attempts: int = 3
param memory: Optional[BaseMemory] = None

可选的内存对象。默认为 None。内存是一个类,在每个链的开始和结束时被调用。在开始时,内存加载变量并在链中传递它们。在结束时,它保存任何返回的变量。有许多不同类型的内存 - 请参阅内存文档以获取完整目录。

param metadata: Optional[Dict[str, Any]] = None

与链关联的可选元数据。默认为 None。此元数据将与此链的每次调用关联,并作为参数传递给 callbacks 中处理程序。您可以使用这些来例如标识具有其用例的链的特定实例。

param qa_chain: LLMChain [必需]
param return_aql_query: bool = False
param return_aql_result: bool = False
param tags: Optional[List[str]] = None

与链关联的可选标签列表。默认为 None。这些标签将与此链的每次调用关联,并作为参数传递给 callbacks 中定义的处理程序。您可以使用这些来例如标识具有其用例的链的特定实例。

param top_k: int = 10
param verbose: bool [可选]

是否在 verbose 模式下运行。在 verbose 模式下,一些中间日志将被打印到控制台。默认为全局 verbose 值,可通过 langchain.globals.get_verbose() 访问。

__call__(inputs: Union[Dict[str, Any], Any], return_only_outputs: bool = False, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, include_run_info: bool = False) Dict[str, Any]

Deprecated since version langchain==0.1.0: 请使用 invoke 代替。

执行链。

参数
  • inputs (Union[Dict[str, Any], Any]) – 输入字典,或者如果链只期望一个参数,则为单个输入。应包含 Chain.input_keys 中指定的所有输入,但链的内存将设置的输入除外。

  • return_only_outputs (bool) – 是否仅在响应中返回输出。如果为 True,则仅返回由此链生成的新键。如果为 False,则将返回输入键和由此链生成的新键。默认为 False。

  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调除了在构造期间传递给链的回调之外还会被调用,但只有这些运行时回调会传播到对其他对象的调用。

  • tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签除了在构造期间传递给链的标签之外还会被传递,但只有这些运行时标签会传播到对其他对象的调用。

  • metadata (Optional[Dict[str, Any]]) – 与链关联的可选元数据。默认为 None

  • include_run_info (bool) – 是否在响应中包含运行信息。默认为 False。

  • run_name (Optional[str]) –

返回值

命名输出的字典。应包含在

Chain.output_keys 中指定的所有输出.

返回类型

Dict[str, Any]

async abatch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) List[Output]

默认实现使用 asyncio.gather 并行运行 ainvoke。

batch 的默认实现适用于 IO 绑定的 runnables。

如果子类可以更有效地进行批量处理,则应覆盖此方法;例如,如果底层 Runnable 使用支持批量模式的 API。

参数
  • inputs (List[Input]) – Runnable 的输入列表。

  • config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) – 调用 Runnable 时要使用的配置。该配置支持标准键,如 ‘tags’、‘metadata’(用于跟踪目的)、‘max_concurrency’(用于控制并行执行多少工作)和其他键。有关更多详细信息,请参阅 RunnableConfig。默认为 None。

  • return_exceptions (bool) – 是否返回异常而不是引发异常。默认为 False。

  • kwargs (Optional[Any]) – 要传递给 Runnable 的其他关键字参数。

返回值

来自 Runnable 的输出列表。

返回类型

List[Output]

async abatch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) AsyncIterator[Tuple[int, Union[Output, Exception]]]

在输入列表上并行运行 ainvoke,并在结果完成时产生结果。

参数
  • inputs (Sequence[Input]) – Runnable 的输入列表。

  • config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) – 调用 Runnable 时要使用的配置。该配置支持标准键,如 ‘tags’、‘metadata’(用于跟踪目的)、‘max_concurrency’(用于控制并行执行多少工作)和其他键。有关更多详细信息,请参阅 RunnableConfig。默认为 None。默认为 None。

  • return_exceptions (bool) – 是否返回异常而不是引发异常。默认为 False。

  • kwargs (Optional[Any]) – 要传递给 Runnable 的其他关键字参数。

产生

输入索引和来自 Runnable 的输出的元组。

返回类型

AsyncIterator[Tuple[int, Union[Output, Exception]]]

异步执行链。

参数
  • inputs (Union[Dict[str, Any], Any]) – 输入字典,或者如果链只期望一个参数,则为单个输入。应包含 Chain.input_keys 中指定的所有输入,但链的内存将设置的输入除外。

  • return_only_outputs (bool) – 是否仅在响应中返回输出。如果为 True,则仅返回由此链生成的新键。如果为 False,则将返回输入键和由此链生成的新键。默认为 False。

  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调除了在构造期间传递给链的回调之外还会被调用,但只有这些运行时回调会传播到对其他对象的调用。

  • tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签除了在构造期间传递给链的标签之外还会被传递,但只有这些运行时标签会传播到对其他对象的调用。

  • metadata (Optional[Dict[str, Any]]) – 与链关联的可选元数据。默认为 None

  • include_run_info (bool) – 是否在响应中包含运行信息。默认为 False。

  • run_name (Optional[str]) –

返回值

命名输出的字典。应包含在

Chain.output_keys 中指定的所有输出.

返回类型

Dict[str, Any]

ainvoke 的默认实现,从线程中调用 invoke。

即使 Runnable 没有实现 invoke 的原生异步版本,默认实现也允许使用异步代码。

如果子类可以异步运行,则应覆盖此方法。

参数
返回类型

Dict[str, Any]

对列表中的所有输入调用链。

参数
返回类型

准备链的输入,包括从内存添加输入。

参数

返回值

所有输入的字典,包括链的内存添加的输入。

返回类型

验证和准备链的输出,并将有关此运行的信息保存到内存中。

参数
返回值

最终链输出的字典。

返回类型

执行链的便捷方法。

此方法与

参数
  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调除了在构造期间传递给链的回调之外还会被调用,但只有这些运行时回调会传播到对其他对象的调用。

  • tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签除了在构造期间传递给链的标签之外还会被传递,但只有这些运行时标签会传播到对其他对象的调用。

返回值

链的输出。

返回类型

Any

示例

# Suppose we have a single-input chain that takes a 'question' string:
await chain.arun("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."

# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' string:
question = "What's the temperature in Boise, Idaho?"
context = "Weather report for Boise, Idaho on 07/03/23..."
await chain.arun(question=question, context=context)
# -> "The temperature in Boise is..."

Beta

此 API 处于 Beta 阶段,未来可能会发生变化。

从 Runnable 创建 BaseTool。

参数
返回值

BaseTool 实例。

返回类型

BaseTool

类型化的字典输入

from typing import List
from typing_extensions import TypedDict
from langchain_core.runnables import RunnableLambda

class Args(TypedDict):
    a: int
    b: List[int]

def f(x: Args) -> str:
    return str(x["a"] * max(x["b"]))

runnable = RunnableLambda(f)
as_tool = runnable.as_tool()
as_tool.invoke({"a": 3, "b": [1, 2]})

from typing import Any, Dict, List
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.runnables import RunnableLambda

def f(x: Dict[str, Any]) -> str:
    return str(x["a"] * max(x["b"]))

class FSchema(BaseModel):
    """Apply a function to an integer and list of integers."""

    a: int = Field(..., description="Integer")
    b: List[int] = Field(..., description="List of ints")

runnable = RunnableLambda(f)
as_tool = runnable.as_tool(FSchema)
as_tool.invoke({"a": 3, "b": [1, 2]})

from typing import Any, Dict, List
from langchain_core.runnables import RunnableLambda

def f(x: Dict[str, Any]) -> str:
    return str(x["a"] * max(x["b"]))

runnable = RunnableLambda(f)
as_tool = runnable.as_tool(arg_types={"a": int, "b": List[int]})
as_tool.invoke({"a": 3, "b": [1, 2]})

字符串输入

from langchain_core.runnables import RunnableLambda

def f(x: str) -> str:
    return x + "a"

def g(x: str) -> str:
    return x + "z"

runnable = RunnableLambda(f) | g
as_tool = runnable.as_tool()
as_tool.invoke("b")

0.2.14 版本新增功能。

astream 的默认实现,它调用 ainvoke。如果子类支持流式输出,则应覆盖此方法。

参数
  • kwargs (Optional[Any]) – 要传递给 Runnable 的其他关键字参数。

产生

Runnable 的输出。

返回类型

Beta

此 API 处于 Beta 阶段,未来可能会发生变化。

生成事件流。

用于创建 StreamEvents 的迭代器,该迭代器提供有关 Runnable 进度的实时信息,包括来自中间结果的 StreamEvents。

StreamEvent 是具有以下模式的字典

  • 格式:on_[runnable_type]_(start|stream|end)。

  • 该 Runnable 发出事件。作为父 Runnable 执行一部分调用的子 Runnable 将被分配其自己的唯一 ID。

  • 根 Runnable 将有一个空列表。父 ID 的顺序是从根到直接父级。仅适用于 API 的 v2 版本。API 的 v1 版本将返回一个空列表。

  • 事件。

  • 生成事件的元数据。

下面是一个表格,说明了各种链可能发出的一些事件。为了简洁起见,元数据字段已从表格中省略。链定义已包含在表格之后。

事件

名称

输入

输出

on_chat_model_start

[模型名称]

{“messages”: [[SystemMessage, HumanMessage]]}

on_chat_model_stream

[模型名称]

AIMessageChunk(content=”hello”)

on_chat_model_end

[模型名称]

{“messages”: [[SystemMessage, HumanMessage]]}

AIMessageChunk(content=”hello world”)

on_llm_start

[模型名称]

{‘input’: ‘hello’}

on_llm_stream

[模型名称]

‘Hello’

on_llm_end

[模型名称]

‘Hello human!’

on_chain_start

format_docs

on_chain_stream

format_docs

“hello world!, goodbye world!”

on_chain_end

format_docs

[Document(…)]

“hello world!, goodbye world!”

on_tool_start

some_tool

{“x”: 1, “y”: “2”}

on_tool_end

some_tool

{“x”: 1, “y”: “2”}

on_retriever_start

[检索器名称]

{“query”: “hello”}

on_retriever_end

[检索器名称]

{“query”: “hello”}

[Document(…), ..]

on_prompt_start

[模板名称]

{“question”: “hello”}

on_prompt_end

[模板名称]

{“question”: “hello”}

ChatPromptValue(messages: [SystemMessage, …])

除了标准事件外,用户还可以分派自定义事件(请参阅下面的示例)。

自定义事件将仅在 API 的

自定义事件具有以下格式

属性

类型

描述

名称

str

用户定义的事件名称。

data

Any

与事件关联的数据。这可以是任何内容,但我们建议使其可 JSON 序列化。

以下是与上面所示标准事件关联的声明

format_docs:

def format_docs(docs: List[Document]) -> str:
    '''Format the docs.'''
    return ", ".join([doc.page_content for doc in docs])

format_docs = RunnableLambda(format_docs)

some_tool:

@tool
def some_tool(x: int, y: str) -> dict:
    '''Some_tool.'''
    return {"x": x, "y": y}

prompt:

template = ChatPromptTemplate.from_messages(
    [("system", "You are Cat Agent 007"), ("human", "{question}")]
).with_config({"run_name": "my_template", "tags": ["my_template"]})

示例

from langchain_core.runnables import RunnableLambda

async def reverse(s: str) -> str:
    return s[::-1]

chain = RunnableLambda(func=reverse)

events = [
    event async for event in chain.astream_events("hello", version="v2")
]

# will produce the following events (run_id, and parent_ids
# has been omitted for brevity):
[
    {
        "data": {"input": "hello"},
        "event": "on_chain_start",
        "metadata": {},
        "name": "reverse",
        "tags": [],
    },
    {
        "data": {"chunk": "olleh"},
        "event": "on_chain_stream",
        "metadata": {},
        "name": "reverse",
        "tags": [],
    },
    {
        "data": {"output": "olleh"},
        "event": "on_chain_end",
        "metadata": {},
        "name": "reverse",
        "tags": [],
    },
]

示例:分派自定义事件

from langchain_core.callbacks.manager import (
    adispatch_custom_event,
)
from langchain_core.runnables import RunnableLambda, RunnableConfig
import asyncio


async def slow_thing(some_input: str, config: RunnableConfig) -> str:
    """Do something that takes a long time."""
    await asyncio.sleep(1) # Placeholder for some slow operation
    await adispatch_custom_event(
        "progress_event",
        {"message": "Finished step 1 of 3"},
        config=config # Must be included for python < 3.10
    )
    await asyncio.sleep(1) # Placeholder for some slow operation
    await adispatch_custom_event(
        "progress_event",
        {"message": "Finished step 2 of 3"},
        config=config # Must be included for python < 3.10
    )
    await asyncio.sleep(1) # Placeholder for some slow operation
    return "Done"

slow_thing = RunnableLambda(slow_thing)

async for event in slow_thing.astream_events("some_input", version="v2"):
    print(event)
参数
产生

StreamEvents 的异步流。

Raises

返回类型

默认实现使用线程池执行器并行运行 invoke。

batch 的默认实现适用于 IO 绑定的 runnables。

如果子类可以更有效地进行批量处理,则应覆盖此方法;例如,如果底层 Runnable 使用支持批量模式的 API。

参数
返回类型

List[Output]

batch_as_completed(inputs: Sequence[Input], config: Optional[Union[RunnableConfig, Sequence[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs[: Optional[Any]) Iterator[Tuple[int, Union[Output, Exception]]]

运行并行调用列表中的输入,并在完成后生成结果。

参数
返回类型

Iterator[Tuple[int, Union[Output, Exception]]]

configurable_alternatives(which: ConfigurableField, *, default_key: str = 'default', prefix_keys: bool = False, **kwargs: Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) RunnableSerializable[Input, Output]

配置可在运行时设置的 Runnable 的备选项。

参数
  • which (ConfigurableField) – 将用于选择备选项的 ConfigurableField 实例。

  • default_key (str) – 如果未选择备选项,则使用的默认键。默认为“default”。

  • prefix_keys (bool) – 是否为键添加 ConfigurableField id 前缀。默认为 False。

  • **kwargs (Union[Runnable[Input, Output], Callable[[], Runnable[Input, Output]]]) – 键到 Runnable 实例或返回 Runnable 实例的可调用对象的字典。

返回值

配置了备选项的新 Runnable。

返回类型

RunnableSerializable[Input, Output]

from langchain_anthropic import ChatAnthropic
from langchain_core.runnables.utils import ConfigurableField
from langchain_openai import ChatOpenAI

model = ChatAnthropic(
    model_name="claude-3-sonnet-20240229"
).configurable_alternatives(
    ConfigurableField(id="llm"),
    default_key="anthropic",
    openai=ChatOpenAI()
)

# uses the default model ChatAnthropic
print(model.invoke("which organization created you?").content)

# uses ChatOpenAI
print(
    model.with_config(
        configurable={"llm": "openai"}
    ).invoke("which organization created you?").content
)
configurable_fields(**kwargs: Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) RunnableSerializable[Input, Output]

在运行时配置特定的 Runnable 字段。

参数

**kwargs (Union[ConfigurableField, ConfigurableFieldSingleOption, ConfigurableFieldMultiOption]) – 要配置的 ConfigurableField 实例的字典。

返回值

配置了字段的新 Runnable。

返回类型

RunnableSerializable[Input, Output]

from langchain_core.runnables import ConfigurableField
from langchain_openai import ChatOpenAI

model = ChatOpenAI(max_tokens=20).configurable_fields(
    max_tokens=ConfigurableField(
        id="output_token_number",
        name="Max tokens in the output",
        description="The maximum number of tokens in the output",
    )
)

# max_tokens = 20
print(
    "max_tokens_20: ",
    model.invoke("tell me something about chess").content
)

# max_tokens = 200
print("max_tokens_200: ", model.with_config(
    configurable={"output_token_number": 200}
    ).invoke("tell me something about chess").content
)
classmethod from_llm(llm: BaseLanguageModel, *, qa_prompt: BasePromptTemplate = PromptTemplate(input_variables=['adb_schema', 'aql_query', 'aql_result', 'user_input'], template="Task: Generate a natural language `Summary` from the results of an ArangoDB Query Language query.\n\nYou are an ArangoDB Query Language (AQL) expert responsible for creating a well-written `Summary` from the `User Input` and associated `AQL Result`.\n\nA user has executed an ArangoDB Query Language query, which has returned the AQL Result in JSON format.\nYou are responsible for creating an `Summary` based on the AQL Result.\n\nYou are given the following information:\n- `ArangoDB Schema`: contains a schema representation of the user's ArangoDB Database.\n- `User Input`: the original question/request of the user, which has been translated into an AQL Query.\n- `AQL Query`: the AQL equivalent of the `User Input`, translated by another AI Model. Should you deem it to be incorrect, suggest a different AQL Query.\n- `AQL Result`: the JSON output returned by executing the `AQL Query` within the ArangoDB Database.\n\nRemember to think step by step.\n\nYour `Summary` should sound like it is a response to the `User Input`.\nYour `Summary` should not include any mention of the `AQL Query` or the `AQL Result`.\n\nArangoDB Schema:\n{adb_schema}\n\nUser Input:\n{user_input}\n\nAQL Query:\n{aql_query}\n\nAQL Result:\n{aql_result}\n"), aql_generation_prompt: BasePromptTemplate = PromptTemplate(input_variables=['adb_schema', 'aql_examples', 'user_input'], template="Task: Generate an ArangoDB Query Language (AQL) query from a User Input.\n\nYou are an ArangoDB Query Language (AQL) expert responsible for translating a `User Input` into an ArangoDB Query Language (AQL) query.\n\nYou are given an `ArangoDB Schema`. It is a JSON Object containing:\n1. `Graph Schema`: Lists all Graphs within the ArangoDB Database Instance, along with their Edge Relationships.\n2. `Collection Schema`: Lists all Collections within the ArangoDB Database Instance, along with their document/edge properties and a document/edge example.\n\nYou may also be given a set of `AQL Query Examples` to help you create the `AQL Query`. If provided, the `AQL Query Examples` should be used as a reference, similar to how `ArangoDB Schema` should be used.\n\nThings you should do:\n- Think step by step.\n- Rely on `ArangoDB Schema` and `AQL Query Examples` (if provided) to generate the query.\n- Begin the `AQL Query` by the `WITH` AQL keyword to specify all of the ArangoDB Collections required.\n- Return the `AQL Query` wrapped in 3 backticks (```).\n- Use only the provided relationship types and properties in the `ArangoDB Schema` and any `AQL Query Examples` queries.\n- Only answer to requests related to generating an AQL Query.\n- If a request is unrelated to generating AQL Query, say that you cannot help the user.\n\nThings you should not do:\n- Do not use any properties/relationships that can't be inferred from the `ArangoDB Schema` or the `AQL Query Examples`. \n- Do not include any text except the generated AQL Query.\n- Do not provide explanations or apologies in your responses.\n- Do not generate an AQL Query that removes or deletes any data.\n\nUnder no circumstance should you generate an AQL Query that deletes any data whatsoever.\n\nArangoDB Schema:\n{adb_schema}\n\nAQL Query Examples (Optional):\n{aql_examples}\n\nUser Input:\n{user_input}\n\nAQL Query: \n"), aql_fix_prompt: BasePromptTemplate = PromptTemplate(input_variables=['adb_schema', 'aql_error', 'aql_query'], template="Task: Address the ArangoDB Query Language (AQL) error message of an ArangoDB Query Language query.\n\nYou are an ArangoDB Query Language (AQL) expert responsible for correcting the provided `AQL Query` based on the provided `AQL Error`. \n\nThe `AQL Error` explains why the `AQL Query` could not be executed in the database.\nThe `AQL Error` may also contain the position of the error relative to the total number of lines of the `AQL Query`.  \n\nYou are also given the `ArangoDB Schema`. It is a JSON Object containing:\n1. `Graph Schema`: Lists all Graphs within the ArangoDB Database Instance, along with their Edge Relationships.\n2. `Collection Schema`: Lists all Collections within the ArangoDB Database Instance, along with their document/edge properties and a document/edge example.\n\nYou will output the `Corrected AQL Query` wrapped in 3 backticks (```). Do not include any text except the Corrected AQL Query.\n\nRemember to think step by step.\n\nArangoDB Schema:\n{adb_schema}\n\nAQL Query:\n{aql_query}\n\nAQL Error:\n{aql_error}\n\nCorrected AQL Query:\n"), **kwargs: Any) ArangoGraphQAChain[source]

从 LLM 初始化。

参数
返回类型

ArangoGraphQAChain

invoke(input: Dict[str, Any], config: Optional[RunnableConfig] = None, **kwargs[: Any) Dict[str, Any]

将单个输入转换为输出。覆盖以实现。

参数
  • input (Dict[str, Any]) – Runnable 的输入。

  • config (Optional[RunnableConfig]) – 调用 Runnable 时要使用的配置。该配置支持标准键,如用于跟踪目的的“tags”、“metadata”,用于控制并行执行量的“max_concurrency”以及其他键。请参阅 RunnableConfig 以获取更多详细信息。

返回值

Runnable 的输出。

返回类型

Dict[str, Any]

prep_inputs(inputs: Union[Dict[str, Any], Any]) Dict[str, str]

准备链的输入,包括从内存添加输入。

参数

返回值

所有输入的字典,包括链的内存添加的输入。

返回类型

prep_outputs(inputs: Dict[str, str], outputs: Dict[str, str], return_only_outputs: bool = False) Dict[str, str]

验证和准备链的输出,并将有关此运行的信息保存到内存中。

参数
返回值

最终链输出的字典。

返回类型

run(*args: Any, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any) Any

Deprecated since version langchain==0.1.0: 请使用 invoke 代替。

执行链的便捷方法。

此方法与

参数
  • callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – 用于此链运行的回调。这些回调除了在构造期间传递给链的回调之外还会被调用,但只有这些运行时回调会传播到对其他对象的调用。

  • tags (Optional[List[str]]) – 要传递给所有回调的字符串标签列表。这些标签除了在构造期间传递给链的标签之外还会被传递,但只有这些运行时标签会传播到对其他对象的调用。

返回值

链的输出。

返回类型

Any

示例

# Suppose we have a single-input chain that takes a 'question' string:
chain.run("What's the temperature in Boise, Idaho?")
# -> "The temperature in Boise is..."

# Suppose we have a multi-input chain that takes a 'question' string
# and 'context' string:
question = "What's the temperature in Boise, Idaho?"
context = "Weather report for Boise, Idaho on 07/03/23..."
chain.run(question=question, context=context)
# -> "The temperature in Boise is..."
save(file_path: Union[Path, str]) None

保存链。

期望实现 Chain._chain_type 属性,并且内存为空。

null。

参数

file_path (Union[Path, str]) – 保存链到文件的路径。

返回类型

None

示例

chain.save(file_path="path/chain.yaml")
stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) Iterator[Output]

流式传输的默认实现,它调用 invoke。如果子类支持流式输出,则应重写此方法。

参数
  • kwargs (Optional[Any]) – 要传递给 Runnable 的其他关键字参数。

产生

Runnable 的输出。

返回类型

Iterator[Output]

to_json() Union[SerializedConstructor, SerializedNotImplemented]

将 Runnable 序列化为 JSON。

返回值

Runnable 的 JSON 可序列化表示形式。

返回类型

Union[SerializedConstructor, SerializedNotImplemented]

property input_keys: List[str]

链输入中期望的键。

property output_keys: List[str]

链输出中期望的键。

使用 ArangoGraphQAChain 的示例