1,951 matches across 25 files for func main lang:Python lang:Python lang:Python lang:Python
snippet_mode: grep · sorted by relevance
187
188
189▶if __name__ == "__main__":
190 # Get the TOML file path from the command line argument
191 toml_file = sys.argv[1]
· · ·
194 assert versions_for in ["release", "pull_request"]
195
196▶ # Call the function to get the minimum versions
197 min_versions = get_min_version_from_toml(toml_file, versions_for, python_version)
198
1▶"""Helper functions for marking parts of the LangChain API as beta.
2
3This module was loosely adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
· · ·
3▶This module was loosely adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
4module.
5
· · ·
11
12import contextlib
13▶import functools
14import inspect
15import warnings
· · ·
37 addendum: str = "",
38) -> Callable[[T], T]:
39▶ """Decorator to mark a function, a class, or a property as beta.
40
41 When marking a classmethod, a staticmethod, or a property, the `@beta` decorator
· · ·
53 The %(since)s, %(name)s, %(alternative)s, %(obj_type)s, %(addendum)s, and
54 %(removal)s format specifiers will be replaced by the values of the
55▶ respective arguments passed to this function.
56 name: The name of the beta object.
57 obj_type: The object type being beta.
+ 16 more matches in this file
1▶"""Helper functions for deprecating parts of the LangChain API.
2
3This module was adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
· · ·
3▶This module was adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
4module.
5
· · ·
11
12import contextlib
13▶import functools
14import inspect
15import sys
· · ·
131 package: str = "",
132) -> Callable[[T], T]:
133▶ """Decorator to mark a function, a class, or a property as deprecated.
134
135 When deprecating a classmethod, a staticmethod, or a property, the `@deprecated`
· · ·
143
144 Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to
145▶ 'class' if decorating a class, 'attribute' if decorating a property, and 'function'
146 otherwise.
147
+ 22 more matches in this file
80 {
81 "localhost",
82▶ "localhost.localdomain",
83 "host.docker.internal",
84 }
· · ·
142 """Return a reason string if *addr* falls in a blocked range, else None."""
143 # NOTE: if profiling shows this is a hot path, consider memoising with
144▶ # @functools.lru_cache (key on (addr, id(policy))).
145 if isinstance(addr, ipaddress.IPv4Address):
146 if policy.block_private_ips:
· · ·
185
186# ---------------------------------------------------------------------------
187▶# Public validation functions
188# ---------------------------------------------------------------------------
189
5import asyncio
6import atexit
7▶import functools
8import logging
9from abc import ABC, abstractmethod
· · ·
215
216
217▶Func = TypeVar("Func", bound=Callable[..., Any])
218
219
· · ·
220▶def shielded(func: Func) -> Func:
221 """Makes so an awaitable method is always shielded from cancellation.
222
· · ·
223 Args:
224▶ func: The function to shield.
225
226 Returns:
· · ·
227▶ The shielded function
228
229 """
+ 13 more matches in this file
57
58 get_text_length: Callable[[str], int] = _get_length_based
59▶ """Function to measure prompt length. Defaults to word count."""
60
61 max_length: int = 2048
· · ·
105 """
106 inputs = " ".join(input_variables.values())
107▶ remaining_length = self.max_length - self.get_text_length(inputs)
108 i = 0
109 examples = []
· · ·
110▶ while remaining_length > 0 and i < len(self.examples):
111 new_length = remaining_length - self.example_text_lengths[i]
112 if new_length < 0:
· · ·
111▶ new_length = remaining_length - self.example_text_lengths[i]
112 if new_length < 0:
113 break
· · ·
114 examples.append(self.examples[i])
115▶ remaining_length = new_length
116 i += 1
117 return examples
37 already been indexed, and to only index new documents.
38
39▶ The main benefit of this abstraction is that it works across many vectorstores.
40 To be supported, a `VectorStore` needs to only support the ability to add and
41 delete documents by ID. Using the record manager, the indexing API will
· · ·
43 that have already been indexed.
44
45▶ The main constraints of this abstraction are:
46
47 1. It relies on the time-stamps to determine which documents have been
· · ·
515 """Upsert documents into the index.
516
517▶ The upsert functionality should utilize the ID field of the content object
518 if it is provided. If the ID is not provided, the upsert method is free
519 to generate an ID for the content.
· · ·
538 """Add or update documents in the `VectorStore`. Async version of `upsert`.
539
540▶ The upsert functionality should utilize the ID field of the item
541 if it is provided. If the ID is not provided, the upsert method is free
542 to generate an ID for the item.
543 # formally declare but the consumer reads). It carries provider-side
544 # kwargs that don't map onto a typed protocol field — notably Gemini's
545▶ # `__gemini_function_call_thought_signatures__`, which the model
546 # requires on follow-up turns to replay prior thinking. Without this,
547 # streaming-assembled messages would silently drop data that
· · ·
565
566# ---------------------------------------------------------------------------
567▶# Main generators
568# ---------------------------------------------------------------------------
569
· · ·
624 # the streaming path silently diverges multi-turn behavior. Use
625 # `merge_dicts` because the same key can arrive in pieces across
626▶ # chunks (e.g. an accumulating `function_call`), matching how
627 # `AIMessageChunk` merges itself.
628 if msg.additional_kwargs:
19 """Filter out large/inappropriate fields from invocation params for tracing.
20
21▶ Removes fields like tools, functions, messages, response_format that can be large.
22
23 Args:
· · ·
27 The filtered parameters with large fields removed.
28 """
29▶ excluded_keys = {"tools", "functions", "messages", "response_format"}
30 return {k: v for k, v in params.items() if k not in excluded_keys}
31
· · ·
49 If `None`, match any valid OpenAI data block type. Note that this means that
50 if the block has a valid OpenAI data type but the filter_ is set to a
51▶ different type, this function will return False.
52
53 Returns:
· · ·
148 - LangChain v1 standard content blocks
149
150▶ This function extends support to:
151 - `[Audio](https://platform.openai.com/docs/api-reference/chat/create) and
152 `[file](https://platform.openai.com/docs/api-reference/files) data in OpenAI
· · ·
158 !!! warning "Behavior changed in `langchain-core` 1.0.0"
159
160▶ In previous versions, this function returned messages in LangChain v0 format.
161 Now, it returns messages in LangChain v1 format, which upgraded chat models now
162 expect to receive when passing back in message history. For backward
+ 3 more matches in this file
737 Does not mutate `self._text_acc` (the delta-sum accumulator) —
738 the message-wide projection value is derived from per-block
739▶ storage at `_finish` time, so reconciliation remains correct
740 regardless of finish ordering across blocks.
741 """
· · ·
765 # would be ambiguous mid-stream). `_text_acc` is not
766 # spliced — the final value is computed from per-block
767▶ # storage at `_finish`, so this remains correct even when
768 # other blocks have added to `_text_acc` in between.
769 self._text_per_block[idx] = full_text
· · ·
900 # Off-spec extension carrying provider-side `additional_kwargs`
901 # that don't map onto a typed protocol field (e.g. Gemini's
902▶ # `__gemini_function_call_thought_signatures__`). The compat
903 # bridge emits this on `message-finish` so the assembled message
904 # carries the same data `ainvoke` would have preserved.
· · ·
1180
1181 def _drain(self) -> None:
1182▶ """Pull all remaining events until done."""
1183 if self._done:
1184 return
10from abc import ABC, abstractmethod
11from collections.abc import AsyncIterator, Callable, Iterator, Sequence
12▶from functools import cached_property
13from operator import itemgetter
14from typing import TYPE_CHECKING, Any, Literal, cast, overload
· · ·
88 _V2StreamingCallbackHandler,
89)
90▶from langchain_core.utils.function_calling import (
91 convert_to_json_schema,
92 convert_to_openai_tool,
· · ·
276 Methods that actually call the underlying model.
277
278▶ This table provides a brief overview of the main imperative methods. Please see the base `Runnable` reference for full documentation.
279
280 | Method | Input | Output | Description |
· · ·
293 Methods for creating another `Runnable` using the chat model.
294
295▶ This table provides a brief overview of the main declarative methods. Please see the reference for each method for full documentation.
296
297 | Method | Description |
· · ·
336 - If `False` (Default), will always use streaming case if available.
337
338▶ The main reason for this flag is that code might be written using `stream` and
339 a user may want to swap out a given model for another model whose implementation
340 does not properly support streaming.
+ 12 more matches in this file
5where that class is actually located.
6
7▶This mapping helps maintain the ability to serialize and deserialize
8well-known LangChain objects even if they are moved around in the codebase
9across different LangChain versions.
· · ·
51 "ChatMessage",
52 ),
53▶ ("langchain", "schema", "messages", "FunctionMessage"): (
54 "langchain_core",
55 "messages",
· · ·
56▶ "function",
57 "FunctionMessage",
58 ),
· · ·
57▶ "FunctionMessage",
58 ),
59 ("langchain", "schema", "messages", "HumanMessage"): (
· · ·
351 "HumanMessageChunk",
352 ),
353▶ ("langchain", "schema", "messages", "FunctionMessageChunk"): (
354 "langchain_core",
355 "messages",
+ 20 more matches in this file
48 """String-like object that supports both property and method access patterns.
49
50▶ Exists to maintain backward compatibility while transitioning from method-based to
51 property-based text access in message objects. In LangChain <v1.0, message text was
52 accessed via `.text()` method calls. In v1.0=<, the preferred pattern is property
· · ·
413 """Message chunks support concatenation with other message chunks.
414
415▶ This functionality is useful to combine message chunks yielded from
416 a streaming model into a complete message.
417
111```
112
113▶Factory functions offer benefits such as:
114
115- Automatic ID generation (when not provided)
· · ·
133 response, not the original document (as specified in the `url`).
134
135▶ !!! note "Factory function"
136
137 `create_citation` may also be used as a factory to create a `Citation`.
· · ·
208 """Text output from a LLM.
209
210▶ This typically represents the main text content of a message, such as the response
211 from a language model or the text of a user message.
212
· · ·
213▶ !!! note "Factory function"
214
215 `create_text_block` may also be used as a factory to create a
· · ·
256 and an identifier of "123".
257
258▶ !!! note "Factory function"
259
260 `create_tool_call` may also be used as a factory to create a
+ 7 more matches in this file
1▶"""Module contains utility functions for working with messages.
2
3Some examples of what you can do with these functions include:
· · ·
3▶Some examples of what you can do with these functions include:
4
5* Convert messages to strings (serialization)
· · ·
16import math
17from collections.abc import Callable, Iterable, Sequence
18▶from functools import partial, wraps
19from typing import (
20 TYPE_CHECKING,
· · ·
43 is_data_content_block,
44)
45▶from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
46from langchain_core.messages.human import HumanMessage, HumanMessageChunk
47from langchain_core.messages.modifier import RemoveMessage
· · ·
48from langchain_core.messages.system import SystemMessage, SystemMessageChunk
49from langchain_core.messages.tool import ToolCall, ToolMessage, ToolMessageChunk
50▶from langchain_core.utils.function_calling import convert_to_openai_tool
51
52if TYPE_CHECKING:
+ 62 more matches in this file
6import collections
7import contextlib
8▶import functools
9import inspect
10import threading
· · ·
21)
22from concurrent.futures import FIRST_COMPLETED, wait
23▶from functools import wraps
24from itertools import tee
25from operator import itemgetter
· · ·
51from langchain_core.runnables.config import (
52 RunnableConfig,
53▶ acall_func_with_variable_args,
54 call_func_with_variable_args,
55 ensure_config,
· · ·
54▶ call_func_with_variable_args,
55 ensure_config,
56 get_async_callback_manager_for_config,
· · ·
75 gated_coro,
76 gather_with_concurrency,
77▶ get_function_first_arg_dict_keys,
78 get_function_nonlocals,
79 get_lambda_source,
+ 199 more matches in this file
131
132 def render_node(key: str, node: Node, indent: str = "\t") -> str:
133▶ """Helper function to render a node with consistent formatting."""
134 node_name = node.name.split(":")[-1]
135 label = (
· · ·
227 add_subgraph(edge_groups.get("", []), "")
228
229▶ # Add remaining subgraphs with edges
230 for prefix, edges_ in edge_groups.items():
231 if not prefix or ":" in prefix:
66
67 def foo(input) -> None:
68▶ '''Fake function that raises an exception.'''
69 raise ValueError(f"Invoking foo failed. At time {time.time()}")
70
· · ·
240 with attempt:
241 # Retry for inputs that have not yet succeeded
242▶ # Determine which original indices remain.
243 remaining_indices = [
244 i for i in range(len(inputs)) if i not in results_map
· · ·
243▶ remaining_indices = [
244 i for i in range(len(inputs)) if i not in results_map
245 ]
· · ·
246▶ if not remaining_indices:
247 break
248 pending_inputs = [inputs[i] for i in remaining_indices]
· · ·
248▶ pending_inputs = [inputs[i] for i in remaining_indices]
249 pending_configs = [config[i] for i in remaining_indices]
250 pending_run_managers = [run_manager[i] for i in remaining_indices]
+ 11 more matches in this file
3from __future__ import annotations
4
5▶import functools
6import inspect
7import json
· · ·
55from langchain_core.runnables.config import set_config_context
56from langchain_core.runnables.utils import coro_with_context
57▶from langchain_core.utils.function_calling import (
58 _parse_google_docstring,
59 _py_38_safe_origin,
· · ·
123
124
125▶def _parse_python_function_docstring(
126 function: Callable[..., Any],
127 annotations: dict[str, Any],
· · ·
126▶ function: Callable[..., Any],
127 annotations: dict[str, Any],
128 *,
· · ·
129 error_on_invalid_docstring: bool = False,
130) -> tuple[str, dict[str, str]]:
131▶ """Parse function and argument descriptions from a docstring.
132
133 Assumes the function docstring follows Google Python style guide.
+ 52 more matches in this file
34
35
36▶# https://github.com/python/cpython/blob/main/Lib/test/test_asyncgen.py#L54
37@deprecated(since="1.1.2", removal="2.0.0")
38def py_anext(
· · ·
111 """An individual iterator of a `tee`.
112
113▶ This function is a generator that yields items from the shared iterator
114 `iterator`. It buffers items until the least advanced iterator has yielded them as
115 well.
· · ·
326 size: int, iterable: AsyncIterable[T]
327) -> AsyncIterator[list[T]]:
328▶ """Utility batching function for async iterables.
329
330 Args:
35
36 The LLM response for `action_input` may be a multiline string containing unescaped
37▶ newlines, tabs or quotes. This function replaces those characters with their escaped
38 counterparts. (newlines in JSON must be double-escaped: `\\n`).
39
· · ·
121 # Try to parse mods of string until we succeed or run out of characters.
122 while new_chars:
123▶ # Close any remaining open structures in the reverse
124 # order that they were opened.
125 # Attempt to parse the modified string as JSON.
· · ·
177 Args:
178 json_str: The JSON string to parse.
179▶ parser: Optional custom parser function.
180
181 Returns:
1▶"""UUID utility functions.
2
3This module exports a uuid7 function to generate monotonic, time-ordered UUIDs
· · ·
3▶This module exports a uuid7 function to generate monotonic, time-ordered UUIDs
4for tracing and similar operations.
5"""
· · ·
19
20def _to_timestamp_and_nanos(nanoseconds: int) -> tuple[int, int]:
21▶ """Split a nanosecond timestamp into seconds and remaining nanoseconds."""
22 seconds, nanos = divmod(nanoseconds, _NANOS_PER_SECOND)
23 return seconds, nanos
157 This test specifically addresses the issue where async callbacks decorated
158 with @shielded do not properly preserve context variables, breaking
159▶ instrumentation and other context-dependent functionality.
160
161 The issue manifests in callbacks that use the @shielded decorator:
· · ·
205
206 # The context should be preserved in shielded callbacks
207▶ # This was the main issue - shielded decorators were not preserving context
208 assert handler.context_values == ["test_value", "test_value"], (
209 f"Expected context values ['test_value', 'test_value'], "
303
304
305▶# Tests for dumps() function
306def test_dumps_basic_serialization() -> None:
307 """Test basic string serialization with `dumps()`."""
· · ·
320
321def test_dumps_pretty_formatting() -> None:
322▶ """Test pretty printing functionality."""
323 foo = Foo(bar=1, baz="hello")
324
· · ·
387 # Serializable object should be properly serialized
388 assert parsed["serializable"]["type"] == "constructor"
389▶ # Primitives should remain unchanged
390 assert parsed["list"] == [1, 2, {"nested": "value"}]
391 assert parsed["primitive"] == "string"
· · ·
480 }
481
482▶ # Even though AIMessage is allowed, the metadata should remain as dict
483 loaded = load(malicious_data, allowed_objects=[Document, AIMessage])
484 assert loaded.page_content == "test"
· · ·
708
709 def test_init_validator_with_loads(self) -> None:
710▶ """Test that `init_validator` works with `loads()` function."""
711 doc = Document(page_content="test", metadata={"key": "value"})
712 json_str = dumps(doc)
+ 2 more matches in this file