coco-framework 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coco/__init__.py +3 -0
- coco/agents/__init__.py +9 -0
- coco/agents/_subagent_transformer.py +307 -0
- coco/agents/factory.py +2164 -0
- coco/agents/middleware/__init__.py +100 -0
- coco/agents/middleware/_execution.py +385 -0
- coco/agents/middleware/_redaction.py +454 -0
- coco/agents/middleware/_retry.py +134 -0
- coco/agents/middleware/_trace_policy.py +61 -0
- coco/agents/middleware/context_editing.py +306 -0
- coco/agents/middleware/file_search.py +433 -0
- coco/agents/middleware/human_in_the_loop.py +680 -0
- coco/agents/middleware/internal_call_transformer.py +108 -0
- coco/agents/middleware/model_call_limit.py +267 -0
- coco/agents/middleware/model_fallback.py +417 -0
- coco/agents/middleware/model_retry.py +327 -0
- coco/agents/middleware/pii.py +878 -0
- coco/agents/middleware/provider_tool_search.py +307 -0
- coco/agents/middleware/shell_tool.py +949 -0
- coco/agents/middleware/summarization.py +910 -0
- coco/agents/middleware/todo.py +357 -0
- coco/agents/middleware/tool_call_limit.py +495 -0
- coco/agents/middleware/tool_emulator.py +251 -0
- coco/agents/middleware/tool_error.py +209 -0
- coco/agents/middleware/tool_retry.py +421 -0
- coco/agents/middleware/tool_selection.py +515 -0
- coco/agents/middleware/types.py +2201 -0
- coco/agents/structured_output.py +472 -0
- coco/chat_models/__init__.py +7 -0
- coco/chat_models/base.py +1082 -0
- coco/embeddings/__init__.py +18 -0
- coco/embeddings/base.py +279 -0
- coco/mcp/__init__.py +36 -0
- coco/mcp/adapter.py +245 -0
- coco/mcp/elicitation.py +394 -0
- coco/mcp/tools.py +307 -0
- coco/messages/__init__.py +73 -0
- coco/py.typed +0 -0
- coco/rate_limiters/__init__.py +13 -0
- coco/tools/__init__.py +22 -0
- coco/tools/tool_node.py +20 -0
- coco_anthropic/__init__.py +15 -0
- coco_anthropic/_client_utils.py +81 -0
- coco_anthropic/_compat.py +228 -0
- coco_anthropic/_sdk_compat.py +124 -0
- coco_anthropic/_version.py +3 -0
- coco_anthropic/chat_models.py +3349 -0
- coco_anthropic/data/__init__.py +1 -0
- coco_anthropic/data/_profiles.py +491 -0
- coco_anthropic/data/profile_augmentations.toml +69 -0
- coco_anthropic/experimental.py +140 -0
- coco_anthropic/llms.py +428 -0
- coco_anthropic/middleware/__init__.py +25 -0
- coco_anthropic/middleware/anthropic_tools.py +1197 -0
- coco_anthropic/middleware/bash.py +84 -0
- coco_anthropic/middleware/file_search.py +360 -0
- coco_anthropic/middleware/prompt_caching.py +276 -0
- coco_anthropic/output_parsers.py +93 -0
- coco_anthropic/py.typed +0 -0
- coco_core/__init__.py +20 -0
- coco_core/_api/__init__.py +87 -0
- coco_core/_api/beta_decorator.py +266 -0
- coco_core/_api/deprecation.py +637 -0
- coco_core/_api/internal.py +23 -0
- coco_core/_api/path.py +50 -0
- coco_core/_import_utils.py +41 -0
- coco_core/_protocol.py +625 -0
- coco_core/_security/__init__.py +36 -0
- coco_core/_security/_exceptions.py +9 -0
- coco_core/_security/_policy.py +313 -0
- coco_core/_security/_ssrf_protection.py +155 -0
- coco_core/_security/_transport.py +254 -0
- coco_core/agents.py +258 -0
- coco_core/caches.py +272 -0
- coco_core/callbacks/__init__.py +132 -0
- coco_core/callbacks/base.py +1229 -0
- coco_core/callbacks/file.py +266 -0
- coco_core/callbacks/manager.py +2826 -0
- coco_core/callbacks/stdout.py +123 -0
- coco_core/callbacks/streaming_stdout.py +154 -0
- coco_core/callbacks/usage.py +124 -0
- coco_core/chat_history.py +267 -0
- coco_core/chat_loaders.py +26 -0
- coco_core/chat_sessions.py +19 -0
- coco_core/cross_encoders.py +18 -0
- coco_core/document_loaders/__init__.py +36 -0
- coco_core/document_loaders/base.py +155 -0
- coco_core/document_loaders/blob_loaders.py +38 -0
- coco_core/documents/__init__.py +55 -0
- coco_core/documents/base.py +347 -0
- coco_core/documents/compressor.py +74 -0
- coco_core/documents/transformers.py +79 -0
- coco_core/embeddings/__init__.py +31 -0
- coco_core/embeddings/embeddings.py +78 -0
- coco_core/embeddings/fake.py +129 -0
- coco_core/env.py +22 -0
- coco_core/example_selectors/__init__.py +47 -0
- coco_core/example_selectors/base.py +60 -0
- coco_core/example_selectors/length_based.py +131 -0
- coco_core/example_selectors/semantic_similarity.py +366 -0
- coco_core/exceptions.py +166 -0
- coco_core/globals.py +72 -0
- coco_core/indexing/__init__.py +53 -0
- coco_core/indexing/api.py +954 -0
- coco_core/indexing/base.py +661 -0
- coco_core/indexing/in_memory.py +104 -0
- coco_core/language_models/__init__.py +116 -0
- coco_core/language_models/_compat_bridge.py +844 -0
- coco_core/language_models/_utils.py +343 -0
- coco_core/language_models/base.py +500 -0
- coco_core/language_models/chat_model_stream.py +1525 -0
- coco_core/language_models/chat_models.py +2748 -0
- coco_core/language_models/fake.py +137 -0
- coco_core/language_models/fake_chat_models.py +396 -0
- coco_core/language_models/llms.py +1569 -0
- coco_core/language_models/model_profile.py +183 -0
- coco_core/load/__init__.py +44 -0
- coco_core/load/_validation.py +191 -0
- coco_core/load/dump.py +120 -0
- coco_core/load/load.py +828 -0
- coco_core/load/mapping.py +1097 -0
- coco_core/load/serializable.py +406 -0
- coco_core/messages/__init__.py +198 -0
- coco_core/messages/ai.py +854 -0
- coco_core/messages/base.py +518 -0
- coco_core/messages/block_translators/__init__.py +112 -0
- coco_core/messages/block_translators/anthropic.py +534 -0
- coco_core/messages/block_translators/bedrock.py +108 -0
- coco_core/messages/block_translators/bedrock_converse.py +329 -0
- coco_core/messages/block_translators/coco_v0.py +303 -0
- coco_core/messages/block_translators/google_genai.py +610 -0
- coco_core/messages/block_translators/google_vertexai.py +21 -0
- coco_core/messages/block_translators/groq.py +157 -0
- coco_core/messages/block_translators/openai.py +1089 -0
- coco_core/messages/chat.py +64 -0
- coco_core/messages/content.py +1488 -0
- coco_core/messages/function.py +62 -0
- coco_core/messages/human.py +70 -0
- coco_core/messages/modifier.py +33 -0
- coco_core/messages/system.py +70 -0
- coco_core/messages/tool.py +418 -0
- coco_core/messages/utils.py +2442 -0
- coco_core/output_parsers/__init__.py +101 -0
- coco_core/output_parsers/base.py +361 -0
- coco_core/output_parsers/format_instructions.py +16 -0
- coco_core/output_parsers/json.py +139 -0
- coco_core/output_parsers/list.py +249 -0
- coco_core/output_parsers/openai_functions.py +324 -0
- coco_core/output_parsers/openai_tools.py +383 -0
- coco_core/output_parsers/pydantic.py +141 -0
- coco_core/output_parsers/string.py +63 -0
- coco_core/output_parsers/transform.py +175 -0
- coco_core/output_parsers/xml.py +301 -0
- coco_core/outputs/__init__.py +66 -0
- coco_core/outputs/chat_generation.py +147 -0
- coco_core/outputs/chat_result.py +39 -0
- coco_core/outputs/generation.py +80 -0
- coco_core/outputs/llm_result.py +112 -0
- coco_core/outputs/run_info.py +22 -0
- coco_core/prompt_values.py +161 -0
- coco_core/prompts/__init__.py +101 -0
- coco_core/prompts/base.py +508 -0
- coco_core/prompts/chat.py +1495 -0
- coco_core/prompts/dict.py +177 -0
- coco_core/prompts/few_shot.py +483 -0
- coco_core/prompts/few_shot_with_templates.py +239 -0
- coco_core/prompts/image.py +177 -0
- coco_core/prompts/loading.py +296 -0
- coco_core/prompts/message.py +97 -0
- coco_core/prompts/prompt.py +312 -0
- coco_core/prompts/string.py +399 -0
- coco_core/prompts/structured.py +214 -0
- coco_core/py.typed +0 -0
- coco_core/rate_limiters.py +254 -0
- coco_core/retrievers.py +328 -0
- coco_core/runnables/__init__.py +136 -0
- coco_core/runnables/base.py +6725 -0
- coco_core/runnables/branch.py +457 -0
- coco_core/runnables/config.py +712 -0
- coco_core/runnables/configurable.py +710 -0
- coco_core/runnables/fallbacks.py +663 -0
- coco_core/runnables/graph.py +741 -0
- coco_core/runnables/graph_ascii.py +366 -0
- coco_core/runnables/graph_mermaid.py +503 -0
- coco_core/runnables/graph_png.py +215 -0
- coco_core/runnables/history.py +631 -0
- coco_core/runnables/passthrough.py +849 -0
- coco_core/runnables/retry.py +379 -0
- coco_core/runnables/router.py +239 -0
- coco_core/runnables/schema.py +188 -0
- coco_core/runnables/utils.py +798 -0
- coco_core/stores.py +291 -0
- coco_core/structured_query.py +203 -0
- coco_core/sys_info.py +154 -0
- coco_core/tools/__init__.py +95 -0
- coco_core/tools/base.py +1948 -0
- coco_core/tools/convert.py +497 -0
- coco_core/tools/render.py +67 -0
- coco_core/tools/retriever.py +94 -0
- coco_core/tools/simple.py +208 -0
- coco_core/tools/structured.py +322 -0
- coco_core/tracers/__init__.py +47 -0
- coco_core/tracers/_compat.py +95 -0
- coco_core/tracers/_context.py +337 -0
- coco_core/tracers/_streaming.py +53 -0
- coco_core/tracers/base.py +955 -0
- coco_core/tracers/coco.py +279 -0
- coco_core/tracers/context.py +205 -0
- coco_core/tracers/core.py +766 -0
- coco_core/tracers/event_stream.py +1101 -0
- coco_core/tracers/log_stream.py +765 -0
- coco_core/tracers/memory_stream.py +200 -0
- coco_core/tracers/root_listeners.py +130 -0
- coco_core/tracers/run_collector.py +40 -0
- coco_core/tracers/schemas.py +14 -0
- coco_core/tracers/stdout.py +205 -0
- coco_core/utils/__init__.py +111 -0
- coco_core/utils/_gateway.py +274 -0
- coco_core/utils/_merge.py +218 -0
- coco_core/utils/aiter.py +357 -0
- coco_core/utils/env.py +86 -0
- coco_core/utils/formatting.py +80 -0
- coco_core/utils/function_calling.py +869 -0
- coco_core/utils/html.py +132 -0
- coco_core/utils/image.py +15 -0
- coco_core/utils/input.py +82 -0
- coco_core/utils/interactive_env.py +12 -0
- coco_core/utils/iter.py +229 -0
- coco_core/utils/json.py +230 -0
- coco_core/utils/json_schema.py +273 -0
- coco_core/utils/mustache.py +706 -0
- coco_core/utils/pydantic.py +631 -0
- coco_core/utils/strings.py +69 -0
- coco_core/utils/usage.py +61 -0
- coco_core/utils/utils.py +528 -0
- coco_core/utils/uuid.py +57 -0
- coco_core/vectorstores/__init__.py +53 -0
- coco_core/vectorstores/base.py +1111 -0
- coco_core/vectorstores/in_memory.py +546 -0
- coco_core/vectorstores/utils.py +163 -0
- coco_core/version.py +3 -0
- coco_framework-0.1.0.dist-info/METADATA +184 -0
- coco_framework-0.1.0.dist-info/RECORD +400 -0
- coco_framework-0.1.0.dist-info/WHEEL +4 -0
- coco_framework-0.1.0.dist-info/licenses/LICENSE +24 -0
- coco_framework-0.1.0.dist-info/licenses/NOTICE +15 -0
- coco_graph/_internal/__init__.py +4 -0
- coco_graph/_internal/_cache.py +31 -0
- coco_graph/_internal/_config.py +474 -0
- coco_graph/_internal/_constants.py +140 -0
- coco_graph/_internal/_fields.py +213 -0
- coco_graph/_internal/_future.py +220 -0
- coco_graph/_internal/_pydantic.py +275 -0
- coco_graph/_internal/_queue.py +124 -0
- coco_graph/_internal/_replay.py +90 -0
- coco_graph/_internal/_retry.py +29 -0
- coco_graph/_internal/_runnable.py +969 -0
- coco_graph/_internal/_scratchpad.py +19 -0
- coco_graph/_internal/_serde.py +253 -0
- coco_graph/_internal/_timeout.py +25 -0
- coco_graph/_internal/_typing.py +54 -0
- coco_graph/cache/base/__init__.py +48 -0
- coco_graph/cache/base/py.typed +0 -0
- coco_graph/cache/memory/__init__.py +73 -0
- coco_graph/cache/redis/__init__.py +144 -0
- coco_graph/cache/sqlite/__init__.py +120 -0
- coco_graph/callbacks.py +394 -0
- coco_graph/channels/__init__.py +29 -0
- coco_graph/channels/any_value.py +72 -0
- coco_graph/channels/base.py +121 -0
- coco_graph/channels/binop.py +155 -0
- coco_graph/channels/delta.py +202 -0
- coco_graph/channels/ephemeral_value.py +79 -0
- coco_graph/channels/last_value.py +151 -0
- coco_graph/channels/named_barrier_value.py +167 -0
- coco_graph/channels/topic.py +94 -0
- coco_graph/channels/untracked_value.py +73 -0
- coco_graph/checkpoint/base/__init__.py +861 -0
- coco_graph/checkpoint/base/id.py +109 -0
- coco_graph/checkpoint/base/py.typed +0 -0
- coco_graph/checkpoint/memory/__init__.py +698 -0
- coco_graph/checkpoint/memory/py.typed +0 -0
- coco_graph/checkpoint/postgres/__init__.py +602 -0
- coco_graph/checkpoint/postgres/_ainternal.py +23 -0
- coco_graph/checkpoint/postgres/_internal.py +21 -0
- coco_graph/checkpoint/postgres/aio.py +691 -0
- coco_graph/checkpoint/postgres/base.py +666 -0
- coco_graph/checkpoint/postgres/py.typed +0 -0
- coco_graph/checkpoint/postgres/shallow.py +967 -0
- coco_graph/checkpoint/serde/__init__.py +0 -0
- coco_graph/checkpoint/serde/_msgpack.py +97 -0
- coco_graph/checkpoint/serde/base.py +64 -0
- coco_graph/checkpoint/serde/encrypted.py +80 -0
- coco_graph/checkpoint/serde/event_hooks.py +52 -0
- coco_graph/checkpoint/serde/jsonplus.py +883 -0
- coco_graph/checkpoint/serde/py.typed +0 -0
- coco_graph/checkpoint/serde/types.py +68 -0
- coco_graph/checkpoint/sqlite/__init__.py +645 -0
- coco_graph/checkpoint/sqlite/_delta.py +172 -0
- coco_graph/checkpoint/sqlite/aio.py +738 -0
- coco_graph/checkpoint/sqlite/py.typed +0 -0
- coco_graph/checkpoint/sqlite/utils.py +116 -0
- coco_graph/config.py +196 -0
- coco_graph/constants.py +64 -0
- coco_graph/errors.py +241 -0
- coco_graph/func/__init__.py +620 -0
- coco_graph/graph/__init__.py +12 -0
- coco_graph/graph/_branch.py +225 -0
- coco_graph/graph/_node.py +103 -0
- coco_graph/graph/message.py +437 -0
- coco_graph/graph/state.py +1978 -0
- coco_graph/graph/ui.py +227 -0
- coco_graph/managed/__init__.py +3 -0
- coco_graph/managed/base.py +31 -0
- coco_graph/managed/is_last_step.py +24 -0
- coco_graph/prebuilt/__init__.py +23 -0
- coco_graph/prebuilt/_tool_call_stream.py +117 -0
- coco_graph/prebuilt/_tool_call_transformer.py +165 -0
- coco_graph/prebuilt/chat_agent_executor.py +1015 -0
- coco_graph/prebuilt/interrupt.py +105 -0
- coco_graph/prebuilt/py.typed +0 -0
- coco_graph/prebuilt/tool_node.py +2030 -0
- coco_graph/prebuilt/tool_validator.py +221 -0
- coco_graph/pregel/__init__.py +3 -0
- coco_graph/pregel/_algo.py +1460 -0
- coco_graph/pregel/_call.py +298 -0
- coco_graph/pregel/_checkpoint.py +331 -0
- coco_graph/pregel/_config.py +0 -0
- coco_graph/pregel/_draw.py +294 -0
- coco_graph/pregel/_executor.py +223 -0
- coco_graph/pregel/_io.py +174 -0
- coco_graph/pregel/_log.py +3 -0
- coco_graph/pregel/_loop.py +1988 -0
- coco_graph/pregel/_messages.py +461 -0
- coco_graph/pregel/_read.py +312 -0
- coco_graph/pregel/_retry.py +854 -0
- coco_graph/pregel/_runner.py +941 -0
- coco_graph/pregel/_tools.py +268 -0
- coco_graph/pregel/_utils.py +221 -0
- coco_graph/pregel/_validate.py +120 -0
- coco_graph/pregel/_write.py +192 -0
- coco_graph/pregel/debug.py +302 -0
- coco_graph/pregel/main.py +4364 -0
- coco_graph/pregel/protocol.py +288 -0
- coco_graph/pregel/types.py +38 -0
- coco_graph/py.typed +0 -0
- coco_graph/runtime.py +350 -0
- coco_graph/store/base/__init__.py +1322 -0
- coco_graph/store/base/batch.py +371 -0
- coco_graph/store/base/embed.py +436 -0
- coco_graph/store/base/py.typed +0 -0
- coco_graph/store/memory/__init__.py +592 -0
- coco_graph/store/memory/py.typed +0 -0
- coco_graph/store/postgres/__init__.py +4 -0
- coco_graph/store/postgres/aio.py +592 -0
- coco_graph/store/postgres/base.py +1480 -0
- coco_graph/store/postgres/py.typed +0 -0
- coco_graph/store/sqlite/__init__.py +4 -0
- coco_graph/store/sqlite/aio.py +632 -0
- coco_graph/store/sqlite/base.py +1514 -0
- coco_graph/stream/__init__.py +45 -0
- coco_graph/stream/_convert.py +32 -0
- coco_graph/stream/_mux.py +523 -0
- coco_graph/stream/_types.py +330 -0
- coco_graph/stream/run_stream.py +735 -0
- coco_graph/stream/stream_channel.py +341 -0
- coco_graph/stream/transformers.py +1039 -0
- coco_graph/types.py +1079 -0
- coco_graph/typing.py +48 -0
- coco_graph/utils/__init__.py +1 -0
- coco_graph/utils/config.py +4 -0
- coco_graph/utils/runnable.py +3 -0
- coco_graph/version.py +13 -0
- coco_graph/warnings.py +69 -0
- coco_openai/__init__.py +20 -0
- coco_openai/_compat.py +45 -0
- coco_openai/_version.py +3 -0
- coco_openai/chat_models/__init__.py +6 -0
- coco_openai/chat_models/_client_utils.py +684 -0
- coco_openai/chat_models/_compat.py +525 -0
- coco_openai/chat_models/azure.py +1227 -0
- coco_openai/chat_models/base.py +5654 -0
- coco_openai/chat_models/codex.py +557 -0
- coco_openai/chatgpt_oauth.py +1063 -0
- coco_openai/data/__init__.py +1 -0
- coco_openai/data/_profiles.py +1655 -0
- coco_openai/data/profile_augmentations.toml +127 -0
- coco_openai/embeddings/__init__.py +6 -0
- coco_openai/embeddings/azure.py +240 -0
- coco_openai/embeddings/base.py +820 -0
- coco_openai/llms/__init__.py +6 -0
- coco_openai/llms/azure.py +249 -0
- coco_openai/llms/base.py +919 -0
- coco_openai/middleware/__init__.py +11 -0
- coco_openai/middleware/openai_moderation.py +484 -0
- coco_openai/output_parsers/__init__.py +9 -0
- coco_openai/output_parsers/tools.py +9 -0
- coco_openai/py.typed +0 -0
- coco_openai/tools/__init__.py +5 -0
- coco_openai/tools/custom_tool.py +111 -0
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Interface for a rate limiter and an in-memory rate limiter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import abc
|
|
6
|
+
import asyncio
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BaseRateLimiter(abc.ABC):
|
|
12
|
+
"""Base class for rate limiters.
|
|
13
|
+
|
|
14
|
+
Usage of the base limiter is through the acquire and aacquire methods depending
|
|
15
|
+
on whether running in a sync or async context.
|
|
16
|
+
|
|
17
|
+
Implementations are free to add a timeout parameter to their initialize method
|
|
18
|
+
to allow users to specify a timeout for acquiring the necessary tokens when
|
|
19
|
+
using a blocking call.
|
|
20
|
+
|
|
21
|
+
Current limitations:
|
|
22
|
+
|
|
23
|
+
- Rate limiting information is not surfaced in tracing or callbacks. This means
|
|
24
|
+
that the total time it takes to invoke a chat model will encompass both
|
|
25
|
+
the time spent waiting for tokens and the time spent making the request.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
@abc.abstractmethod
|
|
29
|
+
def acquire(self, *, blocking: bool = True) -> bool:
|
|
30
|
+
"""Attempt to acquire the necessary tokens for the rate limiter.
|
|
31
|
+
|
|
32
|
+
This method blocks until the required tokens are available if `blocking`
|
|
33
|
+
is set to `True`.
|
|
34
|
+
|
|
35
|
+
If `blocking` is set to `False`, the method will immediately return the result
|
|
36
|
+
of the attempt to acquire the tokens.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
40
|
+
If `False`, the method will return immediately with the result of
|
|
41
|
+
the attempt.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
@abc.abstractmethod
|
|
48
|
+
async def aacquire(self, *, blocking: bool = True) -> bool:
|
|
49
|
+
"""Attempt to acquire the necessary tokens for the rate limiter.
|
|
50
|
+
|
|
51
|
+
This method blocks until the required tokens are available if `blocking`
|
|
52
|
+
is set to `True`.
|
|
53
|
+
|
|
54
|
+
If `blocking` is set to `False`, the method will immediately return the result
|
|
55
|
+
of the attempt to acquire the tokens.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
59
|
+
If `False`, the method will return immediately with the result of
|
|
60
|
+
the attempt.
|
|
61
|
+
|
|
62
|
+
Returns:
|
|
63
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class InMemoryRateLimiter(BaseRateLimiter):
|
|
68
|
+
"""An in memory rate limiter based on a token bucket algorithm.
|
|
69
|
+
|
|
70
|
+
This is an in memory rate limiter, so it cannot rate limit across
|
|
71
|
+
different processes.
|
|
72
|
+
|
|
73
|
+
The rate limiter only allows time-based rate limiting and does not
|
|
74
|
+
take into account any information about the input or the output, so it
|
|
75
|
+
cannot be used to rate limit based on the size of the request.
|
|
76
|
+
|
|
77
|
+
It is thread safe and can be used in either a sync or async context.
|
|
78
|
+
|
|
79
|
+
The in memory rate limiter is based on a token bucket. The bucket is filled
|
|
80
|
+
with tokens at a given rate. Each request consumes a token. If there are
|
|
81
|
+
not enough tokens in the bucket, the request is blocked until there are
|
|
82
|
+
enough tokens.
|
|
83
|
+
|
|
84
|
+
These tokens have nothing to do with LLM tokens. They are just
|
|
85
|
+
a way to keep track of how many requests can be made at a given time.
|
|
86
|
+
|
|
87
|
+
Current limitations:
|
|
88
|
+
|
|
89
|
+
- The rate limiter is not designed to work across different processes. It is
|
|
90
|
+
an in-memory rate limiter, but it is thread safe.
|
|
91
|
+
- The rate limiter only supports time-based rate limiting. It does not take
|
|
92
|
+
into account the size of the request or any other factors.
|
|
93
|
+
|
|
94
|
+
Example:
|
|
95
|
+
```python
|
|
96
|
+
import time
|
|
97
|
+
|
|
98
|
+
from coco_core.rate_limiters import InMemoryRateLimiter
|
|
99
|
+
|
|
100
|
+
rate_limiter = InMemoryRateLimiter(
|
|
101
|
+
requests_per_second=0.1, # <-- Can only make a request once every 10 seconds!!
|
|
102
|
+
check_every_n_seconds=0.1, # Wake up every 100 ms to check whether allowed to make a request,
|
|
103
|
+
max_bucket_size=10, # Controls the maximum burst size.
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
from coco_anthropic import ChatAnthropic
|
|
107
|
+
|
|
108
|
+
model = ChatAnthropic(model_name="claude-sonnet-5", rate_limiter=rate_limiter)
|
|
109
|
+
|
|
110
|
+
for _ in range(5):
|
|
111
|
+
tic = time.time()
|
|
112
|
+
model.invoke("hello")
|
|
113
|
+
toc = time.time()
|
|
114
|
+
print(toc - tic)
|
|
115
|
+
```
|
|
116
|
+
""" # noqa: E501
|
|
117
|
+
|
|
118
|
+
def __init__(
|
|
119
|
+
self,
|
|
120
|
+
*,
|
|
121
|
+
requests_per_second: float = 1,
|
|
122
|
+
check_every_n_seconds: float = 0.1,
|
|
123
|
+
max_bucket_size: float = 1,
|
|
124
|
+
) -> None:
|
|
125
|
+
"""A rate limiter based on a token bucket.
|
|
126
|
+
|
|
127
|
+
These tokens have nothing to do with LLM tokens. They are just
|
|
128
|
+
a way to keep track of how many requests can be made at a given time.
|
|
129
|
+
|
|
130
|
+
This rate limiter is designed to work in a threaded environment.
|
|
131
|
+
|
|
132
|
+
It works by filling up a bucket with tokens at a given rate. Each
|
|
133
|
+
request consumes a given number of tokens. If there are not enough
|
|
134
|
+
tokens in the bucket, the request is blocked until there are enough
|
|
135
|
+
tokens.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
requests_per_second: The number of tokens to add per second to the bucket.
|
|
139
|
+
The tokens represent "credit" that can be used to make requests.
|
|
140
|
+
check_every_n_seconds: Check whether the tokens are available
|
|
141
|
+
every this many seconds. Can be a float to represent
|
|
142
|
+
fractions of a second.
|
|
143
|
+
max_bucket_size: The maximum number of tokens that can be in the bucket.
|
|
144
|
+
Must be at least `1`. Used to prevent bursts of requests.
|
|
145
|
+
"""
|
|
146
|
+
# Number of requests that we can make per second.
|
|
147
|
+
self.requests_per_second = requests_per_second
|
|
148
|
+
|
|
149
|
+
# Number of tokens in the bucket.
|
|
150
|
+
self.available_tokens = 0.0
|
|
151
|
+
|
|
152
|
+
self.max_bucket_size = max_bucket_size
|
|
153
|
+
|
|
154
|
+
# A lock to ensure that tokens can only be consumed by one thread
|
|
155
|
+
# at a given time.
|
|
156
|
+
self._consume_lock = threading.Lock()
|
|
157
|
+
|
|
158
|
+
# The last time we tried to consume tokens.
|
|
159
|
+
self.last: float | None = None
|
|
160
|
+
|
|
161
|
+
self.check_every_n_seconds = check_every_n_seconds
|
|
162
|
+
|
|
163
|
+
def _consume(self) -> bool:
|
|
164
|
+
"""Try to consume a token.
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
True means that the tokens were consumed, and the caller can proceed to
|
|
168
|
+
make the request. A False means that the tokens were not consumed, and
|
|
169
|
+
the caller should try again later.
|
|
170
|
+
"""
|
|
171
|
+
with self._consume_lock:
|
|
172
|
+
now = time.monotonic()
|
|
173
|
+
|
|
174
|
+
# initialize on first call to avoid a burst
|
|
175
|
+
if self.last is None:
|
|
176
|
+
self.last = now
|
|
177
|
+
|
|
178
|
+
elapsed = now - self.last
|
|
179
|
+
|
|
180
|
+
if elapsed * self.requests_per_second >= 1:
|
|
181
|
+
self.available_tokens += elapsed * self.requests_per_second
|
|
182
|
+
self.last = now
|
|
183
|
+
|
|
184
|
+
# Make sure that we don't exceed the bucket size.
|
|
185
|
+
# This is used to prevent bursts of requests.
|
|
186
|
+
self.available_tokens = min(self.available_tokens, self.max_bucket_size)
|
|
187
|
+
|
|
188
|
+
# As long as we have at least one token, we can proceed.
|
|
189
|
+
if self.available_tokens >= 1:
|
|
190
|
+
self.available_tokens -= 1
|
|
191
|
+
return True
|
|
192
|
+
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
def acquire(self, *, blocking: bool = True) -> bool:
|
|
196
|
+
"""Attempt to acquire a token from the rate limiter.
|
|
197
|
+
|
|
198
|
+
This method blocks until the required tokens are available if `blocking`
|
|
199
|
+
is set to `True`.
|
|
200
|
+
|
|
201
|
+
If `blocking` is set to `False`, the method will immediately return the result
|
|
202
|
+
of the attempt to acquire the tokens.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
206
|
+
If `False`, the method will return immediately with the result of
|
|
207
|
+
the attempt.
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
211
|
+
"""
|
|
212
|
+
if not blocking:
|
|
213
|
+
return self._consume()
|
|
214
|
+
|
|
215
|
+
while not self._consume():
|
|
216
|
+
time.sleep(self.check_every_n_seconds)
|
|
217
|
+
|
|
218
|
+
return True
|
|
219
|
+
|
|
220
|
+
async def aacquire(self, *, blocking: bool = True) -> bool:
|
|
221
|
+
"""Attempt to acquire a token from the rate limiter. Async version.
|
|
222
|
+
|
|
223
|
+
This method blocks until the required tokens are available if `blocking`
|
|
224
|
+
is set to `True`.
|
|
225
|
+
|
|
226
|
+
If `blocking` is set to `False`, the method will immediately return the result
|
|
227
|
+
of the attempt to acquire the tokens.
|
|
228
|
+
|
|
229
|
+
Args:
|
|
230
|
+
blocking: If `True`, the method will block until the tokens are available.
|
|
231
|
+
If `False`, the method will return immediately with the result of
|
|
232
|
+
the attempt.
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
`True` if the tokens were successfully acquired, `False` otherwise.
|
|
236
|
+
"""
|
|
237
|
+
if not blocking:
|
|
238
|
+
return self._consume()
|
|
239
|
+
|
|
240
|
+
while not self._consume(): # noqa: ASYNC110
|
|
241
|
+
# This code ignores the ASYNC110 warning which is a false positive in this
|
|
242
|
+
# case.
|
|
243
|
+
# There is no external actor that can mark that the Event is done
|
|
244
|
+
# since the tokens are managed by the rate limiter itself.
|
|
245
|
+
# It needs to wake up to re-fill the tokens.
|
|
246
|
+
# https://docs.astral.sh/ruff/rules/async-busy-wait/
|
|
247
|
+
await asyncio.sleep(self.check_every_n_seconds)
|
|
248
|
+
return True
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
__all__ = [
|
|
252
|
+
"BaseRateLimiter",
|
|
253
|
+
"InMemoryRateLimiter",
|
|
254
|
+
]
|
coco_core/retrievers.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""**Retriever** class returns `Document` objects given a text **query**.
|
|
2
|
+
|
|
3
|
+
It is more general than a vector store. A retriever does not need to be able to
|
|
4
|
+
store documents, only to return (or retrieve) it. Vector stores can be used as
|
|
5
|
+
the backbone of a retriever, but there are other types of retrievers as well.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from abc import ABC, abstractmethod
|
|
11
|
+
from inspect import signature
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
|
|
14
|
+
from pydantic import ConfigDict
|
|
15
|
+
from typing_extensions import Self, TypedDict, override
|
|
16
|
+
|
|
17
|
+
from coco_core.callbacks.manager import AsyncCallbackManager, CallbackManager
|
|
18
|
+
from coco_core.documents import Document
|
|
19
|
+
from coco_core.runnables import (
|
|
20
|
+
Runnable,
|
|
21
|
+
RunnableConfig,
|
|
22
|
+
RunnableSerializable,
|
|
23
|
+
ensure_config,
|
|
24
|
+
)
|
|
25
|
+
from coco_core.runnables.config import run_in_executor
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from coco_core.callbacks.manager import (
|
|
29
|
+
AsyncCallbackManagerForRetrieverRun,
|
|
30
|
+
CallbackManagerForRetrieverRun,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
RetrieverInput = str
|
|
34
|
+
RetrieverOutput = list[Document]
|
|
35
|
+
RetrieverLike = Runnable[RetrieverInput, RetrieverOutput]
|
|
36
|
+
RetrieverOutputLike = Runnable[Any, RetrieverOutput]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class LangSmithRetrieverParams(TypedDict, total=False):
|
|
40
|
+
"""LangSmith parameters for tracing."""
|
|
41
|
+
|
|
42
|
+
ls_retriever_name: str
|
|
43
|
+
"""Retriever name."""
|
|
44
|
+
|
|
45
|
+
ls_vector_store_provider: str | None
|
|
46
|
+
"""Vector store provider."""
|
|
47
|
+
|
|
48
|
+
ls_embedding_provider: str | None
|
|
49
|
+
"""Embedding provider."""
|
|
50
|
+
|
|
51
|
+
ls_embedding_model: str | None
|
|
52
|
+
"""Embedding model."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
|
|
56
|
+
"""Abstract base class for a document retrieval system.
|
|
57
|
+
|
|
58
|
+
A retrieval system is defined as something that can take string queries and return
|
|
59
|
+
the most 'relevant' documents from some source.
|
|
60
|
+
|
|
61
|
+
Usage:
|
|
62
|
+
|
|
63
|
+
A retriever follows the standard `Runnable` interface, and should be used via the
|
|
64
|
+
standard `Runnable` methods of `invoke`, `ainvoke`, `batch`, `abatch`.
|
|
65
|
+
|
|
66
|
+
Implementation:
|
|
67
|
+
|
|
68
|
+
When implementing a custom retriever, the class should implement the
|
|
69
|
+
`_get_relevant_documents` method to define the logic for retrieving documents.
|
|
70
|
+
|
|
71
|
+
Optionally, an async native implementations can be provided by overriding the
|
|
72
|
+
`_aget_relevant_documents` method.
|
|
73
|
+
|
|
74
|
+
!!! example "Retriever that returns the first 5 documents from a list of documents"
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from coco_core.documents import Document
|
|
78
|
+
from coco_core.retrievers import BaseRetriever
|
|
79
|
+
|
|
80
|
+
class SimpleRetriever(BaseRetriever):
|
|
81
|
+
docs: list[Document]
|
|
82
|
+
k: int = 5
|
|
83
|
+
|
|
84
|
+
def _get_relevant_documents(self, query: str) -> list[Document]:
|
|
85
|
+
\"\"\"Return the first k documents from the list of documents\"\"\"
|
|
86
|
+
return self.docs[:self.k]
|
|
87
|
+
|
|
88
|
+
async def _aget_relevant_documents(self, query: str) -> list[Document]:
|
|
89
|
+
\"\"\"(Optional) async native implementation.\"\"\"
|
|
90
|
+
return self.docs[:self.k]
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
!!! example "Simple retriever based on a scikit-learn vectorizer"
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from sklearn.metrics.pairwise import cosine_similarity
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class TFIDFRetriever(BaseRetriever, BaseModel):
|
|
100
|
+
vectorizer: Any
|
|
101
|
+
docs: list[Document]
|
|
102
|
+
tfidf_array: Any
|
|
103
|
+
k: int = 4
|
|
104
|
+
|
|
105
|
+
class Config:
|
|
106
|
+
arbitrary_types_allowed = True
|
|
107
|
+
|
|
108
|
+
def _get_relevant_documents(self, query: str) -> list[Document]:
|
|
109
|
+
# Ip -- (n_docs,x), Op -- (n_docs,n_Feats)
|
|
110
|
+
query_vec = self.vectorizer.transform([query])
|
|
111
|
+
# Op -- (n_docs,1) -- Cosine Sim with each doc
|
|
112
|
+
results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))
|
|
113
|
+
return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]
|
|
114
|
+
```
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
model_config = ConfigDict(
|
|
118
|
+
arbitrary_types_allowed=True,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
_new_arg_supported: bool = False
|
|
122
|
+
|
|
123
|
+
_expects_other_args: bool = False
|
|
124
|
+
|
|
125
|
+
tags: list[str] | None = None
|
|
126
|
+
"""Optional list of tags associated with the retriever.
|
|
127
|
+
|
|
128
|
+
These tags will be associated with each call to this retriever,
|
|
129
|
+
and passed as arguments to the handlers defined in `callbacks`.
|
|
130
|
+
|
|
131
|
+
You can use these to eg identify a specific instance of a retriever with its
|
|
132
|
+
use case.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
metadata: dict[str, Any] | None = None
|
|
136
|
+
"""Optional metadata associated with the retriever.
|
|
137
|
+
|
|
138
|
+
This metadata will be associated with each call to this retriever,
|
|
139
|
+
and passed as arguments to the handlers defined in `callbacks`.
|
|
140
|
+
|
|
141
|
+
You can use these to eg identify a specific instance of a retriever with its
|
|
142
|
+
use case.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
@override
|
|
146
|
+
def __init_subclass__(cls, **kwargs: Any) -> None:
|
|
147
|
+
super().__init_subclass__(**kwargs)
|
|
148
|
+
parameters = signature(cls._get_relevant_documents).parameters
|
|
149
|
+
cls._new_arg_supported = parameters.get("run_manager") is not None
|
|
150
|
+
if (
|
|
151
|
+
not cls._new_arg_supported
|
|
152
|
+
and cls._aget_relevant_documents == BaseRetriever._aget_relevant_documents
|
|
153
|
+
):
|
|
154
|
+
# we need to tolerate no run_manager in _aget_relevant_documents signature
|
|
155
|
+
async def _aget_relevant_documents(
|
|
156
|
+
self: Self, query: str
|
|
157
|
+
) -> list[Document]:
|
|
158
|
+
return await run_in_executor(None, self._get_relevant_documents, query) # type: ignore[call-arg]
|
|
159
|
+
|
|
160
|
+
cls._aget_relevant_documents = _aget_relevant_documents # type: ignore[assignment]
|
|
161
|
+
|
|
162
|
+
# If a V1 retriever broke the interface and expects additional arguments
|
|
163
|
+
cls._expects_other_args = (
|
|
164
|
+
len(set(parameters.keys()) - {"self", "query", "run_manager"}) > 0
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
def _get_ls_params(self, **_kwargs: Any) -> LangSmithRetrieverParams:
|
|
168
|
+
"""Get standard params for tracing."""
|
|
169
|
+
default_retriever_name = self.get_name()
|
|
170
|
+
if default_retriever_name.startswith("Retriever"):
|
|
171
|
+
default_retriever_name = default_retriever_name[9:]
|
|
172
|
+
elif default_retriever_name.endswith("Retriever"):
|
|
173
|
+
default_retriever_name = default_retriever_name[:-9]
|
|
174
|
+
default_retriever_name = default_retriever_name.lower()
|
|
175
|
+
|
|
176
|
+
return LangSmithRetrieverParams(ls_retriever_name=default_retriever_name)
|
|
177
|
+
|
|
178
|
+
@override
|
|
179
|
+
def invoke(
|
|
180
|
+
self, input: str, config: RunnableConfig | None = None, **kwargs: Any
|
|
181
|
+
) -> list[Document]:
|
|
182
|
+
"""Invoke the retriever to get relevant documents.
|
|
183
|
+
|
|
184
|
+
Main entry point for synchronous retriever invocations.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
input: The query string.
|
|
188
|
+
config: Configuration for the retriever.
|
|
189
|
+
**kwargs: Additional arguments to pass to the retriever.
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
List of relevant documents.
|
|
193
|
+
|
|
194
|
+
Examples:
|
|
195
|
+
```python
|
|
196
|
+
retriever.invoke("query")
|
|
197
|
+
```
|
|
198
|
+
"""
|
|
199
|
+
config = ensure_config(config)
|
|
200
|
+
inheritable_metadata = {
|
|
201
|
+
**(config.get("metadata") or {}),
|
|
202
|
+
**self._get_ls_params(**kwargs),
|
|
203
|
+
}
|
|
204
|
+
callback_manager = CallbackManager.configure(
|
|
205
|
+
config.get("callbacks"),
|
|
206
|
+
None,
|
|
207
|
+
verbose=kwargs.get("verbose", False),
|
|
208
|
+
inheritable_tags=config.get("tags"),
|
|
209
|
+
local_tags=self.tags,
|
|
210
|
+
inheritable_metadata=inheritable_metadata,
|
|
211
|
+
local_metadata=self.metadata,
|
|
212
|
+
)
|
|
213
|
+
run_manager = callback_manager.on_retriever_start(
|
|
214
|
+
None,
|
|
215
|
+
input,
|
|
216
|
+
name=config.get("run_name") or self.get_name(),
|
|
217
|
+
run_id=kwargs.pop("run_id", None),
|
|
218
|
+
)
|
|
219
|
+
try:
|
|
220
|
+
kwargs_ = kwargs if self._expects_other_args else {}
|
|
221
|
+
if self._new_arg_supported:
|
|
222
|
+
result = self._get_relevant_documents(
|
|
223
|
+
input, run_manager=run_manager, **kwargs_
|
|
224
|
+
)
|
|
225
|
+
else:
|
|
226
|
+
result = self._get_relevant_documents(input, **kwargs_)
|
|
227
|
+
except Exception as e:
|
|
228
|
+
run_manager.on_retriever_error(e)
|
|
229
|
+
raise
|
|
230
|
+
else:
|
|
231
|
+
run_manager.on_retriever_end(
|
|
232
|
+
result,
|
|
233
|
+
)
|
|
234
|
+
return result
|
|
235
|
+
|
|
236
|
+
@override
|
|
237
|
+
async def ainvoke(
|
|
238
|
+
self,
|
|
239
|
+
input: str,
|
|
240
|
+
config: RunnableConfig | None = None,
|
|
241
|
+
**kwargs: Any,
|
|
242
|
+
) -> list[Document]:
|
|
243
|
+
"""Asynchronously invoke the retriever to get relevant documents.
|
|
244
|
+
|
|
245
|
+
Main entry point for asynchronous retriever invocations.
|
|
246
|
+
|
|
247
|
+
Args:
|
|
248
|
+
input: The query string.
|
|
249
|
+
config: Configuration for the retriever.
|
|
250
|
+
**kwargs: Additional arguments to pass to the retriever.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
List of relevant documents.
|
|
254
|
+
|
|
255
|
+
Examples:
|
|
256
|
+
```python
|
|
257
|
+
await retriever.ainvoke("query")
|
|
258
|
+
```
|
|
259
|
+
"""
|
|
260
|
+
config = ensure_config(config)
|
|
261
|
+
inheritable_metadata = {
|
|
262
|
+
**(config.get("metadata") or {}),
|
|
263
|
+
**self._get_ls_params(**kwargs),
|
|
264
|
+
}
|
|
265
|
+
callback_manager = AsyncCallbackManager.configure(
|
|
266
|
+
config.get("callbacks"),
|
|
267
|
+
None,
|
|
268
|
+
verbose=kwargs.get("verbose", False),
|
|
269
|
+
inheritable_tags=config.get("tags"),
|
|
270
|
+
local_tags=self.tags,
|
|
271
|
+
inheritable_metadata=inheritable_metadata,
|
|
272
|
+
local_metadata=self.metadata,
|
|
273
|
+
)
|
|
274
|
+
run_manager = await callback_manager.on_retriever_start(
|
|
275
|
+
None,
|
|
276
|
+
input,
|
|
277
|
+
name=config.get("run_name") or self.get_name(),
|
|
278
|
+
run_id=kwargs.pop("run_id", None),
|
|
279
|
+
)
|
|
280
|
+
try:
|
|
281
|
+
kwargs_ = kwargs if self._expects_other_args else {}
|
|
282
|
+
if self._new_arg_supported:
|
|
283
|
+
result = await self._aget_relevant_documents(
|
|
284
|
+
input, run_manager=run_manager, **kwargs_
|
|
285
|
+
)
|
|
286
|
+
else:
|
|
287
|
+
result = await self._aget_relevant_documents(input, **kwargs_)
|
|
288
|
+
except Exception as e:
|
|
289
|
+
await run_manager.on_retriever_error(e)
|
|
290
|
+
raise
|
|
291
|
+
else:
|
|
292
|
+
await run_manager.on_retriever_end(
|
|
293
|
+
result,
|
|
294
|
+
)
|
|
295
|
+
return result
|
|
296
|
+
|
|
297
|
+
@abstractmethod
|
|
298
|
+
def _get_relevant_documents(
|
|
299
|
+
self, query: str, *, run_manager: CallbackManagerForRetrieverRun
|
|
300
|
+
) -> list[Document]:
|
|
301
|
+
"""Get documents relevant to a query.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
query: String to find relevant documents for.
|
|
305
|
+
run_manager: The callback handler to use.
|
|
306
|
+
|
|
307
|
+
Returns:
|
|
308
|
+
List of relevant documents.
|
|
309
|
+
"""
|
|
310
|
+
|
|
311
|
+
async def _aget_relevant_documents(
|
|
312
|
+
self, query: str, *, run_manager: AsyncCallbackManagerForRetrieverRun
|
|
313
|
+
) -> list[Document]:
|
|
314
|
+
"""Asynchronously get documents relevant to a query.
|
|
315
|
+
|
|
316
|
+
Args:
|
|
317
|
+
query: String to find relevant documents for
|
|
318
|
+
run_manager: The callback handler to use
|
|
319
|
+
|
|
320
|
+
Returns:
|
|
321
|
+
List of relevant documents
|
|
322
|
+
"""
|
|
323
|
+
return await run_in_executor(
|
|
324
|
+
None,
|
|
325
|
+
self._get_relevant_documents,
|
|
326
|
+
query,
|
|
327
|
+
run_manager=run_manager.get_sync(),
|
|
328
|
+
)
|