langchain_exa.tools
.ExaSearchResults¶
注意
ExaSearchResults 实现了标准的 Runnable 接口
。 🏃
Runnable 接口
在 runnables 上有额外的方法可用,例如 with_types
, with_retry
, assign
, bind
, get_graph
, 以及更多。
- class langchain_exa.tools.ExaSearchResults[源代码]¶
基类:
BaseTool
查询 Metaphor Search API 并返回 JSON 的工具。
初始化工具。
- param args_schema: Optional[TypeBaseModel] = None¶
Pydantic 模型类,用于验证和解析工具的输入参数。
Args schema 应该是
pydantic.BaseModel 的子类。
或 - pydantic.v1.BaseModel 的子类(如果在 pydantic 2 中访问 v1 命名空间)
- param callback_manager: Optional[BaseCallbackManager] = None¶
已弃用。请改用 callbacks。
- param callbacks: Callbacks = None¶
在工具执行期间要调用的回调。
- param client: Exa = None¶
- param description: str = 'Exa Search 的包装器。 输入应为 Exa 优化的查询。 输出是查询结果的 JSON 数组'¶
用于告知模型如何/何时/为何使用该工具。
您可以提供少量示例作为描述的一部分。
- param exa_api_key: SecretStr = None¶
- 约束
type = string
writeOnly = True
format = password
- param handle_tool_error: Optional[Union[bool, str, Callable[[ToolException], str]]] = False¶
处理抛出的 ToolException 的内容。
- param handle_validation_error: Optional[Union[bool, str, Callable[[ValidationError], str]]] = False¶
处理抛出的 ValidationError 的内容。
- param metadata: Optional[Dict] = None¶
与工具关联的可选元数据。默认为 None。此元数据将与此工具的每次调用关联,并作为参数传递给 callbacks 中定义的处理程序。您可以使用这些来例如识别工具的特定实例及其用例。
- param response_format: Literal['content', 'content_and_artifact'] = 'content'¶
工具响应格式。默认为 ‘content’。
如果为 “content”,则工具的输出将被解释为 ToolMessage 的内容。 如果为 “content_and_artifact”,则输出应为与 ToolMessage 的 (content, artifact) 相对应的二元组。
- param return_direct: bool = False¶
是否直接返回工具的输出。
将其设置为 True 意味着在调用工具后,AgentExecutor 将停止循环。
- param tags: Optional[List[str]] = None¶
与工具关联的可选标签列表。默认为 None。这些标签将与此工具的每次调用关联,并作为参数传递给 callbacks 中定义的处理程序。您可以使用这些来例如识别工具的特定实例及其用例。
- param verbose: bool = False¶
是否记录工具的进度。
- __call__(tool_input: str, callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None) str ¶
Deprecated since version langchain-core==0.1.47: 使用
invoke
代替。使工具可调用。
- 参数
tool_input (str) –
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) –
- 返回类型
str
- 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]]]
- async ainvoke(input: Union[str, Dict, ToolCall], config: Optional[RunnableConfig] = None, **kwargs: Any) Any ¶
ainvoke 的默认实现,从线程调用 invoke。
即使 Runnable 没有实现 invoke 的原生异步版本,默认实现也允许使用异步代码。
如果子类可以异步运行,则应覆盖此方法。
- 参数
input (Union[str, Dict, ToolCall]) –
config (Optional[RunnableConfig]) –
kwargs (Any) –
- 返回类型
Any
- async arun(tool_input: Union[str, Dict], verbose: Optional[bool] = None, start_color: Optional[[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, run_id: Optional[UUID] = None, config: Optional[RunnableConfig] = None, tool_call_id: Optional[str] = None, **kwargs: Any) Any ¶
Run the tool asynchronously.
- 参数
tool_input (Union[str, Dict]) – The input to the tool.
verbose (Optional[bool]) – Whether to log the tool’s progress. Defaults to None.
start_color (Optional[str]) – The color to use when starting the tool. Defaults to ‘green’.
color (Optional[str]) – The color to use when ending the tool. Defaults to ‘green’.
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to be called during tool execution. Defaults to None.
tags (Optional[List[str]]) – Optional list of tags associated with the tool. Defaults to None.
metadata (Optional[Dict[str, Any]]) – Optional metadata associated with the tool. Defaults to None.
run_name (Optional[str]) – The name of the run. Defaults to None.
run_id (Optional[UUID]) – The id of the run. Defaults to None.
config (Optional[RunnableConfig]) – The configuration for the tool. Defaults to None.
tool_call_id (Optional[str]) – The id of the tool call. Defaults to None.
kwargs (Any) – Additional arguments to pass to the tool
- 返回
The output of the tool.
- Raises
ToolException – If an error occurs during tool execution.
- 返回类型
Any
- as_tool(args_schema: Optional[Type[BaseModel]] = None, *, name: Optional[str] = None, description: Optional[str] = None, arg_types: Optional[Dict[str, Type]] = None) BaseTool ¶
Beta
This API is in beta and may change in the future.
Create a BaseTool from a Runnable.
as_tool
will instantiate a BaseTool with a name, description, andargs_schema
from a Runnable. Where possible, schemas are inferred fromrunnable.get_input_schema
. Alternatively (e.g., if the Runnable takes a dict as input and the specific dict keys are not typed), the schema can be specified directly withargs_schema
. You can also passarg_types
to just specify the required arguments and their types.- 参数
args_schema (Optional[Type[BaseModel]]) – The schema for the tool. Defaults to None.
name (Optional[str]) – The name of the tool. Defaults to None.
description (Optional[str]) – The description of the tool. Defaults to None.
arg_types (Optional[Dict[str, Type]]) – A dictionary of argument names to types. Defaults to None.
- 返回
A BaseTool instance.
- 返回类型
Typed dict input
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]})
dict
input, specifying schema viaargs_schema
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]})
dict
input, specifying schema viaarg_types
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]})
String input
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")
New in version 0.2.14.
- async astream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) AsyncIterator[Output] ¶
Default implementation of astream, which calls ainvoke. Subclasses should override this method if they support streaming output.
- 参数
input (Input) – The input to the Runnable.
config (Optional[RunnableConfig]) – The config to use for the Runnable. Defaults to None.
kwargs (Optional[Any]) – 要传递给 Runnable 的其他关键字参数。
- 产生
The output of the Runnable.
- 返回类型
AsyncIterator[Output]
- astream_events(input: Any, config: Optional[RunnableConfig] = None, *, version: Literal['v1', 'v2'], include_names: Optional[Sequence[str]] = None, include_types: Optional[Sequence[str]] = None, include_tags: Optional[Sequence[str]] = None, exclude_names: Optional[Sequence[str]] = None, exclude_types: Optional[Sequence[str]] = None, exclude_tags: Optional[Sequence[str]] = None, **kwargs: Any) AsyncIterator[Union[StandardStreamEvent, CustomStreamEvent]] ¶
Beta
This API is in beta and may change in the future.
Generate a stream of events.
Use to create an iterator over StreamEvents that provide real-time information about the progress of the Runnable, including StreamEvents from intermediate results.
A StreamEvent is a dictionary with the following schema
event
: str - Event names are of theformat: on_[runnable_type]_(start|stream|end).
name
: str - The name of the Runnable that generated the event.run_id
: str - randomly generated ID associated with the given execution ofthe Runnable that emitted the event. A child Runnable that gets invoked as part of the execution of a parent Runnable is assigned its own unique ID.
parent_ids
: List[str] - The IDs of the parent runnables thatgenerated the event. The root Runnable will have an empty list. The order of the parent IDs is from the root to the immediate parent. Only available for v2 version of the API. The v1 version of the API will return an empty list.
tags
: Optional[List[str]] - The tags of the Runnable that generatedthe event.
metadata
: Optional[Dict[str, Any]] - The metadata of the Runnablethat generated the event.
data
: Dict[str, Any]
Below is a table that illustrates some evens that might be emitted by various chains. Metadata fields have been omitted from the table for brevity. Chain definitions have been included after the table.
ATTENTION This reference table is for the V2 version of the schema.
event
name
chunk
input
output
on_chat_model_start
[model name]
{“messages”: [[SystemMessage, HumanMessage]]}
on_chat_model_stream
[model name]
AIMessageChunk(content=”hello”)
on_chat_model_end
[model name]
{“messages”: [[SystemMessage, HumanMessage]]}
AIMessageChunk(content=”hello world”)
on_llm_start
[model name]
{‘input’: ‘hello’}
on_llm_stream
[model name]
‘Hello’
on_llm_end
[model name]
‘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
[retriever name]
{“query”: “hello”}
on_retriever_end
[retriever name]
{“query”: “hello”}
[Document(…), ..]
on_prompt_start
[template_name]
{“question”: “hello”}
on_prompt_end
[template_name]
{“question”: “hello”}
ChatPromptValue(messages: [SystemMessage, …])
In addition to the standard events, users can also dispatch custom events (see example below).
Custom events will be only be surfaced with in the v2 version of the API!
A custom event has following format
Attribute
Type
Description
name
str
A user defined name for the event.
data
Any
The data associated with the event. This can be anything, though we suggest making it JSON serializable.
Here are declarations associated with the standard events shown above
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"]})
Example
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": [], }, ]
Example: Dispatch Custom Event
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)
- 参数
input (Any) – The input to the Runnable.
config (Optional[RunnableConfig]) – The config to use for the Runnable.
version (Literal['v1', 'v2']) – The version of the schema to use either v2 or v1. Users should use v2. v1 is for backwards compatibility and will be deprecated in 0.4.0. No default will be assigned until the API is stabilized. custom events will only be surfaced in v2.
include_names (Optional[Sequence[str]]) – Only include events from runnables with matching names.
include_types (Optional[Sequence[str]]) – Only include events from runnables with matching types.
include_tags (Optional[Sequence[str]]) – Only include events from runnables with matching tags.
exclude_names (Optional[Sequence[str]]) – Exclude events from runnables with matching names.
exclude_types (Optional[Sequence[str]]) – Exclude events from runnables with matching types.
exclude_tags (Optional[Sequence[str]]) – Exclude events from runnables with matching tags.
kwargs (Any) – Additional keyword arguments to pass to the Runnable. These will be passed to astream_log as this implementation of astream_events is built on top of astream_log.
- 产生
An async stream of StreamEvents.
- Raises
NotImplementedError – If the version is not v1 or v2.
- 返回类型
AsyncIterator[Union[StandardStreamEvent, CustomStreamEvent]]
- batch(inputs: List[Input], config: Optional[Union[RunnableConfig, List[RunnableConfig]]] = None, *, return_exceptions: bool = False, **kwargs: Optional[Any]) List[Output] ¶
Default implementation runs invoke in parallel using a thread pool executor.
batch 的默认实现非常适用于 IO 绑定的 runnables。
如果子类可以更有效地进行批量处理,则应覆盖此方法;例如,如果底层的 Runnable 使用支持批量模式的 API。
- 参数
inputs (List[Input]) –
config (Optional[Union[RunnableConfig, List[RunnableConfig]]]) –
return_exceptions (bool) –
kwargs (Optional[Any]) –
- 返回类型
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]]] ¶
Run invoke in parallel on a list of inputs, yielding results as they complete.
- 参数
inputs (Sequence[Input]) –
config (Optional[Union[RunnableConfig, Sequence[RunnableConfig]]]) –
return_exceptions (bool) –
kwargs (Optional[Any]) –
- 返回类型
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] ¶
Configure alternatives for Runnables that can be set at runtime.
- 参数
which (ConfigurableField) – The ConfigurableField instance that will be used to select the alternative.
default_key (str) – The default key to use if no alternative is selected. Defaults to “default”.
prefix_keys (bool) – Whether to prefix the keys with the ConfigurableField id. Defaults to 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 )
- invoke(input: Union[str, Dict, ToolCall], config: Optional[RunnableConfig] = None, **kwargs: Any) Any ¶
将单个输入转换为输出。重写以实现。
- 参数
input (Union[str, Dict, ToolCall]) – Runnable 的输入。
config (Optional[RunnableConfig]) – 调用 Runnable 时使用的配置。该配置支持标准键,例如用于跟踪目的的 ‘tags’、‘metadata’,用于控制并行执行量的 ‘max_concurrency’ 以及其他键。有关更多详细信息,请参阅 RunnableConfig。
kwargs (Any) –
- 返回
The output of the Runnable.
- 返回类型
Any
- run(tool_input: Union[str, Dict[str, Any]], verbose: Optional[bool] = None, start_color: Optional[str] = 'green', color: Optional[str] = 'green', callbacks: Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]] = None, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, run_name: Optional[str] = None, run_id: Optional[UUID] = None, config: Optional[RunnableConfig] = None, tool_call_id: Optional[str] = None, **kwargs: Any) Any ¶
运行该工具。
- 参数
tool_input (Union[str, Dict[str, Any]]) – 该工具的输入。
verbose (Optional[bool]) – Whether to log the tool’s progress. Defaults to None.
start_color (Optional[str]) – The color to use when starting the tool. Defaults to ‘green’.
color (Optional[str]) – The color to use when ending the tool. Defaults to ‘green’.
callbacks (Optional[Union[List[BaseCallbackHandler], BaseCallbackManager]]) – Callbacks to be called during tool execution. Defaults to None.
tags (Optional[List[str]]) – Optional list of tags associated with the tool. Defaults to None.
metadata (Optional[Dict[str, Any]]) – Optional metadata associated with the tool. Defaults to None.
run_name (Optional[str]) – The name of the run. Defaults to None.
run_id (Optional[UUID]) – The id of the run. Defaults to None.
config (Optional[RunnableConfig]) – The configuration for the tool. Defaults to None.
tool_call_id (Optional[str]) – The id of the tool call. Defaults to None.
kwargs (Any) – Additional arguments to pass to the tool
- 返回
The output of the tool.
- Raises
ToolException – If an error occurs during tool execution.
- 返回类型
Any
- stream(input: Input, config: Optional[RunnableConfig] = None, **kwargs: Optional[Any]) Iterator[Output] ¶
stream 的默认实现,它调用 invoke。如果子类支持流式输出,则应重写此方法。
- 参数
input (Input) – The input to the Runnable.
config (Optional[RunnableConfig]) – The config to use for the Runnable. Defaults to None.
kwargs (Optional[Any]) – 要传递给 Runnable 的其他关键字参数。
- 产生
The output of the Runnable.
- 返回类型
Iterator[Output]
- to_json() Union[SerializedConstructor, SerializedNotImplemented] ¶
将 Runnable 序列化为 JSON。
- 返回
Runnable 的 JSON 可序列化表示。
- 返回类型
- property args: dict¶
- property is_single_input: bool¶
该工具是否只接受单个输入。
- property tool_call_schema: Type[BaseModel]¶