mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-05 17:35:28 +03:00
fix: formatting issues in docstrings (#32265)
Ensures proper reStructuredText formatting by adding the required blank line before closing docstring quotes, which resolves the "Block quote ends without a blank line; unexpected unindent" warning.
This commit is contained in:
1 parent
a8a2cff129
commit
96cbd90cba
129 files changed
+234
-3
No files matched your search
@@ -61,6 +61,7 @@ class __ModuleName__Loader(BaseLoader):
|
||||
.. code-block:: python
|
||||
|
||||
TODO: Example output
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
# TODO: This method must be implemented to load documents.
|
||||
|
||||
@@ -61,6 +61,7 @@ class __ModuleName__Tool(BaseTool): # type: ignore[override]
|
||||
.. code-block:: python
|
||||
|
||||
# TODO: output of invocation
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
# TODO: Set tool name and description
|
||||
|
||||
@@ -70,6 +70,7 @@ def beta(
|
||||
@beta
|
||||
def the_function_to_annotate():
|
||||
pass
|
||||
|
||||
"""
|
||||
|
||||
def beta(
|
||||
|
||||
@@ -136,6 +136,7 @@ def deprecated(
|
||||
@deprecated('1.4.0')
|
||||
def the_function_to_deprecate():
|
||||
pass
|
||||
|
||||
"""
|
||||
_validate_deprecation_params(
|
||||
removal, alternative, alternative_import, pending=pending
|
||||
@@ -549,6 +550,7 @@ def rename_parameter(
|
||||
|
||||
@_api.rename_parameter("3.1", "bad_name", "good_name")
|
||||
def func(good_name): ...
|
||||
|
||||
"""
|
||||
|
||||
def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:
|
||||
|
||||
@@ -363,6 +363,7 @@ class Context:
|
||||
print(output["result"]) # Output: "hello"
|
||||
print(output["context"]) # Output: "What's your name?"
|
||||
print(output["input"]) # Output: "What's your name?
|
||||
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -53,6 +53,7 @@ class FileCallbackHandler(BaseCallbackHandler):
|
||||
When not used as a context manager, a deprecation warning will be issued
|
||||
on first use. The file will be opened immediately in ``__init__`` and closed
|
||||
in ``__del__`` or when ``close()`` is called explicitly.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -105,6 +105,7 @@ def trace_as_chain_group(
|
||||
# Use the callback manager for the chain group
|
||||
res = llm.invoke(llm_input, {"callbacks": manager})
|
||||
manager.on_chain_end({"output": res})
|
||||
|
||||
""" # noqa: E501
|
||||
from langchain_core.tracers.context import _get_trace_callbacks
|
||||
|
||||
@@ -186,6 +187,7 @@ async def atrace_as_chain_group(
|
||||
# Use the async callback manager for the chain group
|
||||
res = await llm.ainvoke(llm_input, {"callbacks": manager})
|
||||
await manager.on_chain_end({"output": res})
|
||||
|
||||
""" # noqa: E501
|
||||
from langchain_core.tracers.context import _get_trace_callbacks
|
||||
|
||||
@@ -2575,6 +2577,7 @@ async def adispatch_custom_event(
|
||||
behalf.
|
||||
|
||||
.. versionadded:: 0.2.15
|
||||
|
||||
"""
|
||||
from langchain_core.runnables.config import (
|
||||
ensure_config,
|
||||
@@ -2645,6 +2648,7 @@ def dispatch_custom_event(
|
||||
foo_.invoke({"a": "1"}, {"callbacks": [CustomCallbackManager()]})
|
||||
|
||||
.. versionadded:: 0.2.15
|
||||
|
||||
"""
|
||||
from langchain_core.runnables.config import (
|
||||
ensure_config,
|
||||
|
||||
@@ -44,6 +44,7 @@ class UsageMetadataCallbackHandler(BaseCallbackHandler):
|
||||
'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
|
||||
|
||||
.. versionadded:: 0.3.49
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
@@ -127,6 +128,7 @@ def get_usage_metadata_callback(
|
||||
'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
|
||||
|
||||
.. versionadded:: 0.3.49
|
||||
|
||||
"""
|
||||
from langchain_core.tracers.context import register_configure_hook
|
||||
|
||||
|
||||
@@ -91,6 +91,7 @@ class BaseChatMessageHistory(ABC):
|
||||
def clear(self):
|
||||
with open(os.path.join(storage_path, session_id), "w") as f:
|
||||
f.write("[]")
|
||||
|
||||
"""
|
||||
|
||||
messages: list[BaseMessage]
|
||||
|
||||
@@ -36,6 +36,7 @@ class LangSmithLoader(BaseLoader):
|
||||
# -> [Document("...", metadata={"inputs": {...}, "outputs": {...}, ...}), ...]
|
||||
|
||||
.. versionadded:: 0.2.34
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -102,6 +102,7 @@ class Blob(BaseMedia):
|
||||
# Read the blob as a byte stream
|
||||
with blob.as_bytes_io() as f:
|
||||
print(f.read())
|
||||
|
||||
"""
|
||||
|
||||
data: Union[bytes, str, None] = None
|
||||
@@ -265,6 +266,7 @@ class Document(BaseMedia):
|
||||
page_content="Hello, world!",
|
||||
metadata={"source": "https://example.com"}
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
page_content: str
|
||||
|
||||
@@ -46,6 +46,7 @@ class FakeEmbeddings(Embeddings, BaseModel):
|
||||
|
||||
2
|
||||
[-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
|
||||
|
||||
"""
|
||||
|
||||
size: int
|
||||
@@ -103,6 +104,7 @@ class DeterministicFakeEmbedding(Embeddings, BaseModel):
|
||||
|
||||
2
|
||||
[-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
|
||||
|
||||
"""
|
||||
|
||||
size: int
|
||||
|
||||
@@ -51,6 +51,7 @@ def _parse_data_uri(uri: str) -> Optional[dict]:
|
||||
"mime_type": "image/jpeg",
|
||||
"data": "/9j/4AAQSkZJRg...",
|
||||
}
|
||||
|
||||
"""
|
||||
regex = r"^data:(?P<mime_type>[^;]+);base64,(?P<data>.+)$"
|
||||
match = re.match(regex, uri)
|
||||
|
||||
@@ -1467,6 +1467,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
|
||||
.. versionchanged:: 0.2.26
|
||||
|
||||
Added support for TypedDict class.
|
||||
|
||||
""" # noqa: E501
|
||||
_ = kwargs.pop("method", None)
|
||||
_ = kwargs.pop("strict", None)
|
||||
|
||||
@@ -1418,6 +1418,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
|
||||
.. code-block:: python
|
||||
|
||||
llm.save(file_path="path/llm.yaml")
|
||||
|
||||
"""
|
||||
# Convert file to Path object.
|
||||
save_path = Path(file_path)
|
||||
|
||||
@@ -53,6 +53,7 @@ class BaseMemory(Serializable, ABC):
|
||||
|
||||
def clear(self) -> None:
|
||||
pass
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
model_config = ConfigDict(
|
||||
|
||||
@@ -57,6 +57,7 @@ class InputTokenDetails(TypedDict, total=False):
|
||||
.. versionadded:: 0.3.9
|
||||
|
||||
May also hold extra provider-specific keys.
|
||||
|
||||
"""
|
||||
|
||||
audio: int
|
||||
@@ -89,6 +90,7 @@ class OutputTokenDetails(TypedDict, total=False):
|
||||
}
|
||||
|
||||
.. versionadded:: 0.3.9
|
||||
|
||||
"""
|
||||
|
||||
audio: int
|
||||
@@ -128,6 +130,7 @@ class UsageMetadata(TypedDict):
|
||||
.. versionchanged:: 0.3.9
|
||||
|
||||
Added ``input_token_details`` and ``output_token_details``.
|
||||
|
||||
"""
|
||||
|
||||
input_tokens: int
|
||||
|
||||
@@ -28,6 +28,7 @@ class HumanMessage(BaseMessage):
|
||||
# Instantiate a chat model and invoke it with the messages
|
||||
model = ...
|
||||
print(model.invoke(messages))
|
||||
|
||||
"""
|
||||
|
||||
example: bool = False
|
||||
|
||||
@@ -59,6 +59,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
|
||||
The tool_call_id field is used to associate the tool call request with the
|
||||
tool call response. This is useful in situations where a chat model is able
|
||||
to request multiple tool calls in parallel.
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
tool_call_id: str
|
||||
@@ -191,6 +192,7 @@ class ToolCall(TypedDict):
|
||||
|
||||
This represents a request to call the tool named "foo" with arguments {"a": 1}
|
||||
and an identifier of "123".
|
||||
|
||||
"""
|
||||
|
||||
name: str
|
||||
@@ -240,6 +242,7 @@ class ToolCallChunk(TypedDict):
|
||||
AIMessageChunk(content="", tool_call_chunks=left_chunks)
|
||||
+ AIMessageChunk(content="", tool_call_chunks=right_chunks)
|
||||
).tool_call_chunks == [ToolCallChunk(name='foo', args='{"a":1}', index=0)]
|
||||
|
||||
"""
|
||||
|
||||
name: Optional[str]
|
||||
|
||||
@@ -111,6 +111,7 @@ def get_buffer_string(
|
||||
]
|
||||
get_buffer_string(messages)
|
||||
# -> "Human: Hi, how are you?\nAI: Good, how are you?"
|
||||
|
||||
"""
|
||||
string_messages = []
|
||||
for m in messages:
|
||||
@@ -463,6 +464,7 @@ def filter_messages(
|
||||
SystemMessage("you're a good assistant."),
|
||||
HumanMessage("what's your name", id="foo", name="example_user"),
|
||||
]
|
||||
|
||||
""" # noqa: E501
|
||||
messages = convert_to_messages(messages)
|
||||
filtered: list[BaseMessage] = []
|
||||
@@ -869,6 +871,7 @@ def trim_messages(
|
||||
HumanMessage("This is a 4 token text. The full message is 10 tokens.", id="first"),
|
||||
AIMessage( [{"type": "text", "text": "This is the FIRST 4 token block."}], id="second"),
|
||||
]
|
||||
|
||||
""" # noqa: E501
|
||||
# Validate arguments
|
||||
if start_on and strategy == "first":
|
||||
|
||||
@@ -155,6 +155,7 @@ class BaseOutputParser(
|
||||
@property
|
||||
def _type(self) -> str:
|
||||
return "boolean_output_parser"
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
@property
|
||||
|
||||
@@ -214,6 +214,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):
|
||||
pydantic_schema={"cookie": Cookie, "dog": Dog}
|
||||
)
|
||||
result = parser.parse_result([chat_generation])
|
||||
|
||||
"""
|
||||
|
||||
pydantic_schema: Union[type[BaseModel], dict[str, type[BaseModel]]]
|
||||
|
||||
@@ -307,6 +307,7 @@ class BasePromptTemplate(
|
||||
.. code-block:: python
|
||||
|
||||
prompt.format(variable1="foo")
|
||||
|
||||
"""
|
||||
|
||||
async def aformat(self, **kwargs: Any) -> FormatOutputType:
|
||||
@@ -323,6 +324,7 @@ class BasePromptTemplate(
|
||||
.. code-block:: python
|
||||
|
||||
await prompt.aformat(variable1="foo")
|
||||
|
||||
"""
|
||||
return self.format(**kwargs)
|
||||
|
||||
@@ -363,6 +365,7 @@ class BasePromptTemplate(
|
||||
.. code-block:: python
|
||||
|
||||
prompt.save(file_path="path/prompt.yaml")
|
||||
|
||||
"""
|
||||
if self.partial_variables:
|
||||
msg = "Cannot save prompt with partial variables."
|
||||
@@ -442,6 +445,7 @@ def format_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
|
||||
prompt = PromptTemplate.from_template("Page {page}: {page_content}")
|
||||
format_document(doc, prompt)
|
||||
>>> "Page 1: This is a joke"
|
||||
|
||||
"""
|
||||
return prompt.format(**_get_document_info(doc, prompt))
|
||||
|
||||
|
||||
@@ -126,6 +126,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
|
||||
# -> [
|
||||
# HumanMessage(content="Hello!"),
|
||||
# ]
|
||||
|
||||
"""
|
||||
|
||||
variable_name: str
|
||||
@@ -1164,6 +1165,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
|
||||
Returns:
|
||||
a chat prompt template.
|
||||
|
||||
"""
|
||||
return cls(messages, template_format=template_format)
|
||||
|
||||
@@ -1248,6 +1250,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
|
||||
template2 = template.partial(user="Lucy", name="R2D2")
|
||||
|
||||
template2.format_messages(input="hello")
|
||||
|
||||
"""
|
||||
prompt_dict = self.__dict__.copy()
|
||||
prompt_dict["input_variables"] = list(
|
||||
|
||||
@@ -357,6 +357,7 @@ class FewShotChatMessagePromptTemplate(
|
||||
from langchain_core.chat_models import ChatAnthropic
|
||||
chain = final_prompt | ChatAnthropic(model="claude-3-haiku-20240307")
|
||||
chain.invoke({"input": "What's 3+3?"})
|
||||
|
||||
"""
|
||||
|
||||
input_variables: list[str] = Field(default_factory=list)
|
||||
|
||||
@@ -122,6 +122,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
|
||||
.. code-block:: python
|
||||
|
||||
prompt.format(variable1="foo")
|
||||
|
||||
"""
|
||||
kwargs = self._merge_partial_and_user_variables(**kwargs)
|
||||
# Get the examples to use.
|
||||
|
||||
@@ -90,6 +90,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
|
||||
.. code-block:: python
|
||||
|
||||
prompt.format(variable1="foo")
|
||||
|
||||
"""
|
||||
formatted = {}
|
||||
for k, v in self.template.items():
|
||||
|
||||
@@ -45,6 +45,7 @@ class PipelinePromptTemplate(BasePromptTemplate):
|
||||
Each PromptTemplate will be formatted and then passed
|
||||
to future prompt templates as a variable with
|
||||
the same name as `name`
|
||||
|
||||
"""
|
||||
|
||||
final_prompt: BasePromptTemplate
|
||||
|
||||
@@ -56,6 +56,7 @@ class PromptTemplate(StringPromptTemplate):
|
||||
|
||||
# Instantiation using initializer
|
||||
prompt = PromptTemplate(template="Say {foo}")
|
||||
|
||||
"""
|
||||
|
||||
@property
|
||||
|
||||
@@ -115,6 +115,7 @@ class StructuredPrompt(ChatPromptTemplate):
|
||||
|
||||
Returns:
|
||||
a structured prompt template
|
||||
|
||||
"""
|
||||
return cls(messages, schema, **kwargs)
|
||||
|
||||
|
||||
@@ -123,6 +123,7 @@ class InMemoryRateLimiter(BaseRateLimiter):
|
||||
|
||||
|
||||
.. versionadded:: 0.2.24
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -124,6 +124,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
|
||||
# Op -- (n_docs,1) -- Cosine Sim with each doc
|
||||
results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))
|
||||
return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
model_config = ConfigDict(
|
||||
@@ -230,6 +231,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
|
||||
.. code-block:: python
|
||||
|
||||
retriever.invoke("query")
|
||||
|
||||
"""
|
||||
from langchain_core.callbacks.manager import CallbackManager
|
||||
|
||||
@@ -294,6 +296,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
|
||||
.. code-block:: python
|
||||
|
||||
await retriever.ainvoke("query")
|
||||
|
||||
"""
|
||||
from langchain_core.callbacks.manager import AsyncCallbackManager
|
||||
|
||||
|
||||
@@ -236,6 +236,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
)
|
||||
|
||||
For a UI (and much more) checkout LangSmith: https://docs.smith.langchain.com/
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
name: Optional[str]
|
||||
@@ -391,6 +392,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
print(runnable.get_input_jsonschema())
|
||||
|
||||
.. versionadded:: 0.3.0
|
||||
|
||||
"""
|
||||
return self.get_input_schema(config).model_json_schema()
|
||||
|
||||
@@ -464,6 +466,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
print(runnable.get_output_jsonschema())
|
||||
|
||||
.. versionadded:: 0.3.0
|
||||
|
||||
"""
|
||||
return self.get_output_schema(config).model_json_schema()
|
||||
|
||||
@@ -620,6 +623,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
sequence.batch([1, 2, 3])
|
||||
await sequence.abatch([1, 2, 3])
|
||||
# -> [4, 6, 8]
|
||||
|
||||
"""
|
||||
return RunnableSequence(self, *others, name=name)
|
||||
|
||||
@@ -1361,6 +1365,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
|
||||
Raises:
|
||||
NotImplementedError: If the version is not `v1` or `v2`.
|
||||
|
||||
""" # noqa: E501
|
||||
from langchain_core.tracers.event_stream import (
|
||||
_astream_events_implementation_v1,
|
||||
@@ -1607,6 +1612,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
on_end=fn_end
|
||||
)
|
||||
chain.invoke(2)
|
||||
|
||||
"""
|
||||
from langchain_core.tracers.root_listeners import RootListenersTracer
|
||||
|
||||
@@ -1825,6 +1831,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
|
||||
runnable = RunnableLambda(_lambda)
|
||||
print(runnable.map().invoke([1, 2, 3])) # [2, 3, 4]
|
||||
|
||||
"""
|
||||
return RunnableEach(bound=self)
|
||||
|
||||
@@ -2446,6 +2453,7 @@ class Runnable(ABC, Generic[Input, Output]):
|
||||
as_tool.invoke("b")
|
||||
|
||||
.. versionadded:: 0.2.14
|
||||
|
||||
"""
|
||||
# Avoid circular import
|
||||
from langchain_core.tools import convert_runnable_to_tool
|
||||
@@ -2517,6 +2525,7 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
|
||||
configurable={"output_token_number": 200}
|
||||
).invoke("tell me something about chess").content
|
||||
)
|
||||
|
||||
"""
|
||||
from langchain_core.runnables.configurable import RunnableConfigurableFields
|
||||
|
||||
@@ -2577,6 +2586,7 @@ class RunnableSerializable(Serializable, Runnable[Input, Output]):
|
||||
configurable={"llm": "openai"}
|
||||
).invoke("which organization created you?").content
|
||||
)
|
||||
|
||||
"""
|
||||
from langchain_core.runnables.configurable import (
|
||||
RunnableConfigurableAlternatives,
|
||||
@@ -2741,6 +2751,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
|
||||
async for chunk in chain.astream({'topic': 'colors'}):
|
||||
print('-') # noqa: T201
|
||||
print(chunk, sep='', flush=True) # noqa: T201
|
||||
|
||||
"""
|
||||
|
||||
# The steps are broken into first, middle and last, solely for type checking
|
||||
@@ -3539,6 +3550,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
|
||||
for key in chunk:
|
||||
output[key] = output[key] + chunk[key].content
|
||||
print(output) # noqa: T201
|
||||
|
||||
"""
|
||||
|
||||
steps__: Mapping[str, Runnable[Input, Any]]
|
||||
@@ -4061,6 +4073,7 @@ class RunnableGenerator(Runnable[Input, Output]):
|
||||
|
||||
runnable = chant_chain | RunnableLambda(reverse_generator)
|
||||
"".join(runnable.stream({"topic": "waste"})) # ".elcycer ,esuer ,ecudeR"
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -4321,6 +4334,7 @@ class RunnableLambda(Runnable[Input, Output]):
|
||||
runnable = RunnableLambda(add_one, afunc=add_one_async)
|
||||
runnable.invoke(1) # Uses add_one
|
||||
await runnable.ainvoke(1) # Uses add_one_async
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -5175,6 +5189,7 @@ class RunnableEach(RunnableEachBase[Input, Output]):
|
||||
{'topic':'Art'},
|
||||
{'topic':'Biology'}])
|
||||
print(output) # noqa: T201
|
||||
|
||||
"""
|
||||
|
||||
@override
|
||||
@@ -5709,6 +5724,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
|
||||
kwargs={'stop': ['-']} # <-- Note the additional kwargs
|
||||
)
|
||||
runnable_binding.invoke('Say "Parrot-MAGIC"') # Should return `Parrot`
|
||||
|
||||
"""
|
||||
|
||||
@override
|
||||
@@ -5989,5 +6005,6 @@ def chain(
|
||||
|
||||
for chunk in llm.stream(formatted):
|
||||
yield chunk
|
||||
|
||||
"""
|
||||
return RunnableLambda(func)
|
||||
@@ -63,6 +63,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
|
||||
|
||||
branch.invoke("hello") # "HELLO"
|
||||
branch.invoke(None) # "goodbye"
|
||||
|
||||
"""
|
||||
|
||||
branches: Sequence[tuple[Runnable[Input, bool], Runnable[Input, Output]]]
|
||||
|
||||
@@ -378,6 +378,7 @@ class RunnableConfigurableFields(DynamicRunnable[Input, Output]):
|
||||
{"question": "foo", "context": "bar"},
|
||||
config={"configurable": {"hub_commit": "rlm/rag-prompt-llama"}},
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
fields: dict[str, AnyConfigurableField]
|
||||
|
||||
@@ -85,6 +85,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
|
||||
| model
|
||||
| StrOutputParser()
|
||||
).with_fallbacks([RunnableLambda(when_all_is_lost)])
|
||||
|
||||
"""
|
||||
|
||||
runnable: Runnable[Input, Output]
|
||||
|
||||
@@ -611,6 +611,7 @@ class Graph:
|
||||
|
||||
Returns:
|
||||
The Mermaid syntax string.
|
||||
|
||||
"""
|
||||
from langchain_core.runnables.graph_mermaid import draw_mermaid
|
||||
|
||||
@@ -681,6 +682,7 @@ class Graph:
|
||||
|
||||
Returns:
|
||||
The PNG image as bytes.
|
||||
|
||||
"""
|
||||
from langchain_core.runnables.graph_mermaid import draw_mermaid_png
|
||||
|
||||
|
||||
@@ -263,6 +263,7 @@ def draw_ascii(vertices: Mapping[str, str], edges: Sequence[LangEdge]) -> str:
|
||||
+---+ +---+
|
||||
| 3 | | 4 |
|
||||
+---+ +---+
|
||||
|
||||
"""
|
||||
# NOTE: coordinates might me negative, so we need to shift
|
||||
# everything to the positive plane before we actually draw it.
|
||||
|
||||
@@ -70,6 +70,7 @@ def draw_mermaid(
|
||||
|
||||
Returns:
|
||||
str: Mermaid graph syntax.
|
||||
|
||||
"""
|
||||
# Initialize Mermaid graph configuration
|
||||
original_frontmatter_config = frontmatter_config or {}
|
||||
|
||||
@@ -311,6 +311,7 @@ class RunnableWithMessageHistory(RunnableBindingBase):
|
||||
into the get_session_history factory.
|
||||
**kwargs: Arbitrary additional kwargs to pass to parent class
|
||||
``RunnableBindingBase`` init.
|
||||
|
||||
"""
|
||||
history_chain: Runnable = RunnableLambda(
|
||||
self._enter_history, self._aenter_history
|
||||
|
||||
@@ -132,6 +132,7 @@ class RunnablePassthrough(RunnableSerializable[Other, Other]):
|
||||
|
||||
runnable.invoke('hello')
|
||||
# {'llm1': 'completion', 'llm2': 'completion', 'total_chars': 20}
|
||||
|
||||
"""
|
||||
|
||||
input_type: Optional[type[Other]] = None
|
||||
@@ -393,6 +394,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
|
||||
# Asynchronous example
|
||||
await runnable_assign.ainvoke({"input": 5})
|
||||
# returns {'input': 5, 'add_step': {'added': 15}}
|
||||
|
||||
"""
|
||||
|
||||
mapper: RunnableParallel
|
||||
@@ -697,6 +699,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
|
||||
output_data = runnable.invoke(input_data)
|
||||
|
||||
print(output_data) # Output: {'name': 'John', 'age': 30}
|
||||
|
||||
"""
|
||||
|
||||
keys: Union[str, list[str]]
|
||||
|
||||
@@ -110,6 +110,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
|
||||
# Bad
|
||||
chain = template | model
|
||||
retryable_chain = chain.with_retry()
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
retry_exception_types: tuple[type[BaseException], ...] = (Exception,)
|
||||
|
||||
@@ -66,6 +66,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
|
||||
|
||||
router = RouterRunnable(runnables={"add": add, "square": square})
|
||||
router.invoke({"key": "square", "input": 3})
|
||||
|
||||
"""
|
||||
|
||||
runnables: Mapping[str, Runnable[Any, Output]]
|
||||
|
||||
@@ -83,6 +83,7 @@ class BaseStreamEvent(TypedDict):
|
||||
"tags": [],
|
||||
},
|
||||
]
|
||||
|
||||
"""
|
||||
|
||||
event: str
|
||||
|
||||
@@ -76,6 +76,7 @@ class BaseStore(ABC, Generic[K, V]):
|
||||
for key in self.store.keys():
|
||||
if key.startswith(prefix):
|
||||
yield key
|
||||
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
@@ -302,6 +303,7 @@ class InMemoryStore(InMemoryBaseStore[Any]):
|
||||
# ['key2']
|
||||
list(store.yield_keys(prefix='k'))
|
||||
# ['key2']
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@@ -327,6 +329,7 @@ class InMemoryByteStore(InMemoryBaseStore[bytes]):
|
||||
# ['key2']
|
||||
list(store.yield_keys(prefix='k'))
|
||||
# ['key2']
|
||||
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -1273,6 +1273,7 @@ class InjectedToolCallId(InjectedToolArg):
|
||||
name="foo",
|
||||
tool_call_id=tool_call_id
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
|
||||
|
||||
@@ -215,6 +215,7 @@ def tool(
|
||||
monkey: The baz.
|
||||
\"\"\"
|
||||
return bar
|
||||
|
||||
""" # noqa: D214, D410, D411
|
||||
|
||||
def _create_tool_factory(
|
||||
|
||||
@@ -174,6 +174,7 @@ class StructuredTool(BaseTool):
|
||||
return a + b
|
||||
tool = StructuredTool.from_function(add)
|
||||
tool.run(1, 2) # 3
|
||||
|
||||
"""
|
||||
if func is not None:
|
||||
source_function = func
|
||||
|
||||
@@ -189,6 +189,7 @@ class Tee(Generic[T]):
|
||||
To enforce sequential use of ``anext``, provide a ``lock``
|
||||
- e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -
|
||||
and access is automatically synchronised.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -280,6 +281,7 @@ class aclosing(AbstractAsyncContextManager): # noqa: N801
|
||||
<block>
|
||||
finally:
|
||||
await agen.aclose()
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -687,6 +687,7 @@ def tool_example_to_messages(
|
||||
messages.extend(
|
||||
tool_example_to_messages(txt, [tool_call])
|
||||
)
|
||||
|
||||
"""
|
||||
messages: list[BaseMessage] = [HumanMessage(content=input)]
|
||||
openai_tool_calls = [
|
||||
|
||||
@@ -126,6 +126,7 @@ class Tee(Generic[T]):
|
||||
To enforce sequential use of ``anext``, provide a ``lock``
|
||||
- e.g. an :py:class:`asyncio.Lock` instance in an :py:mod:`asyncio` application -
|
||||
and access is automatically synchronised.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -994,6 +994,7 @@ class VectorStore(ABC):
|
||||
docsearch.as_retriever(
|
||||
search_kwargs={'filter': {'paper_title':'GPT-4 Technical Report'}}
|
||||
)
|
||||
|
||||
"""
|
||||
tags = kwargs.pop("tags", None) or [*self._get_retriever_tags()]
|
||||
return VectorStoreRetriever(vectorstore=self, tags=tags, **kwargs)
|
||||
|
||||
@@ -66,6 +66,7 @@ def pytest_collection_modifyitems(
|
||||
@pytest.mark.requires("package1", "package2")
|
||||
def test_something():
|
||||
...
|
||||
|
||||
"""
|
||||
# Mapping from the name of a package to whether it is installed or not.
|
||||
# Used to avoid repeated calls to `util.find_spec`
|
||||
|
||||
@@ -196,6 +196,7 @@ class BaseSingleActionAgent(BaseModel):
|
||||
|
||||
# If working with agent executor
|
||||
agent.agent.save(file_path="path/agent.yaml")
|
||||
|
||||
"""
|
||||
# Convert file to Path object.
|
||||
save_path = Path(file_path) if isinstance(file_path, str) else file_path
|
||||
@@ -339,6 +340,7 @@ class BaseMultiActionAgent(BaseModel):
|
||||
|
||||
# If working with agent executor
|
||||
agent.agent.save(file_path="path/agent.yaml")
|
||||
|
||||
"""
|
||||
# Convert file to Path object.
|
||||
save_path = Path(file_path) if isinstance(file_path, str) else file_path
|
||||
|
||||
@@ -90,6 +90,7 @@ def create_vectorstore_agent(
|
||||
|
||||
Returns:
|
||||
AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response
|
||||
|
||||
""" # noqa: E501
|
||||
tools = toolkit.get_tools()
|
||||
prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)
|
||||
@@ -198,6 +199,7 @@ def create_vectorstore_router_agent(
|
||||
|
||||
Returns:
|
||||
AgentExecutor: Returns a callable AgentExecutor object. Either you can call it or use run method with the query to get the response.
|
||||
|
||||
""" # noqa: E501
|
||||
tools = toolkit.get_tools()
|
||||
prompt = ZeroShotAgent.create_prompt(tools, prefix=prefix)
|
||||
|
||||
@@ -160,6 +160,7 @@ def create_json_chat_agent(
|
||||
MessagesPlaceholder("agent_scratchpad"),
|
||||
]
|
||||
)
|
||||
|
||||
""" # noqa: E501
|
||||
missing_vars = {"tools", "tool_names", "agent_scratchpad"}.difference(
|
||||
prompt.input_variables + list(prompt.partial_variables),
|
||||
|
||||
@@ -359,6 +359,7 @@ def create_openai_functions_agent(
|
||||
MessagesPlaceholder("agent_scratchpad"),
|
||||
]
|
||||
)
|
||||
|
||||
"""
|
||||
if "agent_scratchpad" not in (
|
||||
prompt.input_variables + list(prompt.partial_variables)
|
||||
|
||||
@@ -84,6 +84,7 @@ def create_openai_tools_agent(
|
||||
MessagesPlaceholder("agent_scratchpad"),
|
||||
]
|
||||
)
|
||||
|
||||
"""
|
||||
missing_vars = {"agent_scratchpad"}.difference(
|
||||
prompt.input_variables + list(prompt.partial_variables),
|
||||
|
||||
@@ -116,6 +116,7 @@ def create_react_agent(
|
||||
Thought:{agent_scratchpad}'''
|
||||
|
||||
prompt = PromptTemplate.from_template(template)
|
||||
|
||||
""" # noqa: E501
|
||||
missing_vars = {"tools", "tool_names", "agent_scratchpad"}.difference(
|
||||
prompt.input_variables + list(prompt.partial_variables),
|
||||
|
||||
@@ -185,6 +185,7 @@ def create_self_ask_with_search_agent(
|
||||
Are followup questions needed here:{agent_scratchpad}'''
|
||||
|
||||
prompt = PromptTemplate.from_template(template)
|
||||
|
||||
""" # noqa: E501
|
||||
missing_vars = {"agent_scratchpad"}.difference(
|
||||
prompt.input_variables + list(prompt.partial_variables),
|
||||
|
||||
@@ -280,6 +280,7 @@ def create_structured_chat_agent(
|
||||
("human", human),
|
||||
]
|
||||
)
|
||||
|
||||
""" # noqa: E501
|
||||
missing_vars = {"tools", "tool_names", "agent_scratchpad"}.difference(
|
||||
prompt.input_variables + list(prompt.partial_variables),
|
||||
|
||||
@@ -85,6 +85,7 @@ def create_tool_calling_agent(
|
||||
The agent prompt must have an `agent_scratchpad` key that is a
|
||||
``MessagesPlaceholder``. Intermediate agent actions and tool output
|
||||
messages will be passed in here.
|
||||
|
||||
"""
|
||||
missing_vars = {"agent_scratchpad"}.difference(
|
||||
prompt.input_variables + list(prompt.partial_variables),
|
||||
|
||||
@@ -37,7 +37,6 @@ class XMLAgent(BaseSingleActionAgent):
|
||||
tools = ...
|
||||
model =
|
||||
|
||||
|
||||
"""
|
||||
|
||||
tools: list[BaseTool]
|
||||
@@ -209,6 +208,7 @@ def create_xml_agent(
|
||||
Question: {input}
|
||||
{agent_scratchpad}'''
|
||||
prompt = PromptTemplate.from_template(template)
|
||||
|
||||
""" # noqa: E501
|
||||
missing_vars = {"tools", "agent_scratchpad"}.difference(
|
||||
prompt.input_variables + list(prompt.partial_variables),
|
||||
|
||||
@@ -191,6 +191,7 @@ try:
|
||||
)
|
||||
async for event in events:
|
||||
event["messages"][-1].pretty_print()
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
api_request_chain: LLMChain
|
||||
|
||||
@@ -618,6 +618,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
|
||||
context = "Weather report for Boise, Idaho on 07/03/23..."
|
||||
chain.run(question=question, context=context)
|
||||
# -> "The temperature in Boise is..."
|
||||
|
||||
"""
|
||||
# Run at start to make sure this is possible/defined
|
||||
_output_key = self._run_output_key
|
||||
@@ -692,6 +693,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
|
||||
context = "Weather report for Boise, Idaho on 07/03/23..."
|
||||
await chain.arun(question=question, context=context)
|
||||
# -> "The temperature in Boise is..."
|
||||
|
||||
"""
|
||||
if len(self.output_keys) != 1:
|
||||
msg = (
|
||||
@@ -746,6 +748,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
|
||||
|
||||
chain.dict(exclude_unset=True)
|
||||
# -> {"_type": "foo", "verbose": False, ...}
|
||||
|
||||
"""
|
||||
_dict = super().dict(**kwargs)
|
||||
with contextlib.suppress(NotImplementedError):
|
||||
@@ -765,6 +768,7 @@ class Chain(RunnableSerializable[dict[str, Any], dict[str, Any]], ABC):
|
||||
.. code-block:: python
|
||||
|
||||
chain.save(file_path="path/chain.yaml")
|
||||
|
||||
"""
|
||||
if self.memory is not None:
|
||||
msg = "Saving of memory is not yet supported."
|
||||
|
||||
@@ -234,6 +234,7 @@ class AnalyzeDocumentChain(Chain):
|
||||
input_documents=itemgetter("input_document") | split_text,
|
||||
) | chain.pick("output_text")
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
input_key: str = "input_document" #: :meta private:
|
||||
|
||||
@@ -99,6 +99,7 @@ class MapReduceDocumentsChain(BaseCombineDocumentsChain):
|
||||
llm_chain=llm_chain,
|
||||
reduce_documents_chain=reduce_documents_chain,
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
llm_chain: LLMChain
|
||||
|
||||
@@ -69,6 +69,7 @@ class MapRerankDocumentsChain(BaseCombineDocumentsChain):
|
||||
rank_key="score",
|
||||
answer_key="answer",
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
llm_chain: LLMChain
|
||||
|
||||
@@ -201,6 +201,7 @@ class ReduceDocumentsChain(BaseCombineDocumentsChain):
|
||||
combine_documents_chain=combine_documents_chain,
|
||||
collapse_documents_chain=collapse_documents_chain,
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
combine_documents_chain: BaseCombineDocumentsChain
|
||||
|
||||
@@ -79,6 +79,7 @@ class RefineDocumentsChain(BaseCombineDocumentsChain):
|
||||
document_variable_name=document_variable_name,
|
||||
initial_response_name=initial_response_name,
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
initial_llm_chain: LLMChain
|
||||
|
||||
@@ -75,6 +75,7 @@ def create_stuff_documents_chain(
|
||||
]
|
||||
|
||||
chain.invoke({"context": docs})
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
_validate_prompt(prompt, document_variable_name)
|
||||
@@ -142,6 +143,7 @@ class StuffDocumentsChain(BaseCombineDocumentsChain):
|
||||
document_prompt=document_prompt,
|
||||
document_variable_name=document_variable_name
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
llm_chain: LLMChain
|
||||
|
||||
@@ -187,6 +187,7 @@ class ConstitutionalChain(Chain):
|
||||
)
|
||||
|
||||
constitutional_chain.run(question="What is the meaning of life?")
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
chain: LLMChain
|
||||
|
||||
@@ -97,6 +97,7 @@ class ConversationChain(LLMChain):
|
||||
from langchain_community.llms import OpenAI
|
||||
|
||||
conversation = ConversationChain(llm=OpenAI())
|
||||
|
||||
"""
|
||||
|
||||
memory: BaseMemory = Field(default_factory=ConversationBufferMemory)
|
||||
|
||||
@@ -374,6 +374,7 @@ class ConversationalRetrievalChain(BaseConversationalRetrievalChain):
|
||||
retriever=retriever,
|
||||
question_generator=question_generator_chain,
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
retriever: BaseRetriever
|
||||
|
||||
@@ -34,6 +34,7 @@ class ElasticsearchDatabaseChain(Chain):
|
||||
|
||||
database = Elasticsearch("http://localhost:9200")
|
||||
db_chain = ElasticsearchDatabaseChain.from_llm(OpenAI(), database)
|
||||
|
||||
"""
|
||||
|
||||
query_chain: Runnable
|
||||
|
||||
@@ -74,6 +74,7 @@ class LLMChain(Chain):
|
||||
input_variables=["adjective"], template=prompt_template
|
||||
)
|
||||
llm = LLMChain(llm=OpenAI(), prompt=prompt)
|
||||
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
@@ -323,6 +324,7 @@ class LLMChain(Chain):
|
||||
.. code-block:: python
|
||||
|
||||
completion = llm.predict(adjective="funny")
|
||||
|
||||
"""
|
||||
return self(kwargs, callbacks=callbacks)[self.output_key]
|
||||
|
||||
@@ -340,6 +342,7 @@ class LLMChain(Chain):
|
||||
.. code-block:: python
|
||||
|
||||
completion = llm.predict(adjective="funny")
|
||||
|
||||
"""
|
||||
return (await self.acall(kwargs, callbacks=callbacks))[self.output_key]
|
||||
|
||||
|
||||
@@ -82,6 +82,7 @@ class LLMCheckerChain(Chain):
|
||||
from langchain.chains import LLMCheckerChain
|
||||
llm = OpenAI(temperature=0.7)
|
||||
checker_chain = LLMCheckerChain.from_llm(llm)
|
||||
|
||||
"""
|
||||
|
||||
question_to_checked_assertions_chain: SequentialChain
|
||||
|
||||
@@ -146,6 +146,7 @@ class LLMMathChain(Chain):
|
||||
from langchain.chains import LLMMathChain
|
||||
from langchain_community.llms import OpenAI
|
||||
llm_math = LLMMathChain.from_llm(OpenAI())
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
llm_chain: LLMChain
|
||||
|
||||
@@ -85,6 +85,7 @@ class LLMSummarizationCheckerChain(Chain):
|
||||
from langchain.chains import LLMSummarizationCheckerChain
|
||||
llm = OpenAI(temperature=0.0)
|
||||
checker_chain = LLMSummarizationCheckerChain.from_llm(llm)
|
||||
|
||||
"""
|
||||
|
||||
sequential_chain: SequentialChain
|
||||
|
||||
@@ -27,6 +27,7 @@ class OpenAIModerationChain(Chain):
|
||||
|
||||
from langchain.chains import OpenAIModerationChain
|
||||
moderation = OpenAIModerationChain()
|
||||
|
||||
"""
|
||||
|
||||
client: Any = None #: :meta private:
|
||||
|
||||
@@ -47,6 +47,7 @@ class NatBotChain(Chain):
|
||||
|
||||
from langchain.chains import NatBotChain
|
||||
natbot = NatBotChain.from_default("Buy me a new hat.")
|
||||
|
||||
"""
|
||||
|
||||
llm_chain: Runnable
|
||||
@@ -151,6 +152,7 @@ class NatBotChain(Chain):
|
||||
|
||||
browser_content = "...."
|
||||
llm_command = natbot.run("www.google.com", browser_content)
|
||||
|
||||
"""
|
||||
_inputs = {
|
||||
self.input_url_key: url,
|
||||
|
||||
@@ -121,6 +121,7 @@ def create_openai_fn_chain(
|
||||
chain = create_openai_fn_chain([RecordPerson, RecordDog], llm, prompt)
|
||||
chain.run("Harry was a chubby brown beagle who loved chicken")
|
||||
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
|
||||
|
||||
""" # noqa: E501
|
||||
if not functions:
|
||||
msg = "Need to pass in at least one function. Received zero."
|
||||
@@ -203,6 +204,7 @@ def create_structured_output_chain(
|
||||
chain = create_structured_output_chain(Dog, llm, prompt)
|
||||
chain.run("Harry was a chubby brown beagle who loved chicken")
|
||||
# -> Dog(name="Harry", color="brown", fav_food="chicken")
|
||||
|
||||
""" # noqa: E501
|
||||
if isinstance(output_schema, dict):
|
||||
function: Any = {
|
||||
|
||||
@@ -94,6 +94,7 @@ def create_citation_fuzzy_match_runnable(llm: BaseChatModel) -> Runnable:
|
||||
|
||||
Returns:
|
||||
Runnable that can be used to answer questions with citations.
|
||||
|
||||
"""
|
||||
if llm.bind_tools is BaseChatModel.bind_tools:
|
||||
msg = "Language model must implement bind_tools to use this function."
|
||||
|
||||
@@ -345,6 +345,7 @@ def get_openapi_chain(
|
||||
`ChatOpenAI(model="gpt-3.5-turbo-0613")`.
|
||||
prompt: Main prompt template to use.
|
||||
request_chain: Chain for taking the functions output and executing the request.
|
||||
|
||||
""" # noqa: E501
|
||||
try:
|
||||
from langchain_community.utilities.openapi import OpenAPISpec
|
||||
|
||||
@@ -86,6 +86,7 @@ def create_tagging_chain(
|
||||
|
||||
Returns:
|
||||
Chain (LLMChain) that can be used to extract information from a passage.
|
||||
|
||||
"""
|
||||
function = _get_tagging_function(schema)
|
||||
prompt = prompt or ChatPromptTemplate.from_template(_TAGGING_TEMPLATE)
|
||||
@@ -154,6 +155,7 @@ def create_tagging_chain_pydantic(
|
||||
|
||||
Returns:
|
||||
Chain (LLMChain) that can be used to extract information from a passage.
|
||||
|
||||
"""
|
||||
if hasattr(pydantic_schema, "model_json_schema"):
|
||||
openai_schema = pydantic_schema.model_json_schema()
|
||||
|
||||
@@ -62,6 +62,7 @@ class QAGenerationChain(Chain):
|
||||
split_text | RunnableEach(bound=prompt | llm | JsonOutputParser())
|
||||
)
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
llm_chain: LLMChain
|
||||
|
||||
@@ -147,6 +147,7 @@ class BaseRetrievalQA(Chain):
|
||||
|
||||
res = indexqa({'query': 'This is my query'})
|
||||
answer, docs = res['result'], res['source_documents']
|
||||
|
||||
"""
|
||||
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
|
||||
question = inputs[self.input_key]
|
||||
@@ -191,6 +192,7 @@ class BaseRetrievalQA(Chain):
|
||||
|
||||
res = indexqa({'query': 'This is my query'})
|
||||
answer, docs = res['result'], res['source_documents']
|
||||
|
||||
"""
|
||||
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
|
||||
question = inputs[self.input_key]
|
||||
|
||||
@@ -96,6 +96,7 @@ class LLMRouterChain(RouterChain):
|
||||
)
|
||||
|
||||
chain.invoke({"query": "what color are carrots"})
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
llm_chain: LLMChain
|
||||
|
||||
@@ -140,6 +140,7 @@ class MultiPromptChain(MultiRouteChain):
|
||||
result = await app.ainvoke({"query": "what color are carrots"})
|
||||
print(result["destination"])
|
||||
print(result["answer"])
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
@property
|
||||
|
||||
@@ -113,6 +113,7 @@ def create_sql_query_chain(
|
||||
|
||||
Question: {input}'''
|
||||
prompt = PromptTemplate.from_template(template)
|
||||
|
||||
""" # noqa: E501
|
||||
if prompt is not None:
|
||||
prompt_to_use = prompt
|
||||
|
||||
@@ -132,6 +132,7 @@ def create_openai_fn_runnable(
|
||||
structured_llm = create_openai_fn_runnable([RecordPerson, RecordDog], llm)
|
||||
structured_llm.invoke("Harry was a chubby brown beagle who loved chicken)
|
||||
# -> RecordDog(name="Harry", color="brown", fav_food="chicken")
|
||||
|
||||
""" # noqa: E501
|
||||
if not functions:
|
||||
msg = "Need to pass in at least one function. Received zero."
|
||||
@@ -390,6 +391,7 @@ def create_structured_output_runnable(
|
||||
)
|
||||
chain = prompt | structured_llm
|
||||
chain.invoke({"input": "Harry was a chubby brown beagle who loved chicken"})
|
||||
|
||||
""" # noqa: E501
|
||||
# for backwards compatibility
|
||||
force_function_usage = kwargs.get(
|
||||
|
||||
@@ -26,6 +26,7 @@ class TransformChain(Chain):
|
||||
from langchain.chains import TransformChain
|
||||
transform_chain = TransformChain(input_variables=["text"],
|
||||
output_variables["entities"], transform=func())
|
||||
|
||||
"""
|
||||
|
||||
input_variables: list[str]
|
||||
|
||||
@@ -47,6 +47,7 @@ def _parse_model_string(model_name: str) -> tuple[str, str]:
|
||||
Raises:
|
||||
ValueError: If the model string is not in the correct format or
|
||||
the provider is unsupported
|
||||
|
||||
"""
|
||||
if ":" not in model_name:
|
||||
providers = _SUPPORTED_PROVIDERS
|
||||
@@ -177,6 +178,7 @@ def init_embeddings(
|
||||
)
|
||||
|
||||
.. versionadded:: 0.3.9
|
||||
|
||||
"""
|
||||
if not model:
|
||||
providers = _SUPPORTED_PROVIDERS.keys()
|
||||
|
||||
@@ -140,6 +140,7 @@ class TrajectoryEvalChain(AgentTrajectoryEvaluator, LLMEvalChain):
|
||||
)
|
||||
print(result["score"]) # noqa: T201
|
||||
# 0
|
||||
|
||||
"""
|
||||
|
||||
agent_tools: Optional[list[BaseTool]] = None
|
||||
|
||||
@@ -58,6 +58,7 @@ def load_dataset(uri: str) -> list[dict]:
|
||||
|
||||
from langchain.evaluation import load_dataset
|
||||
ds = load_dataset("llm-math")
|
||||
|
||||
"""
|
||||
try:
|
||||
from datasets import load_dataset
|
||||
|
||||
@@ -70,6 +70,7 @@ class LLMListwiseRerank(BaseDocumentCompressor):
|
||||
compressed_docs = reranker.compress_documents(documents, "Who is steve")
|
||||
assert len(compressed_docs) == 3
|
||||
assert "Steve" in compressed_docs[0].page_content
|
||||
|
||||
"""
|
||||
|
||||
reranker: Runnable[dict, list[Document]]
|
||||
|
||||
@@ -54,6 +54,7 @@ class ParentDocumentRetriever(MultiVectorRetriever):
|
||||
child_splitter=child_splitter,
|
||||
parent_splitter=parent_splitter,
|
||||
)
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
child_splitter: TextSplitter
|
||||
|
||||
@@ -87,6 +87,7 @@ or LangSmith's `RunEvaluator` classes.
|
||||
- :func:`arun_on_dataset <langchain.smith.evaluation.runner_utils.arun_on_dataset>`: Asynchronous function to evaluate a chain, agent, or other LangChain component over a dataset.
|
||||
- :func:`run_on_dataset <langchain.smith.evaluation.runner_utils.run_on_dataset>`: Function to evaluate a chain, agent, or other LangChain component over a dataset.
|
||||
- :class:`RunEvalConfig <langchain.smith.evaluation.config.RunEvalConfig>`: Class representing the configuration for running evaluation. You can select evaluators by :class:`EvaluatorType <langchain.evaluation.schema.EvaluatorType>` or config, or you can pass in `custom_evaluators`
|
||||
|
||||
""" # noqa: E501
|
||||
|
||||
from langchain.smith.evaluation import (
|
||||
|
||||
@@ -1451,6 +1451,7 @@ async def arun_on_dataset(
|
||||
llm_or_chain_factory=construct_chain,
|
||||
evaluation=evaluation_config,
|
||||
)
|
||||
|
||||
""" # noqa: E501
|
||||
input_mapper = kwargs.pop("input_mapper", None)
|
||||
if input_mapper:
|
||||
@@ -1623,6 +1624,7 @@ def run_on_dataset(
|
||||
llm_or_chain_factory=construct_chain,
|
||||
evaluation=evaluation_config,
|
||||
)
|
||||
|
||||
""" # noqa: E501
|
||||
input_mapper = kwargs.pop("input_mapper", None)
|
||||
if input_mapper:
|
||||
|
||||
@@ -46,6 +46,7 @@ class EncoderBackedStore(BaseStore[K, V]):
|
||||
store.mset([(1, 3.14), (2, 2.718)])
|
||||
values = store.mget([1, 2]) # Retrieves [3.14, 2.718]
|
||||
store.mdelete([1, 2]) # Deletes the keys 1 and 2
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user