1,969 matches across 25 files for func main
snippet_mode: grep · sorted by relevance
22 * [LangChain Forum](https://forum.langchain.com/),
23
24▶ **Note:** Do not begin work on a PR unless explicitly assigned to this issue by a maintainer.
25 - type: checkboxes
26 id: checks
· · ·
81 Please provide a clear and concise description of the feature you would like to see added to LangChain.
82
83▶ What specific functionality are you requesting? Be as detailed as possible.
84 placeholder: |
85 I would like LangChain to support...
· · ·
111 If you have ideas about how this feature could be implemented, please describe them here.
112
113▶ This is optional but can be helpful for maintainers to understand your vision.
114 placeholder: |
115 I think this could be implemented by...
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
66# `--accurate` mode for `--cc`?
67
68▶if __name__ != "__main__":
69 raise ImportError("{} should not be used as a module.".format(__name__))
70
· · ·
184 action="store_true",
185 help="""
186▶ Consider only the first parent, the "main branch", when evaluating merge commits.
187 Only effective when merge commits are processed, either when --merge is
188 used or when finding missing files after the first regular log search.
· · ·
318
319
320▶# Helper functions ############################################################
321
322
· · ·
337 https://git-scm.com/docs/git-config#Documentation/git-config.txt-corequotePath
338
339▶ This function reverts this encoding, so:
340 normalize(r'"Back\\slash_double\"quote_a\303\247a\303\255"') =>
341 r'Back\slash_double"quote_açaí')
· · ·
367
368def dummy(*_args, **_kwargs):
369▶ """No-op function used in dry-run tests"""
370
371
+ 6 more matches in this file
60 const squashMessage = `${title} (#${number})\n\n${fullBody}`;
61
62▶ async function findStickyComment() {
63 const comments = await github.paginate(github.rest.issues.listComments, {
64 ...context.repo,
· · ·
72 // turn this advisory job red on its own: fork PRs run with
73 // restricted tokens, secondary rate limits, transient API errors.
74▶ // Fall back to `core.summary` so a maintainer can paste the
75 // remediation manually. The check still fails — `setFailed` is
76 // invoked before this function, so the failure signal is already
· · ·
76▶ // invoked before this function, so the failure signal is already
77 // recorded by the time the comment write is attempted.
78 //
· · ·
80 // `findStickyComment` (e.g., pagination throwing) surfaces with
81 // its true cause instead of being misattributed to "fork PR token".
82▶ async function postStickyOrSummary(commentBody, summaryHeading) {
83 const existing = await findStickyComment();
84 try {
3# labeled "missing-issue-link", commented on, and closed.
4#
5▶# Maintainer override: an org member can reopen the PR or remove
6# "missing-issue-link" — both add "bypass-issue-check" and reopen.
7#
· · ·
32 check-issue-link:
33 # Run when the "external" label is added, on edit/reopen if already labeled,
34▶ # or when "missing-issue-link" is removed (triggers maintainer override check).
35 # Skip entirely when the PR already carries "trusted-contributor" or
36 # "bypass-issue-check".
· · ·
59
60 // ── Helper: ensure a label exists, then add it to the PR ────────
61▶ async function ensureAndAddLabel(labelName, color) {
62 try {
63 await github.rest.issues.getLabel({ owner, repo, name: labelName });
· · ·
83 // to be an org member, which GITHUB_TOKEN (an app installation
84 // token) never is — so it always returns 403.
85▶ async function senderIsOrgMember() {
86 const sender = context.payload.sender?.login;
87 if (!sender) {
· · ·
93 });
94 const perm = data.permission;
95▶ if (['admin', 'maintain', 'write'].includes(perm)) {
96 console.log(`${sender} has ${perm} permission — treating as maintainer`);
97 return { isMember: true, login: sender };
+ 20 more matches in this file
14│ ├── core/ # `langchain-core` primitives and base abstractions
15│ ├── langchain/ # `langchain-classic` (legacy, no new features)
16▶│ ├── langchain_v1/ # Actively maintained `langchain` package
17│ ├── partners/ # Third-party integrations
18│ │ ├── openai/ # OpenAI models and embeddings
· · ·
19│ │ ├── anthropic/ # Anthropic (Claude) integration
20│ │ ├── ollama/ # Local model support
21▶│ │ └── ... (other integrations maintained by the LangChain team)
22│ ├── text-splitters/ # Document chunking utilities
23│ ├── standard-tests/ # Shared test suite for integrations
· · ·
30- **Core layer** (`langchain-core`): Base abstractions, interfaces, and protocols. Users should not need to know about this layer directly.
31- **Implementation layer** (`langchain`): Concrete implementations and high-level public utilities
32▶- **Integration layer** (`partners/`): Third-party service integrations. Note that this monorepo is not exhaustive of all LangChain integrations; some are maintained in separate repos, such as `langchain-ai/langchain-google` and `langchain-ai/langchain-aws`. Usually these repos are cloned at the same level as this monorepo, so if needed, you can refer to their code directly by navigating to `../langchain-google/` from this monorepo.
33- **Testing layer** (`standard-tests/`): Standardized integration tests for partner integrations
34
· · ·
85#### Key config files
86
87▶- pyproject.toml: Main workspace configuration with dependency groups
88- uv.lock: Locked dependencies for reproducible builds
89- Makefile: Development tasks
· · ·
91#### PR and commit titles
92
93▶Follow Conventional Commits. See `.github/workflows/pr_lint.yml` for allowed types and scopes. All titles must include a scope with no exceptions — even for the main `langchain` package.
94
95- Start the text after `type(scope):` with a lowercase letter, unless the first word is a proper noun (e.g. `Azure`, `GitHub`, `OpenAI`) or a named entity (class, function, method, parameter, or variable name).
+ 13 more matches in this file
14│ ├── core/ # `langchain-core` primitives and base abstractions
15│ ├── langchain/ # `langchain-classic` (legacy, no new features)
16▶│ ├── langchain_v1/ # Actively maintained `langchain` package
17│ ├── partners/ # Third-party integrations
18│ │ ├── openai/ # OpenAI models and embeddings
· · ·
19│ │ ├── anthropic/ # Anthropic (Claude) integration
20│ │ ├── ollama/ # Local model support
21▶│ │ └── ... (other integrations maintained by the LangChain team)
22│ ├── text-splitters/ # Document chunking utilities
23│ ├── standard-tests/ # Shared test suite for integrations
· · ·
30- **Core layer** (`langchain-core`): Base abstractions, interfaces, and protocols. Users should not need to know about this layer directly.
31- **Implementation layer** (`langchain`): Concrete implementations and high-level public utilities
32▶- **Integration layer** (`partners/`): Third-party service integrations. Note that this monorepo is not exhaustive of all LangChain integrations; some are maintained in separate repos, such as `langchain-ai/langchain-google` and `langchain-ai/langchain-aws`. Usually these repos are cloned at the same level as this monorepo, so if needed, you can refer to their code directly by navigating to `../langchain-google/` from this monorepo.
33- **Testing layer** (`standard-tests/`): Standardized integration tests for partner integrations
34
· · ·
85#### Key config files
86
87▶- pyproject.toml: Main workspace configuration with dependency groups
88- uv.lock: Locked dependencies for reproducible builds
89- Makefile: Development tasks
· · ·
91#### PR and commit titles
92
93▶Follow Conventional Commits. See `.github/workflows/pr_lint.yml` for allowed types and scopes. All titles must include a scope with no exceptions — even for the main `langchain` package.
94
95- Start the text after `type(scope):` with a lowercase letter, unless the first word is a proper noun (e.g. `Azure`, `GitHub`, `OpenAI`) or a named entity (class, function, method, parameter, or variable name).
+ 13 more matches in this file
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)
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
56
57 get_text_length: Callable[[str], int] = _get_length_based
58▶ """Function to measure prompt length. Defaults to word count."""
59
60 max_length: int = 2048
· · ·
104 """
105 inputs = " ".join(input_variables.values())
106▶ remaining_length = self.max_length - self.get_text_length(inputs)
107 i = 0
108 examples = []
· · ·
109▶ while remaining_length > 0 and i < len(self.examples):
110 new_length = remaining_length - self.example_text_lengths[i]
111 if new_length < 0:
· · ·
110▶ new_length = remaining_length - self.example_text_lengths[i]
111 if new_length < 0:
112 break
· · ·
113 examples.append(self.examples[i])
114▶ remaining_length = new_length
115 i += 1
116 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
· · ·
87 _V2StreamingCallbackHandler,
88)
89▶from langchain_core.utils.function_calling import (
90 convert_to_json_schema,
91 convert_to_openai_tool,
· · ·
274 Methods that actually call the underlying model.
275
276▶ This table provides a brief overview of the main imperative methods. Please see the base `Runnable` reference for full documentation.
277
278 | Method | Input | Output | Description |
· · ·
291 Methods for creating another `Runnable` using the chat model.
292
293▶ This table provides a brief overview of the main declarative methods. Please see the reference for each method for full documentation.
294
295 | Method | Description |
· · ·
334 - If `False` (Default), will always use streaming case if available.
335
336▶ The main reason for this flag is that code might be written using `stream` and
337 a user may want to swap out a given model for another model whose implementation
338 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,
+ 197 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,
· · ·
126def _get_filtered_args(
127 inferred_model: type[BaseModel],
128▶ func: Callable,
129 *,
130 filter_args: Sequence[str],
· · ·
131 include_injected: bool = True,
132) -> dict:
133▶ """Get filtered arguments from a function's signature.
134
135 Args:
· · ·
136▶ inferred_model: The Pydantic model inferred from the function.
137 func: The function to extract arguments from.
138 filter_args: Arguments to exclude from the result.
+ 57 more matches in this file