上下文#

class langchain_core.beta.runnables.context.Context[来源]#

可运行任务的上下文。

Context 类提供了用于在可运行对象中创建上下文范围、获取器和设置器的方法。它允许在程序执行过程中管理和访问上下文信息。

示例

from langchain_core.beta.runnables.context import Context
from langchain_core.runnables.passthrough import RunnablePassthrough
from langchain_core.prompts.prompt import PromptTemplate
from langchain_core.output_parsers.string import StrOutputParser
from tests.unit_tests.fake.llm import FakeListLLM

chain = (
    Context.setter("input")
    | {
        "context": RunnablePassthrough()
                | Context.setter("context"),
        "question": RunnablePassthrough(),
    }
    | PromptTemplate.from_template("{context} {question}")
    | FakeListLLM(responses=["hello"])
    | StrOutputParser()
    | {
        "result": RunnablePassthrough(),
        "context": Context.getter("context"),
        "input": Context.getter("input"),
    }
)

# Use the chain
output = chain.invoke("What's your name?")
print(output["result"])  # Output: "hello"
print(output["context"])  # Output: "What's your name?"
print(output["input"])  # Output: "What's your name?

方法

create_scope(scope, /)

创建一个上下文范围。

getter(key, /)

setter([_key, _value])

static create_scope(scope: str, /) PrefixContext[source]#

创建一个上下文范围。

Parameters:

scope (str) – 范围。

Returns:

上下文范围。

Return type:

PrefixContext

static getter(key: str | list[str], /) ContextGet[source]#
Parameters:

key (str | list[str])

Return type:

ContextGet

static setter(_key: str | None = None, _value: Runnable[Input, Output] | Callable[[Input], Output] | Callable[[Input], Awaitable[Output]] | Any | None = None, /, **kwargs: Runnable[Input, Output] | Callable[[Input], Output] | Callable[[Input], Awaitable[Output]] | Any) ContextSet[源代码]#
Parameters:
  • _key (str | None)

  • _value (Runnable[Input, Output] | Callable[[Input], Output] | Callable[[Input], Awaitable[Output]] | Any | None)

  • kwargs (Runnable[Input, Output] | Callable[[Input], Output] | Callable[[Input], Awaitable[Output]] | Any)

Return type:

ContextSet