6,853 matches across 25 files for error
snippet_mode: auto · sorted by relevance
32from functools import partial
33from io import BytesIO
34▶from json import JSONDecodeError
35from math import ceil
36from operator import itemgetter
· · ·
52 CallbackManagerForLLMRun,
53)
54▶from 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,
· · ·
422 else:
423 msg = f"Got unknown type {message}"
424▶ raise TypeError(msg)
425 return message_dict
426
· · ·
451 for rtc in raw_tool_calls
452 ]
453▶ except KeyError:
454 pass
455
+ 97 more matches in this file
47from langchain.agents.structured_output import (
48 AutoStrategy,
49▶ MultipleStructuredOutputsError,
50 OutputToolBinding,
51 ProviderStrategy,
· · ·
52 ProviderStrategyBinding,
53 ResponseFormat,
54▶ StructuredOutputError,
55 StructuredOutputValidationError,
56 ToolStrategy,
· · ·
55▶ StructuredOutputValidationError,
56 ToolStrategy,
57)
· · ·
109
110
111▶STRUCTURED_OUTPUT_ERROR_TEMPLATE = "Error: {error}\n Please fix your mistakes."
112
113DYNAMIC_TOOL_ERROR_TEMPLATE = """
· · ·
113▶DYNAMIC_TOOL_ERROR_TEMPLATE = """
114Middleware added tools that the agent doesn't know how to execute.
115
+ 40 more matches in this file
69
70@functools.lru_cache
71▶def _log_error_once(msg: str) -> None:
72 """Log an error once."""
73 logger.error(msg)
· · ·
72▶ """Log an error once."""
73 logger.error(msg)
74
· · ·
73▶ logger.error(msg)
74
75
· · ·
76def create_base_retry_decorator(
77▶ error_types: list[type[BaseException]],
78 max_retries: int = 1,
79 run_manager: AsyncCallbackManagerForLLMRun | CallbackManagerForLLMRun | None = None,
· · ·
80) -> Callable[[Any], Any]:
81▶ """Create a retry decorator for a given LLM and provided a list of error types.
82
83 Args:
+ 42 more matches in this 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
117 content = "Hello, sandbox!\nLine 2\nLine 3"
118 result = sandbox_backend.write(test_path, content)
119▶ assert result.error is None
120 assert result.path == test_path
121 exec_result = sandbox_backend.execute(f"cat {test_path}")
· · ·
133 result = sandbox_backend.read(test_path)
134 assert isinstance(result, ReadResult)
135▶ assert result.error is None
136 assert result.file_data is not None
137 assert all(
· · ·
151 result = sandbox_backend.read(test_path)
152 assert isinstance(result, ReadResult)
153▶ assert result.error is None
154 assert result.file_data is not None
155 assert result.file_data["encoding"] == "base64"
· · ·
171
172 assert isinstance(result, ReadResult)
173▶ assert result.error is None
174 assert result.file_data is not None
175 assert result.file_data["encoding"] == "base64"
· · ·
176 assert base64.b64decode(result.file_data["content"]) == raw_bytes
177
178▶ def test_read_binary_file_1_mib_returns_error(
179 self, sandbox_backend: SandboxBackendProtocol, sandbox_test_root: str
180 ) -> None:
+ 139 more matches in this file
125 except Exception as e:
126 if not group_cm.ended:
127▶ run_manager.on_chain_error(e)
128 raise
129 else:
· · ·
208 except Exception as e:
209 if not group_cm.ended:
210▶ await run_manager.on_chain_error(e)
211 raise
212 else:
· · ·
244 # `call-arg` used to not fail 3.9 or 3.10 tests
245 return await asyncio.shield(task)
246▶ except TypeError:
247 # Python < 3.11 fallback - create task normally then shield
248 # This won't preserve context perfectly but is better than nothing
· · ·
283 if asyncio.iscoroutine(event):
284 coros.append(event)
285▶ except NotImplementedError as e:
286 if event_name == "on_chat_model_start":
287 if message_strings is None:
· · ·
299 handler_name = handler.__class__.__name__
300 logger.warning(
301▶ "NotImplementedError in %s.%s callback: %s",
302 handler_name,
303 event_name,
+ 83 more matches in this 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
+ 52 more matches in this file
46try:
47 from langchain_community.llms.loading import load_llm, load_llm_from_config
48▶except 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
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}"
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
131 Args:
132 json_string: JSON string to parse.
133▶ raw_tool_call: Raw tool call to include in error message.
134 skip: Whether to ignore parsing errors and return the value anyways.
135
· · ·
134▶ skip: Whether to ignore parsing errors and return the value anyways.
135
136 Returns:
· · ·
142 try:
143 return json.loads(json_string)
144▶ except json.JSONDecodeError:
145 try:
146 # Use ast.literal_eval to safely parse Python-style dicts
· · ·
147 # (e.g. with single quotes)
148 return ast.literal_eval(json_string)
149▶ except (SyntaxError, ValueError) as e:
150 # If both fail, and we're not skipping, raise an informative error.
151 if skip:
· · ·
150▶ # If both fail, and we're not skipping, raise an informative error.
151 if skip:
152 return json_string
+ 30 more matches in this file
33from pydantic import Discriminator, Field, Tag
34
35▶from 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
62▶except 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
90 try:
91 return signature(callable).parameters.get("run_manager") is not None
92▶ except ValueError:
93 return False
94
· · ·
105 try:
106 return signature(callable).parameters.get("config") is not None
107▶ except ValueError:
108 return False
109
· · ·
120 try:
121 return signature(callable).parameters.get("context") is not None
122▶ except ValueError:
123 return False
124
· · ·
378 visitor.visit(tree)
379 return sorted(visitor.keys) if visitor.keys else None
380▶ except (SyntaxError, TypeError, OSError, SystemError):
381 return None
382
· · ·
393 try:
394 name = func.__name__ if func.__name__ != "<lambda>" else None
395▶ except AttributeError:
396 name = None
397 try:
+ 7 more matches in this file
106
107
108▶def _generate_response_from_error(error: BaseException) -> list[ChatGeneration]:
109 if hasattr(error, "response"):
110 response = error.response
· · ·
109▶ if hasattr(error, "response"):
110 response = error.response
111 metadata: dict = {}
· · ·
110▶ response = error.response
111 metadata: dict = {}
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))
+ 57 more matches in this file
105
106 Raises:
107▶ ValueError: If path contains traversal sequences or violates prefix rules.
108 """
109 # Reject paths with traversal attempts
· · ·
110 if ".." in path or path.startswith("~"):
111 msg = f"Path traversal not allowed: {path}"
112▶ raise ValueError(msg)
113
114 # Normalize path (resolve ., //, etc.)
· · ·
127 ):
128 msg = f"Path must start with one of {allowed_prefixes}: {path}"
129▶ raise ValueError(msg)
130
131 return normalized
· · ·
255 )
256 return f"Unknown command: {command}"
257▶ except (ValueError, FileNotFoundError) as e:
258 return str(e)
259
· · ·
349
350 msg = f"File not found: {path}"
351▶ raise FileNotFoundError(msg)
352
353 # Format file content with line numbers
+ 18 more matches in this file
4import json
5import logging
6▶from json import JSONDecodeError
7from typing import Annotated, Any
8
· · ·
9▶from pydantic import SkipValidation, ValidationError
10
11from langchain_core.exceptions import OutputParserException
· · ·
54 try:
55 function_args = parse_partial_json(arguments, strict=strict)
56▶ except (JSONDecodeError, TypeError): # None args raise TypeError
57 return None
58 # Handle None or empty string arguments for parameter-less tools
· · ·
62 try:
63 function_args = json.loads(arguments, strict=strict)
64▶ except JSONDecodeError as e:
65 msg = (
66 f"Function {raw_tool_call['function']['name']} arguments:\n\n"
· · ·
67 f"{arguments}\n\nare not valid JSON. "
68▶ f"Received JSONDecodeError {e}"
69 )
70 raise OutputParserException(msg) from e
+ 15 more matches in this file
109) -> Callable[[Any], Any]:
110 """Return a tenacity retry decorator, preconfigured to handle exceptions."""
111▶ errors = [httpx.RequestError, httpx.StreamError]
112 return create_base_retry_decorator(
113 error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
· · ·
113▶ error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
114 )
115
· · ·
152 if role != "assistant":
153 msg = f"Expected role to be 'assistant', got {role}"
154▶ raise ValueError(msg)
155 # Mistral returns None for tool invocations
156 content = _message.get("content", "") or ""
· · ·
180
181
182▶def _raise_on_error(response: httpx.Response) -> None:
183 """Raise an error if the response is an error."""
184 if httpx.codes.is_error(response.status_code):
· · ·
183▶ """Raise an error if the response is an error."""
184 if httpx.codes.is_error(response.status_code):
185 error_message = response.read().decode("utf-8")
+ 35 more matches in this file
31 PydanticDeprecationWarning,
32 SkipValidation,
33▶ ValidationError,
34 validate_arguments,
35)
· · ·
36from pydantic.fields import FieldInfo
37from pydantic.v1 import BaseModel as BaseModelV1
38▶from pydantic.v1 import ValidationError as ValidationErrorV1
39from pydantic.v1 import validate_arguments as validate_arguments_v1
40from typing_extensions import override
· · ·
87
88
89▶class SchemaAnnotationError(TypeError):
90 """Raised when `args_schema` is missing or has an incorrect type annotation."""
91
· · ·
154
155def _parse_python_function_docstring(
156▶ function: Callable, annotations: dict, *, error_on_invalid_docstring: bool = False
157) -> tuple[str, dict]:
158 """Parse function and argument descriptions from a docstring.
· · ·
163 function: The function to parse the docstring from.
164 annotations: Type annotations for the function parameters.
165▶ error_on_invalid_docstring: Whether to raise an error on invalid docstring.
166
167 Returns:
+ 91 more matches in this file
19 CallbackManagerForLLMRun,
20)
21▶from langchain_core.exceptions import ContextOverflowError, OutputParserException
22from langchain_core.language_models import (
23 LanguageModelInput,
· · ·
234 " or base64 encoded string (data:image/png;base64,'/9j/4AAQSk'...)"
235 )
236▶ raise ValueError(
237 msg,
238 )
· · ·
255
256 Empty and `None` IDs are passed through unchanged so that a genuinely
257▶ malformed request surfaces as a clear error from Anthropic rather than
258 being masked by a synthesized ID.
259
· · ·
320 "content": tool_content,
321 "tool_use_id": _normalize_tool_call_id(curr.tool_call_id),
322▶ "is_error": curr.status == "error",
323 }
324 if cache_ctrl:
· · ·
393 "content blocks."
394 )
395▶ raise ValueError(
396 msg,
397 )
+ 30 more matches in this 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
136
137 Raises:
138▶ ValueError: If both `system_prompt` and `system_message` are provided.
139 """
140 # Handle system_prompt/system_message conversion and validation
· · ·
141 if system_prompt is not None and system_message is not None:
142 msg = "Cannot specify both system_prompt and system_message"
143▶ raise ValueError(msg)
144
145 if system_prompt is not None:
· · ·
255
256 Raises:
257▶ ValueError: If both `system_prompt` and `system_message` are provided.
258 """
259 # Handle system_prompt/system_message conversion
· · ·
260 if "system_prompt" in overrides and "system_message" in overrides:
261 msg = "Cannot specify both system_prompt and system_message"
262▶ raise ValueError(msg)
263
264 if "system_prompt" in overrides:
· · ·
326- `ExtendedModelResponse`: Response with an optional `Command` for additional state updates
327 `goto`, `resume`, and `graph` are not yet supported on these commands.
328▶ A `NotImplementedError` will be raised if you try to use them.
329"""
330
+ 18 more matches in this file
30
31
32▶class ChevronError(SyntaxError):
33 """Custom exception for Chevron errors."""
34
· · ·
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 = {
+ 18 more matches in this file
41from langsmith.run_helpers import as_runnable, is_traceable_function
42from langsmith.schemas import Dataset, DataType, Example, Run, TracerSession
43▶from langsmith.utils import LangSmithError
44from requests import HTTPError
45from typing_extensions import TypedDict
· · ·
44▶from requests import HTTPError
45from typing_extensions import TypedDict
46
· · ·
71
72
73▶class InputFormatError(Exception):
74 """Raised when the input format is invalid."""
75
· · ·
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 = []
+ 60 more matches in this file
12
13from langchain_huggingface.utils.import_utils import (
14▶ IMPORT_ERROR,
15 is_ipex_available,
16 is_openvino_available,
· · ·
125 from transformers import pipeline as hf_pipeline # type: ignore[import]
126
127▶ except ImportError as e:
128 msg = (
129 "Could not import transformers python package. "
· · ·
130 "Please install it with `pip install transformers`."
131 )
132▶ raise ValueError(msg) from e
133
134 _model_kwargs = model_kwargs.copy() if model_kwargs else {}
· · ·
142 "`device_map`."
143 )
144▶ raise ValueError(msg)
145
146 if "device_map" in _model_kwargs:
· · ·
147 msg = "`device_map` is already specified in `model_kwargs`."
148▶ raise ValueError(msg)
149
150 _model_kwargs["device_map"] = device_map
+ 10 more matches in this file
14from packaging.version import parse
15from pydantic import SecretStr
16▶from requests import HTTPError, Response
17from typing_extensions import override
18
· · ·
48 f" {', '.join(invalid_group_names)}"
49 )
50▶ raise ValueError(msg)
51 return func(*args, **kwargs)
52
· · ·
57
58def raise_for_status_with_text(response: Response) -> None:
59▶ """Raise an error with the response text.
60
61 Args:
· · ·
62▶ response: The response to check for errors.
63
64 Raises:
· · ·
65▶ ValueError: If the response has an error status code.
66 """
67 try:
+ 36 more matches in this file