1,884 matches across 25 files for func main lang:Python
snippet_mode: auto · sorted by relevance
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:
+ 62 more matches in this file
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
30 ChatMessage,
31 ChatMessageChunk,
32▶ FunctionMessageChunk,
33 HumanMessage,
34 HumanMessageChunk,
· · ·
46from langchain_core.runnables import Runnable, RunnableMap, RunnablePassthrough
47from langchain_core.utils import get_pydantic_field_names, secret_from_env
48▶from langchain_core.utils.function_calling import convert_to_json_schema
49from langchain_core.utils.pydantic import is_basemodel_subclass
50from perplexity import AsyncPerplexity, Perplexity
· · ·
158
159def _is_builtin_tool(tool: dict) -> bool:
160▶ """Return True if `tool` is a Responses-API built-in (non-`function`) tool.
161
162 Perplexity's Agent API ships built-in tools (e.g. `web_search`,
· · ·
163 `code_interpreter`) that are identified by a `type` value other than
164▶ `"function"`. Chat Completions only accepts function tools, so any tool
165 failing this check forces the Responses route.
166 """
· · ·
167▶ return "type" in tool and tool["type"] != "function"
168
169
+ 23 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
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
10import warnings
11from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
12▶from functools import cached_property
13from operator import itemgetter
14from typing import Any, Final, Literal, cast
· · ·
50from langchain_core.tools import BaseTool
51from langchain_core.utils import from_env, get_pydantic_field_names, secret_from_env
52▶from langchain_core.utils.function_calling import (
53 convert_to_json_schema,
54 convert_to_openai_tool,
· · ·
102
103 Custom tools use `name` and `input_schema` fields to define the tool's
104▶ interface. These are converted from LangChain tool formats (functions, Pydantic
105 models, `BaseTool` objects) via `convert_to_anthropic_tool`.
106 """
· · ·
249 `^[a-zA-Z0-9_-]+$`. IDs minted by other providers can violate this when a
250 thread is replayed across providers (e.g. Fireworks/Kimi emits
251▶ `functions.write_todos:0`, whose `.` and `:` are invalid). Valid IDs are
252 returned unchanged; invalid ones are hashed deterministically so that a
253 rewritten `tool_use.id` and its paired `tool_use_id` resolve to the same
· · ·
519 msg = "Dict content block must have a type key"
520 raise ValueError(msg)
521▶ if block["type"] in ("reasoning", "function_call") and (
522 not isinstance(message, AIMessage)
523 or message.response_metadata.get("model_provider")
+ 17 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
5from collections.abc import Awaitable, Callable, Sequence
6from dataclasses import dataclass, field, replace
7▶from inspect import iscoroutinefunction
8from typing import (
9 TYPE_CHECKING,
· · ·
385
386 Subclass this and implement any of the defined methods to customize agent behavior
387▶ between steps in the main agent loop.
388
389 Type Parameters:
· · ·
579 "To resolve this, either: "
580 "(1) subclass AgentMiddleware and implement the synchronous wrap_model_call method, "
581▶ "(2) use the @wrap_model_call decorator on a standalone sync function, or "
582 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
583 )
· · ·
631 "To resolve this, either: "
632 "(1) subclass AgentMiddleware and implement the asynchronous awrap_model_call method, "
633▶ "(2) use the @wrap_model_call decorator on a standalone async function, or "
634 "(3) invoke your agent synchronously using `stream()` or `invoke()`."
635 )
· · ·
737 "To resolve this, either: "
738 "(1) subclass AgentMiddleware and implement the synchronous wrap_tool_call method, "
739▶ "(2) use the @wrap_tool_call decorator on a standalone sync function, or "
740 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
741 )
+ 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
3from __future__ import annotations
4
5▶from functools import partial
6from typing import TYPE_CHECKING, Any, ClassVar, Literal
7
· · ·
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
+ 2 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
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
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
49 ChatMessage,
50 ChatMessageChunk,
51▶ FunctionMessage,
52 FunctionMessageChunk,
53 HumanMessage,
· · ·
52▶ FunctionMessageChunk,
53 HumanMessage,
54 HumanMessageChunk,
· · ·
84 get_pydantic_field_names,
85)
86▶from langchain_core.utils.function_calling import (
87 convert_to_json_schema,
88 convert_to_openai_tool,
· · ·
135 additional_kwargs["reasoning_content"] = reasoning_content
136
137▶ if function_call := _dict.get("function_call"):
138 additional_kwargs["function_call"] = dict(function_call)
139
· · ·
138▶ additional_kwargs["function_call"] = dict(function_call)
139
140 tool_calls = []
+ 48 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
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
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:
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":
· · ·
544 )
545 elif callable(api_key):
546▶ if inspect.iscoroutinefunction(api_key):
547 async_api_key_value = api_key
548 sync_api_key_value = None