1,864 matches across 25 files for func main
snippet_mode: auto · sorted by relevance
29 ChatMessage,
30 ChatMessageChunk,
31▶ FunctionMessageChunk,
32 HumanMessage,
33 HumanMessageChunk,
· · ·
44from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
45from langchain_core.utils import get_pydantic_field_names, secret_from_env
46▶from langchain_core.utils.function_calling import convert_to_json_schema
47from langchain_core.utils.pydantic import is_basemodel_subclass
48from perplexity import AsyncPerplexity, Perplexity
· · ·
222 """Language preference:"""
223
224▶ search_domain_filter: list[str] | None = None
225 """Search domain filter: list of domains to filter search results (max 20)."""
226
· · ·
225▶ """Search domain filter: list of domains to filter search results (max 20)."""
226
227 return_images: bool = False
· · ·
330 if self.language_preference:
331 params["language_preference"] = self.language_preference
332▶ if self.search_domain_filter:
333 params["search_domain_filter"] = self.search_domain_filter
334 if self.return_images:
+ 9 more matches in this file
79from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
80from langchain_core.tools import BaseTool
81▶from langchain_core.utils.function_calling import (
82 convert_to_json_schema,
83 convert_to_openai_tool,
· · ·
152 return json_string
153 msg = (
154▶ f"Function {raw_tool_call['function']['name']} arguments:\n\n"
155 f"{raw_tool_call['function']['arguments']}"
156 "\n\nare not valid JSON or a Python literal. "
· · ·
155▶ f"{raw_tool_call['function']['arguments']}"
156 "\n\nare not valid JSON or a Python literal. "
157 f"Received error: {e}"
· · ·
162 return json_string
163 msg = (
164▶ f"Function {raw_tool_call['function']['name']} arguments:\n\n"
165 f"{raw_tool_call['function']['arguments']}\n\nare not a string or a "
166 f"dictionary. Received TypeError {e}"
· · ·
165▶ f"{raw_tool_call['function']['arguments']}\n\nare not a string or a "
166 f"dictionary. Received TypeError {e}"
167 )
+ 27 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:
+ 60 more matches in this file
9import warnings
10from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
11▶from functools import cached_property
12from operator import itemgetter
13from typing import Any, Final, Literal, cast
· · ·
49from langchain_core.tools import BaseTool
50from langchain_core.utils import from_env, get_pydantic_field_names, secret_from_env
51▶from langchain_core.utils.function_calling import (
52 convert_to_json_schema,
53 convert_to_openai_tool,
· · ·
101
102 Custom tools use `name` and `input_schema` fields to define the tool's
103▶ interface. These are converted from LangChain tool formats (functions, Pydantic
104 models, `BaseTool` objects) via `convert_to_anthropic_tool`.
105 """
· · ·
473 msg = "Dict content block must have a type key"
474 raise ValueError(msg)
475▶ if block["type"] in ("reasoning", "function_call") and (
476 not isinstance(message, AIMessage)
477 or message.response_metadata.get("model_provider")
· · ·
1462
1463 When `True`, only text content is preserved; when `False`, structured
1464▶ content like tool calls and citations are maintained.
1465 block_start_event: Previous content block start event, used for tracking
1466 tool use blocks and maintaining context across related events.
+ 16 more matches in this file
130 separator_ = "" if self._keep_separator else separator
131 for s in splits:
132▶ if self._length_function(s) < self._chunk_size:
133 good_splits.append(s)
134 else:
· · ·
193 # Split along class definitions
194 "\nclass ",
195▶ # Split along function definitions
196 "\nvoid ",
197 "\nint ",
· · ·
212 if language == Language.GO:
213 return [
214▶ # Split along function definitions
215 "\nfunc ",
216 "\nvar ",
· · ·
215▶ "\nfunc ",
216 "\nvar ",
217 "\nconst ",
· · ·
276 if language == Language.JS:
277 return [
278▶ # Split along function definitions
279 "\nfunction ",
280 "\nconst ",
+ 21 more matches in this file
30 Sequence,
31)
32▶from functools import partial
33from io import BytesIO
34from json import JSONDecodeError
· · ·
68 ChatMessage,
69 ChatMessageChunk,
70▶ FunctionMessage,
71 FunctionMessageChunk,
72 HumanMessage,
· · ·
71▶ FunctionMessageChunk,
72 HumanMessage,
73 HumanMessageChunk,
· · ·
109from langchain_core.tools.base import _stringify
110from langchain_core.utils import get_pydantic_field_names
111▶from langchain_core.utils.function_calling import (
112 convert_to_openai_function,
113 convert_to_openai_tool,
· · ·
112▶ convert_to_openai_function,
113 convert_to_openai_tool,
114)
+ 106 more matches in this file
9from abc import ABC, abstractmethod
10from collections.abc import AsyncIterator, Callable, Iterator, Sequence
11▶from functools import cached_property
12from operator import itemgetter
13from typing import TYPE_CHECKING, Any, Literal, cast, overload
· · ·
86 _V2StreamingCallbackHandler,
87)
88▶from langchain_core.utils.function_calling import (
89 convert_to_json_schema,
90 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.
+ 11 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
· · ·
121 package: str = "",
122) -> Callable[[T], T]:
123▶ """Decorator to mark a function, a class, or a property as deprecated.
124
125 When deprecating a classmethod, a staticmethod, or a property, the `@deprecated`
· · ·
133
134 Parameters are the same as for `warn_deprecated`, except that *obj_type* defaults to
135▶ 'class' if decorating a class, 'attribute' if decorating a property, and 'function'
136 otherwise.
137
+ 22 more matches in this file
5from collections.abc import Awaitable, Callable, Sequence
6from dataclasses import dataclass, field, replace
7▶from inspect import iscoroutinefunction
8from typing import (
9 TYPE_CHECKING,
· · ·
382
383 Subclass this and implement any of the defined methods to customize agent behavior
384▶ between steps in the main agent loop.
385
386 Type Parameters:
· · ·
566 "To resolve this, either: "
567 "(1) subclass AgentMiddleware and implement the synchronous wrap_model_call method, "
568▶ "(2) use the @wrap_model_call decorator on a standalone sync function, or "
569 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
570 )
· · ·
618 "To resolve this, either: "
619 "(1) subclass AgentMiddleware and implement the asynchronous awrap_model_call method, "
620▶ "(2) use the @wrap_model_call decorator on a standalone async function, or "
621 "(3) invoke your agent synchronously using `stream()` or `invoke()`."
622 )
· · ·
724 "To resolve this, either: "
725 "(1) subclass AgentMiddleware and implement the synchronous wrap_tool_call method, "
726▶ "(2) use the @wrap_tool_call decorator on a standalone sync function, or "
727 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
728 )
+ 157 more matches in this file
75 alternative="langchain.chat_models.init_chat_model",
76 addendum=(
77▶ "Maintained in `langchain`; `langchain-classic` retains this entry point "
78 "for import-compatibility only."
79 ),
· · ·
91 !!! warning "Use `langchain.chat_models.init_chat_model` instead"
92
93▶ This function lives in `langchain-classic` and is no longer actively
94 maintained. New features and fixes land in the `langchain` package.
95
· · ·
94▶ maintained. New features and fixes land in the `langchain` package.
95
96 Update your imports:
· · ·
104 ```
105
106▶ **Two main use cases:**
107
108 1. **Fixed model** – specify the model upfront and get a
· · ·
746 config = RunnableConfig(**(config or {}), **cast("RunnableConfig", kwargs))
747 model_params = self._model_params(config)
748▶ remaining_config = {k: v for k, v in config.items() if k != "configurable"}
749 remaining_config["configurable"] = {
750 k: v
+ 3 more matches in this file
29from langchain_core.prompts import ChatPromptTemplate
30from langchain_core.tools import BaseTool, tool
31▶from langchain_core.utils.function_calling import (
32 convert_to_json_schema,
33 tool_example_to_messages,
· · ·
99
100
101▶class _MagicFunctionSchema(BaseModel):
102 input: int = Field(..., gt=-1000, lt=1000)
103
· · ·
104
105▶@tool(args_schema=_MagicFunctionSchema)
106def magic_function(_input: int) -> int:
107 """Apply a magic function to an input."""
· · ·
106▶def magic_function(_input: int) -> int:
107 """Apply a magic function to an input."""
108 return _input + 2
· · ·
107▶ """Apply a magic function to an input."""
108 return _input + 2
109
+ 44 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
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
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
35 ChatMessage,
36 ChatMessageChunk,
37▶ FunctionMessage,
38 FunctionMessageChunk,
39 HumanMessage,
· · ·
38▶ FunctionMessageChunk,
39 HumanMessage,
40 HumanMessageChunk,
· · ·
62from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
63from langchain_core.tools import BaseTool
64▶from langchain_core.utils.function_calling import (
65 convert_to_json_schema,
66 convert_to_openai_tool,
· · ·
101def _lc_tool_call_to_hf_tool_call(tool_call: ToolCall) -> dict:
102 return {
103▶ "type": "function",
104 "id": tool_call["id"],
105 "function": {
· · ·
105▶ "function": {
106 "name": tool_call["name"],
107 "arguments": json.dumps(tool_call["args"], ensure_ascii=False),
+ 40 more matches in this 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.
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
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
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:
1from __future__ import annotations
2
3▶import functools
4import os
5import uuid
· · ·
41 """
42
43▶ @functools.wraps(method)
44 async def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
45 try:
· · ·
67 client = QdrantClient()
68 collection_name = "MyCollection"
69▶ qdrant = Qdrant(client, collection_name, embedding_function)
70 ```
71 """
· · ·
85 vector_name: str | None = VECTOR_NAME,
86 async_client: Any | None = None,
87▶ embedding_function: Callable | None = None, # deprecated
88 ) -> None:
89 """Initialize with necessary components."""
· · ·
102 raise ValueError(msg)
103
104▶ if embeddings is None and embedding_function is None:
105 msg = "`embeddings` value can't be None. Pass `embeddings` instance."
106 raise ValueError(msg)
+ 64 more matches in this file
104
105 # Define headers for splitting on h1 and h2 tags.
106▶ headers_to_split_on = [("h1", "Main Topic"), ("h2", "Sub Topic")]
107
108 splitter = HTMLHeaderTextSplitter(
· · ·
127
128 # 'documents' now contains Document objects reflecting the hierarchy:
129▶ # - Document with metadata={"Main Topic": "Introduction"} and
130 # content="Introduction"
131 # - Document with metadata={"Main Topic": "Introduction"} and
· · ·
131▶ # - Document with metadata={"Main Topic": "Introduction"} and
132 # content="Welcome to the introduction section."
133 # - Document with metadata={"Main Topic": "Introduction",
· · ·
133▶ # - Document with metadata={"Main Topic": "Introduction",
134 # "Sub Topic": "Background"} and content="Background"
135 # - Document with metadata={"Main Topic": "Introduction",
· · ·
135▶ # - Document with metadata={"Main Topic": "Introduction",
136 # "Sub Topic": "Background"} and content="Some background details here."
137 # - Document with metadata={"Main Topic": "Conclusion"} and
+ 7 more matches in this file
20import urllib.request
21from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
22▶from functools import lru_cache
23from typing import Any, TypeVar, cast
24
· · ·
168
169 Always returns a tuple (never None) so callers and `@lru_cache` keys
170▶ remain uniform: `()` is the single shape for "no options".
171
172 Target behavior on Linux/gVisor with the full option set: silent peers
· · ·
175 caps at 120s). On platforms that reject some options,
176 `_filter_supported` drops them and the bound degrades to whatever the
177▶ remaining options provide.
178 """
179 if os.environ.get("LANGCHAIN_OPENAI_TCP_KEEPALIVE", "1") == "0":
· · ·
546 )
547 elif callable(api_key):
548▶ if inspect.iscoroutinefunction(api_key):
549 async_api_key_value = api_key
550 sync_api_key_value = None
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:
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