2,065 matches across 25 files for func main
snippet_mode: grep · sorted by relevance
.github/ISSUE_TEMPLATE/feature-request.yml YAML 3 matches view file →
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...
.github/scripts/get_min_versions.py PYTHON 2 matches view file →
187
188
189if __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
.github/tools/git-restore-mtime #! 11 matches · showing 5 view file →
66# `--accurate` mode for `--cc`?
67
68if __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
.github/workflows/pr_lint_trailer.yml YAML 4 matches view 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 {
.github/workflows/require_issue_link.yml YAML 26 matches · showing 5 view file →
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".
· · ·
60
61 // ── Helper: ensure a label exists, then add it to the PR ────────
62 async function ensureAndAddLabel(labelName, color) {
63 try {
64 await github.rest.issues.getLabel({ owner, repo, name: labelName });
· · ·
84 // to be an org member, which GITHUB_TOKEN (an app installation
85 // token) never is — so it always returns 403.
86 async function senderIsOrgMember() {
87 const sender = context.payload.sender?.login;
88 if (!sender) {
· · ·
94 });
95 const perm = data.permission;
96 if (['admin', 'maintain', 'write'].includes(perm)) {
97 console.log(`${sender} has ${perm} permission — treating as maintainer`);
98 return { isMember: true, login: sender };
+ 21 more matches in this file
AGENTS.md MARKDOWN 18 matches · showing 5 view 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
93Follow 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
CLAUDE.md MARKDOWN 18 matches · showing 5 view 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
93Follow 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
libs/core/langchain_core/_api/beta_decorator.py PYTHON 21 matches · showing 5 view 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)
· · ·
3This 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
13import 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
libs/core/langchain_core/_api/deprecation.py PYTHON 27 matches · showing 5 view 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)
· · ·
3This 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
13import 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
libs/core/langchain_core/_security/_policy.py PYTHON 3 matches view file →
80 {
81 "localhost",
82 "localhost.localdomain",
83 "host.docker.internal",
84 }
· · ·
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
libs/core/langchain_core/callbacks/manager.py PYTHON 18 matches · showing 5 view file →
5import asyncio
6import atexit
7import functools
8import inspect
9import logging
· · ·
216
217
218Func = TypeVar("Func", bound=Callable[..., Any])
219
220
· · ·
221def shielded(func: Func) -> Func:
222 """Makes so an awaitable method is always shielded from cancellation.
223
· · ·
224 Args:
225 func: The function to shield.
226
227 Returns:
· · ·
228 The shielded function
229
230 """
+ 13 more matches in this file
libs/core/langchain_core/example_selectors/length_based.py PYTHON 5 matches view 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
libs/core/langchain_core/indexing/base.py PYTHON 4 matches view file →
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.
libs/core/langchain_core/language_models/_compat_bridge.py PYTHON 3 matches view file →
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:
libs/core/langchain_core/language_models/_utils.py PYTHON 8 matches · showing 5 view file →
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
libs/core/langchain_core/language_models/chat_model_stream.py PYTHON 4 matches view 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
libs/core/langchain_core/language_models/chat_models.py PYTHON 17 matches · showing 5 view file →
10from abc import ABC, abstractmethod
11from collections.abc import AsyncIterator, Callable, Iterator, Sequence
12from functools import cached_property
13from operator import itemgetter
14from typing import TYPE_CHECKING, Any, Literal, cast, overload
· · ·
88 _V2StreamingCallbackHandler,
89)
90from 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
libs/core/langchain_core/load/mapping.py PYTHON 25 matches · showing 5 view file →
5where that class is actually located.
6
7This 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
libs/core/langchain_core/messages/base.py PYTHON 2 matches view 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
libs/core/langchain_core/messages/content.py PYTHON 12 matches · showing 5 view file →
111```
112
113Factory 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
libs/core/langchain_core/messages/utils.py PYTHON 66 matches · showing 5 view file →
1"""Module contains utility functions for working with messages.
2
3Some examples of what you can do with these functions include:
· · ·
3Some 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
18from functools import partial, wraps
19from typing import (
20 TYPE_CHECKING,
· · ·
43 is_data_content_block,
44)
45from langchain_core.messages.function import FunctionMessage, FunctionMessageChunk
46from langchain_core.messages.human import HumanMessage, HumanMessageChunk
47from langchain_core.messages.modifier import RemoveMessage
· · ·
89 | Annotated[ChatMessage, Tag(tag="chat")]
90 | Annotated[SystemMessage, Tag(tag="system")]
91 | Annotated[FunctionMessage, Tag(tag="function")]
92 | Annotated[ToolMessage, Tag(tag="tool")]
93 | Annotated[AIMessageChunk, Tag(tag="AIMessageChunk")]
+ 61 more matches in this file
libs/core/langchain_core/runnables/base.py PYTHON 204 matches · showing 5 view file →
6import collections
7import contextlib
8import functools
9import inspect
10import threading
· · ·
21)
22from concurrent.futures import FIRST_COMPLETED, wait
23from functools import wraps
24from itertools import tee
25from operator import itemgetter
· · ·
52from langchain_core.runnables.config import (
53 RunnableConfig,
54 acall_func_with_variable_args,
55 call_func_with_variable_args,
56 ensure_config,
· · ·
55 call_func_with_variable_args,
56 ensure_config,
57 get_async_callback_manager_for_config,
· · ·
76 gated_coro,
77 gather_with_concurrency,
78 get_function_first_arg_dict_keys,
79 get_function_nonlocals,
80 get_lambda_source,
+ 199 more matches in this file
libs/core/langchain_core/runnables/graph_mermaid.py PYTHON 2 matches view 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:
libs/core/langchain_core/runnables/retry.py PYTHON 16 matches · showing 5 view file →
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
libs/core/langchain_core/tools/base.py PYTHON 57 matches · showing 5 view file →
3from __future__ import annotations
4
5import functools
6import inspect
7import json
· · ·
56from langchain_core.runnables.config import set_config_context
57from langchain_core.runnables.utils import coro_with_context
58from langchain_core.utils.function_calling import (
59 _parse_google_docstring,
60 _py_38_safe_origin,
· · ·
125
126
127def _parse_python_function_docstring(
128 function: Callable[..., Any],
129 annotations: dict[str, Any],
· · ·
128 function: Callable[..., Any],
129 annotations: dict[str, Any],
130 *,
· · ·
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.
+ 52 more matches in this file
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.