← Repo overview
/
langchain-ai/ langchain
/
search
@d260c52
214 matches across 25 files for func main
snippet_mode: auto · sorted by relevance
35
36 #
37 ▶ # Helper functions
38 #
39
· · ·
193
194 #
195 ▶ # The main tokenizing function
196 #
197
· · ·
324
325 #
326 ▶ # Helper functions
327 #
328
· · ·
459
460 #
461 ▶ # The main rendering function
462 #
463 g_token_cache: dict[str, list[tuple[str, str]]] = {}
1 ▶ """Helper functions for deprecating parts of the LangChain API.
2
3 This module was adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
· · ·
11
12 import contextlib
13 ▶ import functools
14 import inspect
15 import 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`
· · ·
389 _name = _name or cast("type", obj).__qualname__
390 if not _obj_type:
391 ▶ # edge case: when a function is within another function
392 # within a test, this will call it a "method" not a "function"
393 _obj_type = "function" if "." not in _name else "method"
· · ·
392 ▶ # within a test, this will call it a "method" not a "function"
393 _obj_type = "function" if "." not in _name else "method"
394 wrapped = obj
+ 7 more matches in this file
197 # Split along class definitions
198 "\nclass ",
199 ▶ # Split along function definitions
200 "\nvoid ",
201 "\nint ",
· · ·
216 if language == Language.GO:
217 return [
218 ▶ # Split along function definitions
219 "\nfunc ",
220 "\nvar ",
· · ·
280 if language == Language.JS:
281 return [
282 ▶ # Split along function definitions
283 "\nfunction ",
284 "\nconst ",
· · ·
307 # Split along class definitions
308 "\nclass ",
309 ▶ # Split along function definitions
310 "\nfunction ",
311 "\nconst ",
· · ·
327 if language == Language.PHP:
328 return [
329 ▶ # Split along function definitions
330 "\nfunction ",
331 # Split along class definitions
+ 8 more matches in this file
56
57 search_kwargs: dict = Field(default_factory=dict)
58 ▶ """Keyword arguments to pass to the search function."""
59
60 search_type: SearchType = SearchType.similarity
· · ·
105 sub_docs = self.vectorstore.similarity_search(query, **self.search_kwargs)
106
107 ▶ # We do this to maintain the order of the IDs that are returned
108 ids = []
109 for d in sub_docs:
· · ·
147 )
148
149 ▶ # We do this to maintain the order of the IDs that are returned
150 ids = []
151 for d in sub_docs:
52
53 Runs before built-in stream transformers so the redacted text is what
54 ▶ every downstream consumer sees — both the main protocol event log and
55 the `run.messages` projection that `MessagesTransformer` snapshots into.
56
· · ·
105 with `_redact_value` returns a fresh structure where every
106 message has a redacted copy of its content — the original
107 ▶ objects in graph state remain intact for the state-level
108 enforcer (`apply_to_tool_results` via `before_model`) to act on
109 independently when the agent loops back.
· · ·
582 * `hash`: Replace with deterministic hash (format: `<type_hash:digest>`)
583
584 ▶ detector: Custom detector function or regex pattern.
585
586 * If `Callable`: Function that takes content string and returns
· · ·
586 ▶ * If `Callable`: Function that takes content string and returns
587 list of `PIIMatch` objects
588 * If `str`: Regex pattern to match PII
· · ·
646 # moment a complete PII pattern is detected, failing the run
647 # via langgraph's `StreamMux.afail` path. The state-level
648 ▶ # `after_model` / `before_model` hooks remain a backstop for
649 # non-streaming consumers.
650 if self.apply_to_output or self.apply_to_tool_results:
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")
38 def 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:
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:
· · ·
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
· · ·
259 for message in messages:
260 # We preserve input messages - the caller may reuse them elsewhere and expects
261 ▶ # them to remain unchanged. We only create a copy if we need to translate.
262 formatted_message = message
263
131 error_on_invalid_docstring: bool = False,
132 ) -> tuple[str, dict[str, str]]:
133 ▶ """Parse function and argument descriptions from a docstring.
134
135 Assumes the function docstring follows Google Python style guide.
· · ·
135 ▶ Assumes the function docstring follows Google Python style guide.
136
137 Args:
· · ·
138 ▶ function: The function to parse the docstring from.
139 annotations: Type annotations for the function parameters.
140 error_on_invalid_docstring: Whether to raise an error on invalid docstring.
· · ·
139 ▶ annotations: Type annotations for the function parameters.
140 error_on_invalid_docstring: Whether to raise an error on invalid docstring.
141
· · ·
142 Returns:
143 ▶ A tuple containing the function description and argument descriptions.
144 """
145 docstring = inspect.getdoc(function)
+ 6 more matches in this file
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 ▶ """Module contains utility functions for working with messages.
2
3 Some 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)
· · ·
260 ai_prefix: The prefix to use for `AIMessage`.
261 system_prefix: The prefix to use for `SystemMessage`.
262 ▶ function_prefix: The prefix to use for `FunctionMessage`.
263 tool_prefix: The prefix to use for `ToolMessage`.
264
· · ·
1331 trim_messages(
1332 messages,
1333 ▶ # When `len` is passed in as the token counter function,
1334 # max_tokens will count the number of messages in the chat history.
1335 max_tokens=4,
· · ·
1336 strategy="last",
1337 ▶ # Passing in `len` as a token counter function will
1338 # count the number of messages in the chat history.
1339 token_counter=len,
+ 2 more matches in this file
959
960 After calling, sync invocations on this model will raise. Async
961 ▶ invocations remain available until `aclose()` is also called. Safe to
962 call multiple times.
963 """
· · ·
1259 tools: A list of tool definitions to bind to this chat model.
1260
1261 ▶ Supports any tool definition handled by [`convert_to_openai_tool`][langchain_core.utils.function_calling.convert_to_openai_tool].
1262 tool_choice: Which tool to require the model to call.
1263 Must be the name of the single provided function,
· · ·
1263 ▶ Must be the name of the single provided function,
1264 `'auto'` to automatically determine which function to call
1265 with the option to not call any function, `'any'` to enforce that some
· · ·
1431 )
1432 # -> {
1433 ▶ # 'raw': AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Ao02pnFYXD6GN1yzc0uXPsvF', 'function': {'arguments': '{"answer":"They weigh the same.","justification":"Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ."}', 'name': 'AnswerWithJustification'}, 'type': 'function'}]}),
1434 # 'parsed': AnswerWithJustification(answer='They weigh the same.', justification='Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volume or density of the objects may differ.'),
1435 # 'parsing_error': None
562 # formally declare but the consumer reads). It carries provider-side
563 # kwargs that don't map onto a typed protocol field — notably Gemini's
564 ▶ # `__gemini_function_call_thought_signatures__`, which the model
565 # requires on follow-up turns to replay prior thinking. Without this,
566 # streaming-assembled messages would silently drop data that
· · ·
584
585 # ---------------------------------------------------------------------------
586 ▶ # Main generators
587 # ---------------------------------------------------------------------------
588
· · ·
643 # the streaming path silently diverges multi-turn behavior. Use
644 # `merge_dicts` because the same key can arrive in pieces across
645 ▶ # chunks (e.g. an accumulating `function_call`), matching how
646 # `AIMessageChunk` merges itself.
647 if msg.additional_kwargs:
911 """
912
913 ▶ def decorator(func: CallableT) -> CallableT:
914 if can_jump_to is not None:
915 func.__can_jump_to__ = can_jump_to # type: ignore[attr-defined]
· · ·
915 ▶ func.__can_jump_to__ = can_jump_to # type: ignore[attr-defined]
916 return func
917
· · ·
916 ▶ return func
917
918 return decorator
· · ·
921 @overload
922 def before_model(
923 ▶ func: _CallableWithStateAndRuntime[StateT, ContextT],
924 ) -> AgentMiddleware[StateT, ContextT]: ...
925
· · ·
927 @overload
928 def before_model(
929 ▶ func: None = None,
930 *,
931 state_schema: type[StateT] | None = None,
+ 1 more matches in this file
59 The Chain interface makes it easy to create apps that are:
60 - Stateful: add Memory to any Chain to give it state,
61 ▶ - Observable: pass Callbacks to a Chain to execute additional functionality,
62 like logging, outside the main sequence of component calls,
63 - Composable: the Chain API is flexible enough that it is easy to combine
· · ·
62 ▶ like logging, outside the main sequence of component calls,
63 - Composable: the Chain API is flexible enough that it is easy to combine
64 Chains with other components, including other Chains.
· · ·
65
66 ▶ The main methods exposed by chains are:
67 - `__call__`: Chains are callable. The `__call__` method is the primary way to
68 execute a Chain. This takes inputs as a dictionary and returns a
145 """Return a reason string if *addr* falls in a blocked range, else None."""
146 # NOTE: if profiling shows this is a hot path, consider memoising with
147 ▶ # @functools.lru_cache (key on (addr, id(policy))).
148 if isinstance(addr, ipaddress.IPv4Address):
149 if policy.block_private_ips:
· · ·
188
189 # ---------------------------------------------------------------------------
190 ▶ # Public validation functions
191 # ---------------------------------------------------------------------------
192
1 ▶ """Helper functions for marking parts of the LangChain API as beta.
2
3 This module was loosely adapted from matplotlib's [`_api/deprecation.py`](https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py)
· · ·
11
12 import contextlib
13 ▶ import functools
14 import inspect
15 import warnings
· · ·
200 The wrapped function.
201 """
202 ▶ wrapper = functools.wraps(wrapped)(wrapper)
203 wrapper.__doc__ = new_doc
204 return cast("T", wrapper)
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
1 ▶ """UUID utility functions.
2
3 This module exports a uuid7 function to generate monotonic, time-ordered UUIDs
· · ·
3 ▶ This module exports a uuid7 function to generate monotonic, time-ordered UUIDs
4 for tracing and similar operations.
5 """
· · ·
19
20 def _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
221
222 This middleware monitors message token counts and automatically summarizes older
223 ▶ messages when a threshold is reached, preserving recent messages and maintaining
224 context continuity by ensuring AI/Tool message pairs remain together.
225 """
· · ·
224 ▶ context continuity by ensuring AI/Tool message pairs remain together.
225 """
226
187 if isinstance(arguments, dict):
188 for key, value in arguments.items():
189 ▶ # Filter out metadata fields like 'functionName' that echo function name
190 if key == "functionName" and value == function_name:
191 continue
· · ·
1433 tools: A list of tool definitions to bind to this chat model.
1434
1435 ▶ Supports any tool definition handled by [`convert_to_openai_tool`][langchain_core.utils.function_calling.convert_to_openai_tool].
1436 tool_choice: If provided, which tool for model to call. **This parameter
1437 is currently ignored as it is not supported by Ollama.**
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.
249 If defined, less similar results will not be returned.
250 Score of the returned result might be higher or smaller than the
251 ▶ threshold depending on the Distance function used.
252 E.g. for cosine similarity only higher scores will be returned.
253 consistency:
· · ·
2109 if self.embeddings is not None:
2110 embedding = self.embeddings.embed_query(query)
2111 ▶ elif self._embeddings_function is not None:
2112 embedding = self._embeddings_function(query)
2113 else:
· · ·
2112 ▶ embedding = self._embeddings_function(query)
2113 else:
2114 msg = "Neither of embeddings or embedding_function is set"
· · ·
2130 if self.embeddings is not None:
2131 embedding = await self.embeddings.aembed_query(query)
2132 ▶ elif self._embeddings_function is not None:
2133 embedding = self._embeddings_function(query)
2134 else:
· · ·
2133 ▶ embedding = self._embeddings_function(query)
2134 else:
2135 msg = "Neither of embeddings or embedding_function is set"
98 spec: OpenAPISpec,
99 ) -> tuple[list[dict[str, Any]], Callable]:
100 ▶ """OpenAPI spec to OpenAI function JSON Schema.
101
102 Convert a valid OpenAPI spec to the JSON Schema format expected for OpenAI
· · ·
103 ▶ functions.
104
105 Args:
· · ·
107
108 Returns:
109 ▶ Tuple of the OpenAI functions JSON schema and a default function for executing
110 a request based on the OpenAI function schema.
111 """
· · ·
110 ▶ a request based on the OpenAI function schema.
111 """
112 try:
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
105 @tool(args_schema=_MagicFunctionSchema)
106 def magic_function(_input: int) -> int:
107 ▶ """Apply a magic function to an input."""
108 return _input + 2
109
· · ·
111 @tool
112 def magic_function_no_args() -> int:
113 ▶ """Calculate a magic function."""
114 return 5
115
· · ·
2396 properly handles both JSON Schema and Pydantic V2 models.
2397
2398 ▶ `langchain_core` implements a [utility function](https://reference.langchain.com/python/langchain_core/utils/?h=convert_to_op#langchain_core.utils.function_calling.convert_to_openai_tool).
2399 that will accommodate most formats.
2400
· · ·
2550 properly handles Pydantic V2 models with optional parameters.
2551
2552 ▶ `langchain_core` implements a [utility function](https://reference.langchain.com/python/langchain_core/utils/?h=convert_to_op#langchain_core.utils.function_calling.convert_to_openai_tool).
2553 that will accommodate most formats.
2554
Search syntax
auth loginboth terms (AND is implicit)
auth OR logineither term
NOT path:vendorexclude matches
"exact phrase"quoted exact match
/func\s+Test/regex
handler~1fuzzy (Levenshtein 1)
file:*_test.gofilename glob
path:pkg/auth/**full path glob
lang:golanguage filter
Search any public repo from your terminal
This page calls POST /api/v1/code_search. Same tool, available over MCP for Claude/Cursor/Copilot.