1,951 matches across 25 files for func main lang:Python lang:Python lang:Python 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
· · ·
88 _V2StreamingCallbackHandler,
89)
90▶from 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
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
30 ChatMessage,
31 ChatMessageChunk,
32▶ FunctionMessageChunk,
33 HumanMessage,
34 HumanMessageChunk,
· · ·
48from langchain_core.tools import BaseTool
49from langchain_core.utils import get_pydantic_field_names, secret_from_env
50▶from langchain_core.utils.function_calling import (
51 convert_to_json_schema,
52 convert_to_openai_tool,
· · ·
163
164def _is_builtin_tool(tool: dict) -> bool:
165▶ """Return True if `tool` is a Responses-API built-in (non-`function`) tool.
166
167 Perplexity's Agent API ships built-in tools (e.g. `web_search`,
· · ·
168 `code_interpreter`) that are identified by a `type` value other than
169▶ `"function"`. Chat Completions only accepts function tools, so any tool
170 failing this check forces the Responses route.
171 """
· · ·
172▶ return "type" in tool and tool["type"] != "function"
173
174
+ 46 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
4import warnings
5from collections.abc import Callable, Iterable, Mapping
6▶from functools import partial
7from typing import Any, Literal, TypedDict, cast
8
· · ·
64## NEXT STEPS
65
66▶What specific tasks remain to be completed to achieve the session intent? What should you do next?
67
68</instructions>
· · ·
210
211 This middleware monitors message token counts and automatically summarizes older
212▶ messages when a threshold is reached, preserving recent messages and maintaining
213 context continuity by ensuring AI/Tool message pairs remain together.
214 """
· · ·
213▶ context continuity by ensuring AI/Tool message pairs remain together.
214 """
215
· · ·
285 ("fraction", 0.3)
286 ```
287▶ token_counter: Function to count tokens in messages.
288 summary_prompt: Prompt template for generating summaries.
289 trim_tokens_to_summarize: Maximum tokens to keep when preparing messages for
6from collections.abc import Awaitable, Callable, Sequence
7from dataclasses import dataclass, field, replace
8▶from inspect import iscoroutinefunction
9from typing import (
10 TYPE_CHECKING,
· · ·
381
382 Subclass this and implement any of the defined methods to customize agent behavior
383▶ between steps in the main agent loop.
384
385 Type Parameters:
· · ·
575 "To resolve this, either: "
576 "(1) subclass AgentMiddleware and implement the synchronous wrap_model_call method, "
577▶ "(2) use the @wrap_model_call decorator on a standalone sync function, or "
578 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
579 )
· · ·
627 "To resolve this, either: "
628 "(1) subclass AgentMiddleware and implement the asynchronous awrap_model_call method, "
629▶ "(2) use the @wrap_model_call decorator on a standalone async function, or "
630 "(3) invoke your agent synchronously using `stream()` or `invoke()`."
631 )
· · ·
733 "To resolve this, either: "
734 "(1) subclass AgentMiddleware and implement the synchronous wrap_tool_call method, "
735▶ "(2) use the @wrap_tool_call decorator on a standalone sync function, or "
736 "(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
737 )
+ 165 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[..., Any])
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,
+ 199 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,
· · ·
123
124
125▶def _parse_python_function_docstring(
126 function: Callable[..., Any],
127 annotations: dict[str, Any],
· · ·
126▶ function: Callable[..., Any],
127 annotations: dict[str, Any],
128 *,
· · ·
129 error_on_invalid_docstring: bool = False,
130) -> tuple[str, dict[str, str]]:
131▶ """Parse function and argument descriptions from a docstring.
132
133 Assumes the function docstring follows Google Python style guide.
+ 52 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