7,044 matches across 25 files for error
snippet_mode: auto · sorted by relevance
libs/partners/openai/langchain_openai/chat_models/base.py PYTHON 97 matches · showing 5 view file →
32from functools import partial
33from io import BytesIO
34from json import JSONDecodeError
35from math import ceil
36from operator import itemgetter
· · ·
52 CallbackManagerForLLMRun,
53)
54from langchain_core.exceptions import ContextOverflowError
55from langchain_core.language_models import (
56 LanguageModelInput,
· · ·
124 Field,
125 SecretStr,
126 ValidationError,
127 field_validator,
128 model_validator,
· · ·
463 else:
464 msg = f"Got unknown type {message}"
465 raise TypeError(msg)
466 return message_dict
467
· · ·
492 for rtc in raw_tool_calls
493 ]
494 except KeyError:
495 pass
496
+ 92 more matches in this file
libs/langchain_v1/langchain/agents/factory.py PYTHON 45 matches · showing 5 view file →
49from langchain.agents.structured_output import (
50 AutoStrategy,
51 MultipleStructuredOutputsError,
52 OutputToolBinding,
53 ProviderStrategy,
· · ·
54 ProviderStrategyBinding,
55 ResponseFormat,
56 StructuredOutputError,
57 StructuredOutputValidationError,
58 ToolStrategy,
· · ·
57 StructuredOutputValidationError,
58 ToolStrategy,
59)
· · ·
111
112
113STRUCTURED_OUTPUT_ERROR_TEMPLATE = "Error: {error}\n Please fix your mistakes."
114
115DYNAMIC_TOOL_ERROR_TEMPLATE = """
· · ·
115DYNAMIC_TOOL_ERROR_TEMPLATE = """
116Middleware added tools that the agent doesn't know how to execute.
117
+ 40 more matches in this file
libs/core/langchain_core/language_models/llms.py PYTHON 46 matches · showing 5 view file →
71@functools.lru_cache
72def _log_error_once(msg: str) -> None:
73 """Log an error once."""
74 logger.error(msg)
75
· · ·
74 logger.error(msg)
75
76
· · ·
77def create_base_retry_decorator(
78 error_types: list[type[BaseException]],
79 max_retries: int = 1,
80 run_manager: AsyncCallbackManagerForLLMRun | CallbackManagerForLLMRun | None = None,
· · ·
81) -> Callable[[Any], Any]:
82 """Create a retry decorator for a given LLM and provided a list of error types.
83
84 Args:
· · ·
85 error_types: List of error types to retry on.
86 max_retries: Number of retries.
87 run_manager: Callback manager for the run.
+ 41 more matches in this file
libs/core/langchain_core/messages/block_translators/openai.py PYTHON 32 matches · showing 5 view file →
27
28 Raises:
29 ValueError: If required keys are missing.
30 ValueError: If source type is unsupported.
31
· · ·
30 ValueError: If source type is unsupported.
31
32 Returns:
· · ·
42 if "base64" in block or block.get("source_type") == "base64":
43 if "mime_type" not in block:
44 error_message = "mime_type key is required for base64 data."
45 raise ValueError(error_message)
46 mime_type = block["mime_type"]
· · ·
45 raise ValueError(error_message)
46 mime_type = block["mime_type"]
47 base64_data = block["data"] if "data" in block else block["base64"]
· · ·
52 },
53 }
54 error_message = "Unsupported source type. Only 'url' and 'base64' are supported."
55 raise ValueError(error_message)
56
+ 27 more matches in this file
libs/core/langchain_core/callbacks/manager.py PYTHON 84 matches · showing 5 view file →
126 except Exception as e:
127 if not group_cm.ended:
128 run_manager.on_chain_error(e)
129 raise
130 else:
· · ·
209 except Exception as e:
210 if not group_cm.ended:
211 await run_manager.on_chain_error(e)
212 raise
213 else:
· · ·
245 # `call-arg` used to not fail 3.9 or 3.10 tests
246 return await asyncio.shield(task)
247 except TypeError:
248 # Python < 3.11 fallback - create task normally then shield
249 # This won't preserve context perfectly but is better than nothing
· · ·
262 """Wrap an async `on_chat_model_start` coroutine with fallback.
263
264 Catches `NotImplementedError` and triggers the `on_llm_start` fallback.
265 This covers async handlers invoked from a **sync** `handle_event` call,
266 where the coroutine is collected into `coros` and executed later by
· · ·
267 `_run_coros`. Without this wrapper the `NotImplementedError` would be
268 caught generically by `_run_coros` and the trace would be lost.
269 """
+ 79 more matches in this file
libs/core/langchain_core/language_models/chat_model_stream.py PYTHON 52 matches · showing 5 view file →
170 consumer protocol (sync iteration or async iteration + await).
171
172 `done` and `error` are safe read-only views of the terminal state
173 for iterators and other siblings that need to observe lifecycle
174 without reaching into the underlying fields.
· · ·
175 """
176
177 __slots__ = ("_deltas", "_done", "_error", "_final_set", "_final_value")
178
179 def __init__(self) -> None:
· · ·
183 self._final_set: bool = False
184 self._done: bool = False
185 self._error: BaseException | None = None
186
187 @property
· · ·
188 def done(self) -> bool:
189 """Whether the projection has finished (successfully or via error)."""
190 return self._done
191
· · ·
192 @property
193 def error(self) -> BaseException | None:
194 """The terminal error, if any."""
195 return self._error
196
+ 47 more matches in this file
libs/langchain/langchain_classic/chains/loading.py PYTHON 47 matches · showing 5 view file →
46try:
47 from langchain_community.llms.loading import load_llm, load_llm_from_config
48except ImportError:
49
50 def load_llm(*_: Any, **__: Any) -> None:
· · ·
51 """Import error for load_llm."""
52 msg = (
53 "To use this load_llm functionality you must install the "
· · ·
55 "You can install it with `pip install langchain_community`"
56 )
57 raise ImportError(msg)
58
59 def load_llm_from_config(*_: Any, **__: Any) -> None:
· · ·
60 """Import error for load_llm_from_config."""
61 msg = (
62 "To use this load_llm_from_config functionality you must install the "
· · ·
64 "You can install it with `pip install langchain_community`"
65 )
66 raise ImportError(msg)
67
68
+ 42 more matches in this file
libs/core/langchain_core/indexing/api.py PYTHON 43 matches · showing 5 view file →
93 if size <= 0:
94 msg = f"Batch size must be a positive integer, got {size}."
95 raise ValueError(msg)
96 it = iter(iterable)
97 while True:
· · ·
106 if size <= 0:
107 msg = f"Batch size must be a positive integer, got {size}."
108 raise ValueError(msg)
109 batch: list[T] = []
110 async for element in iterable:
· · ·
134 f"Got {source_id_key} of type {type(source_id_key)}."
135 )
136 raise ValueError(msg)
137
138
· · ·
170 return hashlib.sha512(text.encode("utf-8")).hexdigest()
171 msg = f"Unsupported hashing algorithm: {algorithm}" # type: ignore[unreachable]
172 raise ValueError(msg)
173
174
· · ·
199
200 Raises:
201 ValueError: If the metadata cannot be serialized using json.
202
203 Returns:
+ 38 more matches in this file
libs/partners/fireworks/langchain_fireworks/chat_models.py PYTHON 64 matches · showing 5 view file →
18import httpx
19from fireworks import (
20 APIConnectionError,
21 AsyncFireworks,
22 BadRequestError,
· · ·
22 BadRequestError,
23 Fireworks,
24 FireworksError,
· · ·
24 FireworksError,
25 InternalServerError,
26 RateLimitError,
· · ·
25 InternalServerError,
26 RateLimitError,
27)
· · ·
26 RateLimitError,
27)
28from langchain_core.callbacks import (
+ 59 more matches in this file
libs/core/langchain_core/messages/utils.py PYTHON 54 matches · showing 5 view file →
33from pydantic import Discriminator, Field, Tag
34
35from langchain_core.exceptions import ErrorCode, create_message
36from langchain_core.messages.ai import AIMessage, AIMessageChunk
37from langchain_core.messages.base import BaseMessage, BaseMessageChunk
· · ·
60
61 _HAS_LANGCHAIN_TEXT_SPLITTERS = True
62except ImportError:
63 _HAS_LANGCHAIN_TEXT_SPLITTERS = False
64
· · ·
77 f"with a 'type' attribute. Instead got type {type(v)}."
78 )
79 raise TypeError(msg)
80 if not isinstance(result, str):
81 msg = f"Expected 'type' to be a str, got {type(result).__name__}"
· · ·
82 raise TypeError(msg)
83 return result
84
· · ·
267
268 Raises:
269 ValueError: If an unsupported message type is encountered.
270 """
271 if isinstance(m, HumanMessage):
+ 49 more matches in this file
libs/partners/ollama/langchain_ollama/chat_models.py PYTHON 35 matches · showing 5 view file →
132 Args:
133 json_string: JSON string to parse.
134 raw_tool_call: Raw tool call to include in error message.
135 skip: Whether to ignore parsing errors and return the value anyways.
136
· · ·
135 skip: Whether to ignore parsing errors and return the value anyways.
136
137 Returns:
· · ·
143 try:
144 return json.loads(json_string)
145 except json.JSONDecodeError:
146 try:
147 # Use ast.literal_eval to safely parse Python-style dicts
· · ·
148 # (e.g. with single quotes)
149 return ast.literal_eval(json_string)
150 except (SyntaxError, ValueError) as e:
151 # If both fail, and we're not skipping, raise an informative error.
152 if skip:
· · ·
151 # If both fail, and we're not skipping, raise an informative error.
152 if skip:
153 return json_string
+ 30 more matches in this file
libs/core/langchain_core/runnables/utils.py PYTHON 12 matches · showing 5 view file →
94 try:
95 return signature(callable).parameters.get("run_manager") is not None
96 except ValueError:
97 return False
98
· · ·
109 try:
110 return signature(callable).parameters.get("config") is not None
111 except ValueError:
112 return False
113
· · ·
124 try:
125 return signature(callable).parameters.get("context") is not None
126 except ValueError:
127 return False
128
· · ·
381 visitor.visit(tree)
382 return sorted(visitor.keys) if visitor.keys else None
383 except (SyntaxError, TypeError, OSError, SystemError):
384 return None
385
· · ·
396 try:
397 name = func.__name__ if func.__name__ != "<lambda>" else None
398 except AttributeError:
399 name = None
400 try:
+ 7 more matches in this file
libs/core/langchain_core/language_models/chat_models.py PYTHON 61 matches · showing 5 view file →
107
108def _generate_response_from_error(error: BaseException) -> list[ChatGeneration]:
109 if hasattr(error, "response"):
110 response = error.response
111 metadata: dict[str, Any] = {}
· · ·
110 response = error.response
111 metadata: dict[str, Any] = {}
112 if hasattr(response, "json"):
· · ·
125 if hasattr(response, "status_code"):
126 metadata["status_code"] = response.status_code
127 if hasattr(error, "request_id"):
128 metadata["request_id"] = error.request_id
129 generations = [
· · ·
128 metadata["request_id"] = error.request_id
129 generations = [
130 ChatGeneration(message=AIMessage(content="", response_metadata=metadata))
· · ·
211
212 Raises:
213 ValueError: If no generations are found in the stream.
214
215 Returns:
+ 56 more matches in this file
libs/partners/anthropic/langchain_anthropic/middleware/anthropic_tools.py PYTHON 23 matches · showing 5 view file →
130
131 Raises:
132 ValueError: If path contains traversal sequences or violates prefix rules.
133 """
134 # Reject paths with traversal attempts
· · ·
135 if ".." in path or path.startswith("~"):
136 msg = f"Path traversal not allowed: {path}"
137 raise ValueError(msg)
138
139 # Normalize path (resolve ., //, etc.)
· · ·
152 ):
153 msg = f"Path must start with one of {allowed_prefixes}: {path}"
154 raise ValueError(msg)
155
156 return normalized
· · ·
280 )
281 return f"Unknown command: {command}"
282 except (ValueError, FileNotFoundError) as e:
283 return str(e)
284
· · ·
374
375 msg = f"File not found: {path}"
376 raise FileNotFoundError(msg)
377
378 # Format file content with line numbers
+ 18 more matches in this file
libs/partners/mistralai/langchain_mistralai/chat_models.py PYTHON 38 matches · showing 5 view file →
110) -> Callable[[Any], Any]:
111 """Return a tenacity retry decorator, preconfigured to handle exceptions."""
112 errors = [httpx.RequestError, httpx.StreamError]
113 return create_base_retry_decorator(
114 error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
· · ·
114 error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
115 )
116
· · ·
189 if role != "assistant":
190 msg = f"Expected role to be 'assistant', got {role}"
191 raise ValueError(msg)
192 # Mistral returns None for tool invocations. When citations are enabled,
193 # content is a list of typed chunks (text and reference). Normalize
· · ·
221
222def _raise_on_error(response: httpx.Response) -> None:
223 """Raise an error if the response is an error."""
224 if httpx.codes.is_error(response.status_code):
225 error_message = response.read().decode("utf-8")
· · ·
224 if httpx.codes.is_error(response.status_code):
225 error_message = response.read().decode("utf-8")
226 msg = (
+ 33 more matches in this file
libs/core/langchain_core/tools/base.py PYTHON 96 matches · showing 5 view file →
32 PydanticDeprecationWarning,
33 SkipValidation,
34 ValidationError,
35 validate_arguments,
36)
· · ·
37from pydantic.fields import FieldInfo
38from pydantic.v1 import BaseModel as BaseModelV1
39from pydantic.v1 import ValidationError as ValidationErrorV1
40from pydantic.v1 import validate_arguments as validate_arguments_v1
41from typing_extensions import Self, override
· · ·
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.
· · ·
138 function: The function to parse the docstring from.
139 annotations: Type annotations for the function parameters.
140 error_on_invalid_docstring: Whether to raise an error on invalid docstring.
141
142 Returns:
· · ·
147 docstring,
148 list(annotations),
149 error_on_invalid_docstring=error_on_invalid_docstring,
150 )
151
+ 91 more matches in this file
libs/core/langchain_core/output_parsers/openai_tools.py PYTHON 20 matches · showing 5 view file →
4import json
5import logging
6from json import JSONDecodeError
7from typing import Annotated, Any
8
· · ·
9from pydantic import BaseModel, SkipValidation, ValidationError
10from pydantic.v1 import BaseModel as BaseModelV1
11
· · ·
53 try:
54 function_args = parse_partial_json(arguments, strict=strict)
55 except (JSONDecodeError, TypeError): # None args raise TypeError
56 return None
57 # Handle None or empty string arguments for parameter-less tools
· · ·
61 try:
62 function_args = json.loads(arguments, strict=strict)
63 except JSONDecodeError as e:
64 msg = (
65 f"Function {raw_tool_call['function']['name']} arguments:\n\n"
· · ·
66 f"{arguments}\n\nare not valid JSON. "
67 f"Received JSONDecodeError {e}"
68 )
69 raise OutputParserException(msg) from e
+ 15 more matches in this file
libs/partners/anthropic/langchain_anthropic/chat_models.py PYTHON 33 matches · showing 5 view file →
19 CallbackManagerForLLMRun,
20)
21from langchain_core.exceptions import ContextOverflowError, OutputParserException
22from langchain_core.language_models import (
23 LanguageModelInput,
· · ·
235 " or base64 encoded string (data:image/png;base64,'/9j/4AAQSk'...)"
236 )
237 raise ValueError(
238 msg,
239 )
· · ·
256
257 Empty and `None` IDs are passed through unchanged so that a genuinely
258 malformed request surfaces as a clear error from Anthropic rather than
259 being masked by a synthesized ID.
260
· · ·
321 "content": tool_content,
322 "tool_use_id": _normalize_tool_call_id(curr.tool_call_id),
323 "is_error": curr.status == "error",
324 }
325 if cache_ctrl:
· · ·
394 "content blocks."
395 )
396 raise ValueError(
397 msg,
398 )
+ 28 more matches in this file
libs/langchain_v1/langchain/agents/middleware/summarization.py PYTHON 18 matches · showing 5 view file →
365 "with a desired integer value of the model's maximum input tokens."
366 )
367 raise ValueError(msg)
368
369 @override
· · ·
507 at construction. Range and positivity checks are delegated to
508 `_validate_context_size`, keeping a single source of truth for the rules and
509 error messages shared with the tuple form.
510 """
511 if not m:
· · ·
512 msg = "trigger clause must specify at least one of 'tokens', 'messages', 'fraction'"
513 raise ValueError(msg)
514 out: dict[str, float | int] = {}
515 for k, v in m.items():
· · ·
516 if k not in {"tokens", "messages", "fraction"}:
517 msg = f"Unsupported trigger metric: {k!r}"
518 raise ValueError(msg)
519 # `bool` is an `int` subclass; reject it so `{"messages": True}` cannot
520 # silently become a threshold of 1. Raise `ValueError` (not `TypeError`)
· · ·
520 # silently become a threshold of 1. Raise `ValueError` (not `TypeError`)
521 # so every trigger-config error stays one catchable type.
522 if isinstance(v, bool):
+ 13 more matches in this file
libs/langchain/langchain_classic/agents/agent.py PYTHON 64 matches · showing 5 view file →
125
126 Raises:
127 ValueError: If `early_stopping_method` is not supported.
128 """
129 if early_stopping_method == "force":
· · ·
134 )
135 msg = f"Got unsupported early_stopping_method `{early_stopping_method}`"
136 raise ValueError(msg)
137
138 @classmethod
· · ·
155 Agent object.
156 """
157 raise NotImplementedError
158
159 @property
· · ·
160 def _agent_type(self) -> str:
161 """Return Identifier of an agent type."""
162 raise NotImplementedError
163
164 @override
· · ·
172 try:
173 _type = self._agent_type
174 except NotImplementedError:
175 _type = None
176 if isinstance(_type, AgentType):
+ 59 more matches in this file
libs/core/langchain_core/utils/mustache.py PYTHON 22 matches · showing 5 view file →
31
32class ChevronError(SyntaxError):
33 """Custom exception for Chevron errors."""
34
35
· · ·
57
58 # There are no more tags in the template?
59 except ValueError:
60 # Then the rest of the template is a literal
61 return (template, "")
· · ·
128
129 Raises:
130 ChevronError: If the tag is unclosed.
131 ChevronError: If the set delimiter tag is unclosed.
132 """
· · ·
131 ChevronError: If the set delimiter tag is unclosed.
132 """
133 tag_types = {
· · ·
145 try:
146 tag, template = template.split(r_del, 1)
147 except ValueError as e:
148 msg = f"unclosed tag at line {_CURRENT_LINE}"
149 raise ChevronError(msg) from e
+ 17 more matches in this file
libs/langchain/langchain_classic/smith/evaluation/runner_utils.py PYTHON 62 matches · showing 5 view file →
41from langsmith.run_helpers import as_runnable, is_traceable_function
42from langsmith.schemas import Dataset, DataType, Example, Run, TracerSession
43from langsmith.utils import LangSmithError
44from requests import HTTPError
45from typing_extensions import TypedDict
· · ·
44from requests import HTTPError
45from typing_extensions import TypedDict
46
· · ·
106 try:
107 import pandas as pd
108 except ImportError as e:
109 msg = (
110 "Pandas is required to convert the results to a dataframe."
· · ·
111 " to install pandas, run `pip install pandas`."
112 )
113 raise ImportError(msg) from e
114
115 indices = []
· · ·
139 {
140 **{f"feedback.{f.key}": f.score for f in feedback},
141 "error": result.get("Error"),
142 "execution_time": result["execution_time"],
143 "run_id": result.get("run_id"),
+ 57 more matches in this file
libs/partners/huggingface/langchain_huggingface/llms/huggingface_pipeline.py PYTHON 15 matches · showing 5 view file →
14from langchain_huggingface._version import __version__
15from langchain_huggingface.utils.import_utils import (
16 IMPORT_ERROR,
17 is_ipex_available,
18 is_openvino_available,
· · ·
133 from transformers import pipeline as hf_pipeline # type: ignore[import]
134
135 except ImportError as e:
136 msg = (
137 "Could not import transformers python package. "
· · ·
138 "Please install it with `pip install transformers`."
139 )
140 raise ValueError(msg) from e
141
142 _model_kwargs = model_kwargs.copy() if model_kwargs else {}
· · ·
150 "`device_map`."
151 )
152 raise ValueError(msg)
153
154 if "device_map" in _model_kwargs:
· · ·
155 msg = "`device_map` is already specified in `model_kwargs`."
156 raise ValueError(msg)
157
158 _model_kwargs["device_map"] = device_map
+ 10 more matches in this file
libs/core/langchain_core/messages/ai.py PYTHON 8 matches · showing 5 view file →
172
173 invalid_tool_calls: list[InvalidToolCall] = Field(default_factory=list)
174 """If present, tool calls with parsing errors associated with the message."""
175
176 usage_metadata: UsageMetadata | None = None
· · ·
266 try:
267 return translator["translate_content"](self)
268 except NotImplementedError:
269 pass
270
· · ·
394 f" Call ID: {tc.get('id')}",
395 ]
396 if tc.get("error"):
397 lines.append(f" Error: {tc.get('error')}")
398 lines.append(" Args:")
· · ·
397 lines.append(f" Error: {tc.get('error')}")
398 lines.append(" Args:")
399 args = tc.get("args")
· · ·
468 try:
469 return translator["translate_content_chunk"](self)
470 except NotImplementedError:
471 pass
472
+ 3 more matches in this file
libs/langchain_v1/langchain/agents/middleware/shell_tool.py PYTHON 29 matches · showing 5 view file →
34)
35from langchain.agents.middleware._redaction import (
36 PIIDetectionError,
37 PIIMatch,
38 RedactionRule,
· · ·
149
150 Raises:
151 RuntimeError: If the shell session pipes cannot be initialized.
152 """
153 if self._process and self._process.poll() is None:
· · ·
165 ):
166 msg = "Failed to initialize shell session pipes."
167 raise RuntimeError(msg)
168
169 self._stdin = self._process.stdin
· · ·
198 self._stdin.write("exit\n")
199 self._stdin.flush()
200 except (BrokenPipeError, OSError):
201 LOGGER.debug(
202 "Failed to write exit command; terminating shell session.",
· · ·
219 if not self._process or self._process.poll() is not None:
220 msg = "Shell session is not running."
221 raise RuntimeError(msg)
222
223 marker = f"{_DONE_MARKER_PREFIX}{uuid.uuid4().hex}"
+ 24 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.