python Errors
243 error patterns
Asyncio event loop already running
RuntimeError: This event loop is already running
- •Use nest_asyncio.apply() to allow nested event loops
- •Use asyncio.run_coroutine_threadsafe() instead of asyncio.run()
Coroutine never awaited
RuntimeWarning: coroutine '.*' was never awaited
- •Add 'await' before the coroutine call
- •Use asyncio.create_task() to schedule the coroutine
Asyncio task was cancelled
asyncio\.CancelledError
- •Handle CancelledError in try/except within the task
- •Use asyncio.shield() to protect critical sections from cancellation
Executor shutdown prevents new task scheduling
RuntimeError: cannot schedule new futures after shutdown
- •Ensure all tasks are submitted before calling executor.shutdown()
- •Use 'with' context manager for ThreadPoolExecutor
Future attached to different event loop
RuntimeError: Task .* got Future .* attached to a different loop
- •Ensure all coroutines use the same event loop
- •Avoid creating futures in one loop and awaiting in another
No running event loop in current thread
RuntimeError: no running event loop
- •Use asyncio.run() to start the event loop
- •Use asyncio.new_event_loop() and set it with asyncio.set_event_loop()
Asyncio wait_for timeout exceeded
TimeoutError.*asyncio\.wait_for
- •Increase the timeout value in asyncio.wait_for()
- •Add retry logic with exponential backoff
Coroutine already awaited cannot be reused
RuntimeError: cannot reuse already awaited coroutine
- •Create a new coroutine instance for each await
- •Wrap in a function that returns a fresh coroutine each time
FastAPI 422 validation error on request
422 Unprocessable Entity.*validation error
- •Check request body matches the Pydantic model schema
- •Use Optional[] for nullable fields with default=None
FastAPI request validation error
fastapi\.exceptions\.RequestValidationError
- •Add custom exception handler with @app.exception_handler(RequestValidationError)
- •Check path parameter types match route definition
FastAPI dependency injection resolution failure
DependencyInjection.*Depends\(\).*cannot be resolved
- •Ensure dependency function signature matches expected parameters
- •Check that sub-dependencies are properly defined
FastAPI background task execution error
RuntimeError: BackgroundTask.*after response
- •Return BackgroundTasks in the route function parameter, not manually
- •Ensure background task function doesn't depend on request lifecycle
FastAPI WebSocket client disconnected
starlette\.websockets\.WebSocketDisconnect
- •Wrap receive() in try/except WebSocketDisconnect
- •Implement heartbeat/ping mechanism to detect stale connections
SQLAlchemy session transaction already rolled back
sqlalchemy\.exc\.InvalidRequestError: This Session's transaction has been rolled back
- •Call session.rollback() explicitly before retrying
- •Use session.begin() context manager for automatic rollback on exception
SQLAlchemy accessing attribute on detached instance
sqlalchemy\.exc\.DetachedInstanceError
- •Use eager loading (joinedload/selectinload) to load relationships before detaching
- •Keep the session open while accessing lazy-loaded attributes
SQLAlchemy stale data during flush
sqlalchemy\.orm\.exc\.StaleDataError
- •Refresh the instance with session.refresh(obj) before modifying
- •Use optimistic locking with version_id_col
SQLAlchemy lazy load in async session without greenlet
sqlalchemy\.exc\.MissingGreenlet.*lazy load.*within
- •Use selectinload() or joinedload() in the query options
- •Use run_sync() to access lazy attributes in async context
SQLAlchemy object already attached to another session
sqlalchemy\.exc\.InvalidRequestError.*is already attached to session
- •Use session.merge() instead of session.add() for detached objects
- •Expunge the object from the original session first
SQLAlchemy query returned no results
sqlalchemy\.exc\.NoResultFound
- •Use .first() instead of .one() if zero results is acceptable
- •Use .one_or_none() to get None instead of an exception
SQLAlchemy duplicate key integrity error
sqlalchemy\.exc\.IntegrityError.*duplicate key
- •Use INSERT ... ON CONFLICT DO UPDATE (upsert) pattern
- •Check for existence before inserting
Pydantic v2 validation error
pydantic_core\._pydantic_core\.ValidationError
- •Check field types match the input data
- •Use model_validate() instead of direct constructor for dict input
Pydantic v2 protected namespace conflict
PydanticUserError.*model_config.*protected_namespaces
- •Set model_config = ConfigDict(protected_namespaces=()) to disable
- •Rename fields that start with 'model_'
Pydantic v2 discriminated union discriminator missing
PydanticUserError.*discriminator.*not found
- •Add Literal type annotation for the discriminator field in each model
- •Ensure the discriminator field name exists in all union members
Pydantic v2 schema generation error
pydantic\.errors\.PydanticSchemaGenerationError
- •Use model_rebuild() after all models are defined for forward references
- •Replace complex types with simpler annotations or custom types
Pydantic v2 unexpected keyword in model init
TypeError.*BaseModel.*__init__.*unexpected keyword argument
- •Check model field names match the keyword arguments
- •Use model_config = ConfigDict(extra='allow') to permit extra fields
Poetry dependency resolution conflict
poetry\.installer\.installer.*SolverProblemError
- •Run 'poetry update' to refresh lock file
- •Use 'poetry add package@latest' to get compatible version
Poetry hash mismatch during install
CalledProcessError.*poetry.*install.*hash
- •Delete poetry.lock and run 'poetry lock' to regenerate
- •Clear Poetry cache with 'poetry cache clear pypi --all'
PDM resolution impossible for dependencies
pdm\.exceptions\.ResolutionImpossible
- •Widen version constraints in pyproject.toml
- •Use 'pdm update --unconstrained' to find a working set
PyTorch CUDA out of memory
RuntimeError:.*CUDA out of memory
- •Reduce batch size in training/inference
- •Use torch.cuda.empty_cache() to free unused memory
PyTorch tensor size mismatch
RuntimeError: The size of tensor a \(\d+\) must match the size of tensor b \(\d+\)
- •Check input dimensions with tensor.shape before operations
- •Use tensor.view() or tensor.reshape() to align dimensions
PyTorch tensor not tracking gradients
RuntimeError: element .* does not require grad and does not have a grad_fn
- •Set requires_grad=True on the tensor
- •Ensure the tensor is part of the computation graph (not detached)
PyTorch inplace operation breaks autograd
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
- •Replace inplace operations (+=, relu_) with out-of-place versions
- •Clone the tensor before modifying: x = x.clone()
PyTorch tensors on different devices
RuntimeError: Expected all tensors to be on the same device
- •Move all tensors to the same device with .to(device)
- •Use model.device to get the model's device and match tensors
NumPy array memory allocation error
numpy\.core\._exceptions\._ArrayMemoryError
- •Use memory-mapped arrays with np.memmap()
- •Process data in chunks instead of loading all at once
NumPy broadcasting shape mismatch
ValueError: operands could not be broadcast together with shapes
- •Reshape arrays to compatible dimensions with np.reshape()
- •Use np.expand_dims() to add dimensions for broadcasting
Pandas SettingWithCopyWarning
SettingWithCopyWarning: A value is trying to be set on a copy of a slice
- •Use .loc[] for label-based assignment: df.loc[mask, col] = value
- •Create an explicit copy with df.copy() before modifying
Pandas merge with no common columns
MergeError: No common columns to perform merge on
- •Specify left_on and right_on parameters explicitly
- •Rename columns to match before merging
Pandas DataFrame memory error
MemoryError.*pandas.*DataFrame
- •Use dtype optimization: df = pd.read_csv(file, dtype={'col': 'int32'})
- •Read in chunks with chunksize parameter
Pandas merge on columns with different types
ValueError: You are trying to merge on.*columns of different types
- •Cast columns to same type: df['col'] = df['col'].astype(str)
- •Use pd.to_numeric() or pd.to_datetime() for type conversion
Python Protocol class instantiation error
TypeError.*Protocol.*cannot be instantiated
- •Protocols are structural types - implement a concrete class instead
- •Use runtime_checkable decorator if you need isinstance() checks
Python overload without implementation
TypeError.*overload.*no implementation
- •Add a non-decorated implementation function after all @overload variants
- •The implementation must handle all overload signatures
TypeVar bound to non-class type
TypeError.*TypeVar.*bound.*is not a class
- •Use a Protocol class as the bound instead
- •Ensure the bound argument is a concrete class or Protocol
Asyncio future result accessed before set
asyncio\.exceptions\.InvalidStateError: Result is not set
- •Await the future before accessing .result()
- •Check future.done() before accessing the result
Asyncio timeout used outside task context
RuntimeError: Timeout context manager should be used inside a task
- •Ensure async with asyncio.timeout() is inside an async task
- •Use asyncio.wait_for(coro, timeout) as an alternative
FastAPI 401 Unauthorized
fastapi\.exceptions\.HTTPException.*status_code.*401
- •Check OAuth2 token is valid and not expired
- •Verify the Authorization header format is 'Bearer <token>'
Trying to await an async generator
TypeError: object (Async)?Generator.*can't be used in 'await' expression
- •Use 'async for' to iterate over async generators
- •If you need a single value, use anext(generator)
SQLAlchemy database connection lost
sqlalchemy\.exc\.OperationalError.*server closed the connection unexpectedly
- •Set pool_pre_ping=True in create_engine() to verify connections
- •Configure pool_recycle to a value less than DB timeout
SQLAlchemy table does not exist
sqlalchemy\.exc\.ProgrammingError.*relation.*does not exist
- •Run alembic upgrade head to apply migrations
- •Use Base.metadata.create_all(engine) for development
Pydantic v2 serialization error
pydantic.*SerializationError.*unable to serialize
- •Add custom serializer with @field_serializer decorator
- •Use model_config = ConfigDict(arbitrary_types_allowed=True)
PyTorch CUDA allocation failure with size info
torch\.cuda\.OutOfMemoryError.*tried to allocate
- •Use torch.cuda.memory_summary() to identify memory hogs
- •Implement gradient accumulation to reduce per-step memory
PyTorch incorrect tensor dimensions
RuntimeError: Expected .* to have .* dimensions but got .* dimensions
- •Use tensor.unsqueeze() to add missing dimensions
- •Use tensor.squeeze() to remove extra dimensions
PyTorch matrix multiplication shape mismatch
RuntimeError: mat1 and mat2 shapes cannot be multiplied
- •Verify Linear layer in_features matches input size
- •Use tensor.view(-1, correct_size) to reshape before linear layers
PyTorch optimizer has no parameters
ValueError: optimizer got an empty parameter list
- •Ensure model.parameters() is called after model is fully defined
- •Check that the model has trainable parameters (requires_grad=True)
Pandas CSV parsing error
pandas\.errors\.ParserError: Error tokenizing data
- •Use error_bad_lines=False (or on_bad_lines='skip' in newer pandas)
- •Specify the correct separator with sep parameter
Pandas column not in DataFrame index
KeyError:.*not in index
- •Check available columns with df.columns.tolist()
- •Use df.get(key, default) for safe access
Pandas duplicate index prevents reindexing
ValueError: cannot reindex from a duplicate axis
- •Reset index with df.reset_index(drop=True)
- •Remove duplicates with df[~df.index.duplicated()]
Poetry Python version incompatible with project
poetry.*Current Python version.*is not allowed by the project
- •Update python requirement in pyproject.toml: python = '^3.9'
- •Use pyenv to install and switch to compatible Python version
Rye toolchain download failure
rye.*error.*failed to download.*toolchain
- •Check network connectivity and proxy settings
- •Use 'rye toolchain list --include-downloadable' to see available versions
PDM package missing from lock file
pdm.*PackageWarning.*not found in the lock file
- •Run 'pdm lock' to regenerate the lock file
- •Use 'pdm add <package>' to add it properly
Pydantic model with unhashable field in set/dict key
TypeError: unhashable type: 'dict'.*Pydantic
- •Use frozenset or tuple instead of list/dict in hashable contexts
- •Implement __hash__ on custom types used as fields
Pydantic required field missing from input
pydantic.*ValidationError.*Field required
- •Provide the required field in input data
- •Add default value or Optional annotation to make field optional
SQLAlchemy column not found in mapping
sqlalchemy\.exc\.ArgumentError.*Could not locate any.*column
- •Verify column name matches exactly (case-sensitive)
- •Check that the model's __tablename__ is correct
SQLAlchemy connection pool exhausted
sqlalchemy\.exc\.TimeoutError.*QueuePool limit
- •Increase pool_size and max_overflow in create_engine()
- •Ensure sessions are closed/returned after use (use context managers)
SQLAlchemy AsyncSession method mismatch
AttributeError: 'AsyncSession' object has no attribute 'execute'
- •Use 'await session.execute()' - it's async
- •Ensure you imported from sqlalchemy.ext.asyncio
Asyncio stream read incomplete
asyncio\.IncompleteReadError
- •Handle IncompleteReadError for premature connection close
- •Use readexactly() with try/except for fixed-length reads
No event loop in non-main thread
RuntimeError: There is no current event loop in thread
- •Create new loop: loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop)
- •Use asyncio.run() which creates and sets a loop automatically
FastAPI lifespan state not accessible
fastapi.*LifespanState.*not available
- •Use the new lifespan context manager pattern with async generator
- •Access state via request.state instead of app.state in routes
FastAPI response contains non-serializable object
TypeError: Object of type .* is not JSON serializable.*FastAPI
- •Add custom JSON encoder via json_encoders in model Config
- •Use jsonable_encoder() from fastapi.encoders before returning
Pydantic invalid discriminator field
ValueError: \[Pydantic\] .* is not a valid discriminator
- •Use a Literal type for the discriminator field in each variant
- •Ensure the discriminator field is required (not Optional)
Pydantic model_validator before mode type error
pydantic.*model_validator.*mode='before'.*TypeError
- •In mode='before', input can be dict or the raw input - handle both
- •Use @model_validator(mode='wrap') for more control
PyTorch backward on non-scalar tensor
torch\.autograd\..*grad can be implicitly created only for scalar outputs
- •Call .sum() or .mean() on the loss before .backward()
- •Pass gradient argument to .backward() for non-scalar tensors
PyTorch second backward pass without retain_graph
RuntimeError: Trying to backward through the graph a second time
- •Use loss.backward(retain_graph=True) if you need multiple passes
- •Restructure code to avoid needing multiple backward passes
Pandas merge with duplicate keys
pandas\.errors\.MergeError.*merge keys.*not unique in (left|right) dataset
- •Use validate='one_to_one' to detect and raise early
- •Deduplicate before merge: df.drop_duplicates(subset=['key'])
Pandas deprecated axis=1 in groupby
FutureWarning.*DataFrame\.groupby with axis=1 is deprecated
- •Use df.T.groupby(...) then transpose back
- •Switch to using .apply() across columns instead
NumPy singular matrix in linear algebra
numpy\.linalg\.LinAlgError: Singular matrix
- •Use np.linalg.pinv() (pseudo-inverse) instead of np.linalg.inv()
- •Add regularization: matrix + eps * np.eye(n)
NumPy arithmetic overflow
RuntimeWarning: overflow encountered in (multiply|exp|power)
- •Use larger dtype (float64 instead of float32)
- •Apply log-space computation for very large values
Module not found in Poetry environment
ModuleNotFoundError: No module named '.*'.*poetry
- •Run 'poetry install' to install dependencies
- •Ensure you're running within the venv: 'poetry run python ...'
SQLAlchemy unconsumed column names in INSERT
sqlalchemy\.exc\.CompileError.*Unconsumed column names
- •Remove columns from values() that don't exist in the table
- •Check column names match table definition exactly
Alembic target database not up to date
alembic\.util\.exc\.CommandError.*Target database is not up to date
- •Run 'alembic upgrade head' before generating new migration
- •Use 'alembic stamp head' to mark current state if manually migrated
Alembic can't locate migration revision
alembic\.util\.exc\.CommandError.*Can't locate revision
- •Check migration files exist in alembic/versions/
- •Verify alembic_version table has a valid revision hash
FastAPI 403 Forbidden
fastapi\.exceptions\.HTTPException.*status_code.*403
- •Verify user has required permissions/roles
- •Check CORS configuration allows the origin
Pydantic issubclass error with type annotation
TypeError: issubclass\(\) arg 1 must be a class.*Pydantic
- •Use typing.get_origin() and typing.get_args() for generic types
- •Wrap complex annotations in Annotated[] with proper metadata
PyTorch distributed NCCL communication error
torch\.distributed.*NCCL error.*unhandled system error
- •Set NCCL_DEBUG=INFO for detailed error messages
- •Check all GPUs are accessible and CUDA versions match
PyTorch DataLoader worker killed
RuntimeError: DataLoader worker.*is killed by signal
- •Reduce num_workers in DataLoader
- •Increase shared memory (--shm-size in Docker)
Pandas datetime out of bounds
pandas\.errors\.OutOfBoundsDatetime
- •Use pd.Timestamp.min/max to check bounds before parsing
- •Set errors='coerce' in pd.to_datetime() to replace invalid with NaT
Pandas assignment length mismatch
ValueError: Length of values.*does not match length of index
- •Verify the array/list length matches DataFrame index length
- •Reset index before assignment: df.reset_index(drop=True)
SQLAlchemy relationship copying column warning
sqlalchemy\.exc\.SAWarning.*relationship .* will copy column
- •Set overlaps parameter on relationship: overlaps='other_rel'
- •Use back_populates instead of backref for explicit relationships
Protocol with attributes can't use issubclass
TypeError: Protocols with non-method members don't support issubclass
- •Only use isinstance() for runtime_checkable Protocols with non-method members
- •Remove @runtime_checkable if structural checking isn't needed at runtime
Pydantic model inheritance from invalid base
TypeError: type '.*' is not an acceptable base type.*Pydantic
- •Ensure base class inherits from BaseModel
- •Use composition instead of inheritance for non-Pydantic types
Asyncio barrier broken due to task failure
asyncio\.BrokenBarrierError
- •Wrap barrier.wait() in try/except and handle BrokenBarrierError
- •Reset the barrier with barrier.reset() if recovery is possible
Unclosed SSL socket resource warning
ResourceWarning: unclosed.*<ssl\.SSLSocket
- •Use async with for aiohttp sessions
- •Call await session.close() in a finally block
TorchScript type error with None value
torch\.jit\.Error.*expected.*Tensor.*got.*None
- •Use Optional[torch.Tensor] annotation for nullable returns
- •Add explicit None checks before tensor operations in scripted code
NumPy axis out of bounds
numpy\.AxisError: axis .* is out of bounds for array of dimension
- •Check array dimensions with arr.ndim before specifying axis
- •Use axis=-1 for the last dimension instead of hardcoding
FastAPI response_model validation failure
fastapi\.routing\.APIRoute.*response_model.*validation error
- •Ensure returned data matches response_model schema exactly
- •Use response_model_exclude_unset=True for partial responses
Pydantic computed_field with default value
pydantic\.errors\.PydanticUserError.*computed_field.*cannot have default
- •Remove default value from @computed_field decorated property
- •Computed fields derive their value from the property body
SQLAlchemy duplicate identity in session
sqlalchemy\.exc\.InvalidRequestError.*Can't attach instance.*another instance with key.*already present
- •Use session.merge() to reconcile with existing identity
- •Query for existing record first: session.get(Model, id)
Pydantic v2 import in v1 environment
ImportError: cannot import name 'field_validator' from 'pydantic'
- •Upgrade pydantic: pip install 'pydantic>=2.0'
- •Use @validator instead of @field_validator for Pydantic v1
Async generator concurrent access error
RuntimeError: async generator.*asend.*already running
- •Ensure only one consumer iterates the async generator at a time
- •Use asyncio.Lock() to serialize access to the generator
Pandas cannot cast NaN to integer
pd\.errors\.IntCastingNaNError.*Cannot convert non-finite values
- •Use pd.Int64Dtype() (nullable integer): df['col'].astype('Int64')
- •Fill NaN before casting: df['col'].fillna(0).astype(int)
PyTorch unsupported dtype for operation
torch\..*ComplexHalf.*not supported
- •Cast tensor to supported dtype: tensor.to(torch.float32)
- •Check operation documentation for supported dtypes
PyTorch CUDA Out of Memory
CUDA out of memory\. Tried to allocate [\d.]+ [GM]iB
- •Reduce batch size
- •Use torch.cuda.empty_cache() between iterations
PyTorch Tensor Dimension Mismatch
RuntimeError: The size of tensor a \(\d+\) must match the size of tensor b \(\d+\)
- •Check tensor shapes with .shape before operations
- •Use .view() or .reshape() to align dimensions
PyTorch Autograd Graph Already Freed
RuntimeError: Trying to backward through the graph a second time
- •Set retain_graph=True in .backward() if needed
- •Detach tensors with .detach() when reusing
PyTorch DataLoader Worker Killed
RuntimeError: DataLoader worker \(pid \d+\) is killed by signal
- •Reduce num_workers in DataLoader
- •Increase system shared memory (--shm-size in Docker)
PyTorch Mixed Device Tensors
RuntimeError: Expected all tensors to be on the same device, but found at least two devices
- •Move all tensors to same device with .to(device)
- •Check model.device and input.device match
PyTorch Inplace Operation Breaks Autograd
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
- •Replace inplace ops (x += y) with out-of-place (x = x + y)
- •Use .clone() before modifying tensors needed for grad
PyTorch CUDA OOM Error Class
torch\.cuda\.OutOfMemoryError: CUDA out of memory
- •Use mixed precision training with torch.cuda.amp
- •Implement gradient accumulation over smaller batches
PyTorch Distributed NCCL Failure
RuntimeError: NCCL communicator was aborted
- •Set NCCL_DEBUG=INFO for detailed error logs
- •Check network connectivity between nodes
PyTorch Matrix Multiplication Shape Error
RuntimeError: mat1 and mat2 shapes cannot be multiplied \(\d+x\d+ and \d+x\d+\)
- •Verify linear layer in_features matches input tensor last dim
- •Use .T or .transpose() to align matrices
PyTorch Model/Input Device Mismatch
RuntimeError: Input type \(torch\.cuda\.FloatTensor\) and weight type \(torch\.FloatTensor\) should be the same
- •Call model.to(device) before inference
- •Move input tensor with input.to(device)
PyTorch CUDA Device Assert
RuntimeError: CUDA error: device-side assert triggered
- •Run with CUDA_LAUNCH_BLOCKING=1 for exact line
- •Check label indices are within num_classes range
PyTorch Dtype Mismatch Float vs Half
RuntimeError: expected scalar type Float but found Half
- •Cast tensor with .float() or .half() as needed
- •Use torch.cuda.amp.autocast() for automatic mixed precision
PyTorch Concatenation Dimension Mismatch
RuntimeError: Sizes of tensors must match except in dimension \d+
- •Verify all tensors have same shape except concat dim
- •Use padding to equalize dimensions before concat
PyTorch CUDA Fork Error
RuntimeError: Cannot re-initialize CUDA in forked subprocess
- •Set multiprocessing start method to 'spawn'
- •Initialize CUDA after fork, not before
PyTorch Loss Function Size Mismatch
ValueError: Target size \(torch\.Size\(\[.*\]\)\) must be the same as input size
- •Squeeze predictions with .squeeze() to match target shape
- •Verify batch dimensions align between pred and target
PyTorch CPU Tensor Passed to CUDA Op
RuntimeError: Expected object of device type cuda but got device type cpu
- •Move tensor to GPU with tensor.cuda() or tensor.to('cuda')
- •Check all inputs in forward() are on correct device
PyTorch Non-Scalar Backward
RuntimeError: grad can be implicitly created only for scalar outputs
- •Reduce loss to scalar with .mean() or .sum()
- •Pass gradient argument to .backward(gradient=...)
PyTorch cuDNN Unsupported Config
RuntimeError: cuDNN error: CUDNN_STATUS_NOT_SUPPORTED
- •Set torch.backends.cudnn.enabled = False to debug
- •Check input dimensions meet cuDNN requirements
PyTorch Stack Unequal Tensors
RuntimeError: stack expects each tensor to be equal size
- •Pad sequences to same length before stacking
- •Use torch.nn.utils.rnn.pad_sequence()
PyTorch View Non-Contiguous Tensor
RuntimeError: view size is not compatible with input tensor's size and stride
- •Call .contiguous() before .view()
- •Use .reshape() instead which handles non-contiguous
TensorFlow SavedModel Not Found
tensorflow\.python\.framework\.errors_impl\.NotFoundError: SavedModel file does not exist
- •Verify saved_model.pb exists in the directory
- •Use correct path without trailing slash
TensorFlow Disconnected Graph Error
tensorflow\.python\.framework\.errors_impl\.InvalidArgumentError: Graph disconnected
- •Ensure all layers are connected in model definition
- •Check for orphaned layers not linked to input/output
TensorFlow Invalid Optimizer
ValueError: Could not interpret optimizer identifier
- •Use string name like 'adam' or instance tf.keras.optimizers.Adam()
- •Check optimizer is from tf.keras.optimizers not tf.train
TensorFlow NaN/Inf Loss
tensorflow.*LossTensor is inf or nan
- •Add tf.debugging.check_numerics() to detect source
- •Reduce learning rate
TensorFlow TPU Not Available
RuntimeError: TPU.*not available
- •Initialize TPU with tf.distribute.cluster_resolver.TPUClusterResolver()
- •Call tf.tpu.experimental.initialize_tpu_system()
TensorFlow Layer Input Incompatible
ValueError: Input \d+ of layer .* is incompatible with the layer
- •Check input_shape parameter matches actual input dimensions
- •Add Input layer with correct shape specification
TensorFlow GPU OOM
ResourceExhaustedError: OOM when allocating tensor
- •Set tf.config.experimental.set_memory_growth(gpu, True)
- •Reduce batch size in training config
TensorFlow Shape Incompatibility
InvalidArgumentError: Incompatible shapes: \[\d+.*\] vs\. \[\d+.*\]
- •Use tf.debugging.assert_shapes() to validate
- •Reshape with tf.reshape() before the operation
TensorFlow Keras Shape Compile Error
ValueError: Shapes \(.*\) and \(.*\) are incompatible
- •Verify model.compile() metrics match output shape
- •Check loss function expects correct output format
TensorFlow Operation Cancelled
AbortedError: .* was cancelled
- •Check for session timeout in distributed training
- •Increase RPC timeout for remote operations
HuggingFace Tokenizer Type Mismatch
The tokenizer class you load from this checkpoint is not the same type
- •Use AutoTokenizer.from_pretrained() instead of specific class
- •Ensure tokenizer and model are from same checkpoint
HuggingFace Model File Missing
RuntimeError: .* does not appear to have a file named pytorch_model\.bin
- •Check if model uses safetensors format instead
- •Download with from_pretrained(model_name, use_safetensors=True)
HuggingFace Model Too Large for GPU
torch\.cuda\.OutOfMemoryError.*loading.*model
- •Load with device_map='auto' for automatic sharding
- •Use load_in_8bit=True or load_in_4bit=True with bitsandbytes
HuggingFace Pipeline Model Incompatible
PipelineException: The model .* is not compatible with this pipeline
- •Verify model task matches pipeline type (e.g., text-generation)
- •Specify task explicitly in pipeline() call
HuggingFace Tokenizer Overflow
ValueError: Unable to create tensor.*overflowing values
- •Set truncation=True in tokenizer call
- •Specify max_length parameter
HuggingFace Training NaN Loss
FloatingPointError: Overflow.*loss became NaN
- •Enable fp16=True with loss scaling in TrainingArguments
- •Reduce learning rate by 10x
HuggingFace Embedding Index OOB
IndexError: index out of range in self.*Embedding
- •Resize embeddings with model.resize_token_embeddings(len(tokenizer))
- •Check tokenizer vocab size matches model embedding size
HuggingFace Config Missing
OSError: .* does not appear to have a file named config\.json
- •Verify model name/path is correct on HuggingFace Hub
- •Check internet connection for model download
HuggingFace Wrong Input Type to Tokenizer
ValueError: text input must of type `str`.*but is.*<class 'list'>
- •Pass single string or list of strings to tokenizer
- •Use tokenizer.batch_encode_plus() for list inputs
HuggingFace Attention Mask Shape Error
RuntimeError: The expanded size of the tensor.*must match the existing size
- •Ensure attention_mask shape matches input_ids shape
- •Pad both input_ids and attention_mask to same length
LangChain Output Parser Failed
OutputParserException: Could not parse LLM output
- •Add output_fixing_parser with retry logic
- •Improve prompt to enforce output format
LangChain Vector Store Document Not Found
ValueError: Could not find.*in vectorstore
- •Verify documents were added to vectorstore before query
- •Check embedding model matches between index and query time
LangChain Chain Missing Input Variables
langchain.*ChainError.*missing.*input_variables
- •Check all required variables in prompt template are passed
- •Verify chain.invoke() dict keys match template variables
LangChain Retriever Failure
RetrieverError: Failed to retrieve documents
- •Check vectorstore connection is alive
- •Verify embedding dimensions match stored embeddings
LangChain Pydantic Validation Error
langchain.*ValidationError.*field required
- •Provide all required fields in model/chain config
- •Check API key environment variables are set
OpenAI API Rate Limit
openai\.RateLimitError: Rate limit reached
- •Implement exponential backoff with tenacity or backoff library
- •Use tiktoken to estimate tokens and batch efficiently
OpenAI Token Limit Exceeded
openai\.BadRequestError:.*maximum context length.*tokens.*you requested \d+ tokens
- •Truncate input to fit within model context window
- •Use tiktoken to count tokens before sending
OpenAI Function Calling Schema Error
openai\.BadRequestError:.*Invalid schema for function
- •Validate JSON Schema before passing to API
- •Ensure parameters.type is 'object' with properties defined
OpenAI API Connection Failed
openai\.APIConnectionError: Connection error
- •Check network connectivity and proxy settings
- •Set httpx timeout with timeout=httpx.Timeout(60.0)
OpenAI Streaming Response Error
openai.*Stream.*error.*incomplete
- •Add try/except around stream iteration with retry
- •Set stream_options={'include_usage': True} to detect end
OpenAI Invalid API Key
openai\.AuthenticationError: Incorrect API key provided
- •Verify OPENAI_API_KEY env var is set correctly
- •Check key starts with sk- and has no trailing whitespace
OpenAI Content Filter Triggered
openai\.BadRequestError:.*content_filter
- •Rephrase input to avoid triggering content policy
- •Add system message clarifying legitimate use case
OpenAI Invalid Tool Choice
openai\.BadRequestError:.*'tool_choice'.*not.*valid
- •Use tool_choice='auto' or {'type':'function','function':{'name':'...'}}
- •Verify function name in tool_choice exists in tools list
Ollama Model Not Found
Error: model .* not found.*try pulling it first
- •Run 'ollama pull <model-name>' to download model
- •Check available models with 'ollama list'
Ollama Context Length Exceeded
context length exceeded.*maximum.*\d+
- •Set num_ctx parameter in model options to increase context
- •Truncate input to fit within model context window
Ollama Quantization Format Error
error loading model.*quantization.*not supported
- •Download correct quantization format for your hardware
- •Use Q4_0 or Q4_K_M for lower memory systems
Ollama Server Not Running
connection refused.*localhost:11434
- •Start Ollama with 'ollama serve' command
- •Check if port 11434 is available or change OLLAMA_HOST
PyTorch Model Parallelism OOM
RuntimeError: CUDA out of memory.*model parallel
- •Balance layer distribution across GPUs more evenly
- •Use pipeline parallelism with smaller micro-batches
PyTorch Missing Model Weight
RuntimeError: module.*has no attribute.*weight
- •Load state_dict with strict=False to see missing keys
- •Verify checkpoint matches model architecture version
PyTorch Memory Format Mismatch
RuntimeError: Expected.*channels_last.*but got.*contiguous_format
- •Convert tensor with .to(memory_format=torch.channels_last)
- •Ensure model and input use same memory format
PyTorch Scheduler Before Optimizer Step
RuntimeError: Detected.*call of.*lr_scheduler\.step\(\) before.*optimizer\.step\(\)
- •Move scheduler.step() after optimizer.step()
- •Follow order: loss.backward() → optimizer.step() → scheduler.step()
PyTorch Tensor No Grad for Backward
RuntimeError: element \d+ of tensors does not require grad
- •Set requires_grad=True on tensor
- •Verify tensor is part of computation graph
PyTorch Non-Tensor Grad Requirement
RuntimeError: Only Tensors.*can.*require gradients
- •Convert numpy array to tensor with torch.from_numpy()
- •Ensure Variable is replaced with Tensor (deprecated API)
PyTorch Distributed System Error
torch\.distributed\.DistBackendError: NCCL error.*unhandled system error
- •Check GPU driver version compatibility
- •Set NCCL_P2P_DISABLE=1 if P2P communication fails
PyTorch Unexpected Dtype in Operation
RuntimeError: Expected.*dtype.*but got.*dtype
- •Cast tensors with .to(dtype=torch.float32)
- •Check model expects float32 vs float16 input
HuggingFace Trainer Missing Dataset
ValueError: Trainer requires a train_dataset or a data_collator
- •Pass train_dataset to Trainer constructor
- •Create dataset with datasets.Dataset.from_dict()
HuggingFace Trainer OOM During Training
OutOfMemoryError.*during.*Trainer\.train\(\)
- •Set per_device_train_batch_size=1 with gradient_accumulation_steps
- •Enable fp16=True or bf16=True in TrainingArguments
HuggingFace Batch Size Mismatch in Loss
ValueError: Expected input batch_size.*to match target batch_size
- •Verify labels shape matches model output shape
- •Check data collator produces correct batch format
HuggingFace BitsAndBytes CUDA Error
ImportError: .*bitsandbytes.*CUDA
- •Install bitsandbytes with pip install bitsandbytes
- •Verify CUDA toolkit version matches bitsandbytes requirements
HuggingFace Feature Count Mismatch
ValueError: The model.*expects.*features.*but got
- •Verify dataset columns match model expected inputs
- •Remove or rename extra columns with dataset.remove_columns()
LangChain Callback Handler Error
langchain.*callbacks.*error.*handler
- •Implement all required methods in custom callback handler
- •Use AsyncCallbackHandler for async chains
LangChain Memory Key Mismatch
langchain.*memory.*ConversationBufferMemory.*key
- •Set memory_key parameter to match chain's expected input
- •Use input_key and output_key params in memory config
LangChain Text Splitter Invalid Config
langchain.*text_splitter.*chunk_size.*must be.*chunk_overlap
- •Set chunk_size larger than chunk_overlap
- •Typical values: chunk_size=1000, chunk_overlap=200
LangChain ChromaDB Duplicate ID
chromadb.*DuplicateIDError
- •Generate unique IDs for each document chunk
- •Use hash of content + metadata as ID
LangChain Agent Output Parse Failure
langchain.*agent.*Could not parse LLM output
- •Use handle_parsing_errors=True in AgentExecutor
- •Add format instructions to agent prompt
OpenAI Internal Server Error
openai\.InternalServerError: The server had an error
- •Implement retry with exponential backoff
- •Try alternative model if specific model is overloaded
OpenAI Response Truncated by Max Tokens
openai.*finish_reason.*length.*max_tokens
- •Increase max_tokens parameter in API call
- •Implement continuation logic to stitch multiple responses
OpenAI Empty Message Content
openai.*invalid_request_error.*messages.*must.*content
- •Ensure all messages have non-null content field
- •Remove messages with None content from history
TensorFlow Variable Not Initialized
tensorflow\.python\.framework\.errors_impl\.FailedPreconditionError:.*not initialized
- •Call tf.compat.v1.global_variables_initializer() in TF1 code
- •Use tf.Variable with initial_value in TF2
TensorFlow Mixed Precision Underflow
tensorflow.*mixed_precision.*loss_scale.*underflow
- •Increase initial_scale in LossScaleOptimizer
- •Use dynamic loss scaling with longer scale_window
TensorFlow No Gradients Available
ValueError: No gradients provided for any variable
- •Verify loss is connected to trainable variables
- •Check tf.GradientTape watches the correct variables
TensorFlow Logits Labels Batch Mismatch
InvalidArgumentError:.*logits and labels must have the same first dimension
- •Verify batch sizes match between predictions and labels
- •Check for inadvertent shape broadcasting
TensorFlow Keras API Method Missing
tensorflow.*keras.*Model.*has no attribute.*predict_proba
- •Use model.predict() instead of predict_proba()
- •Wrap model output with sigmoid/softmax for probabilities
TensorFlow Placeholder Not Fed (TF1)
INVALID_ARGUMENT: You must feed a value for placeholder tensor
- •Migrate to TF2 eager mode eliminating placeholders
- •Provide all required feed_dict values in session.run()
TensorFlow TPU Compilation Timeout
RuntimeError:.*DeadlineExceeded.*TPU.*compilation
- •Reduce model size or batch size for faster compilation
- •Use tf.function with jit_compile=False for debugging
HuggingFace Hub Authentication Error
huggingface_hub.*HTTPError: 401.*token
- •Run huggingface-cli login with valid token
- •Set HF_TOKEN environment variable
HuggingFace Missing Padding Token
ValueError: Asking to pad but the tokenizer does not have a padding token
- •Set tokenizer.pad_token = tokenizer.eos_token
- •Add pad token with tokenizer.add_special_tokens({'pad_token': '[PAD]'})
PyTorch CUDA Compute Capability Mismatch
CUDA error: no kernel image is available for execution on the device
- •Install PyTorch built for your GPU architecture
- •Check GPU compute capability with nvidia-smi
PyTorch Numpy Not Available
RuntimeError: Numpy is not available
- •Install numpy with pip install numpy
- •Check numpy version compatibility with PyTorch version
LangChain LCEL Runnable Input Error
langchain.*RunnableSequence.*error.*input
- •Verify input dict keys match RunnablePassthrough assignments
- •Use RunnableLambda to transform inputs between steps
FAISS Index Dimension Mismatch
faiss.*IndexError.*dimension
- •Verify embedding dimension matches index dimension at creation
- •Rebuild index with correct dimension: faiss.IndexFlatL2(dim)
OpenAI JSON Mode Missing Instruction
openai.*json_mode.*must.*contain.*JSON
- •Add 'respond in JSON' to system or user message
- •Include JSON format example in the prompt
PyTorch Checkpoint Weight Size Mismatch
RuntimeError:.*weight.*copying from.*size.*different
- •Use strict=False in load_state_dict and handle missing keys
- •Verify model architecture matches checkpoint version
HuggingFace Generation Config Conflict
ValueError:.*GenerationConfig.*max_new_tokens.*max_length
- •Use max_new_tokens instead of max_length for generate()
- •Remove conflicting generation parameters
HuggingFace Accelerate Device Map Error
accelerate.*dispatch.*model.*device_map.*error
- •Install accelerate: pip install accelerate
- •Use device_map='auto' for automatic allocation
HuggingFace Deprecated API Argument
TypeError: .* got an unexpected keyword argument 'return_dict'
- •Update transformers to latest version
- •Remove deprecated arguments from model forward call
LangChain Embedding Dimension Changed
langchain.*embeddings.*dimension.*mismatch
- •Delete and recreate vector store with new embeddings
- •Ensure same embedding model is used for index and query
OpenAI Model Access Denied
openai\.PermissionDeniedError:.*model.*does not exist or you do not have access
- •Verify model name is correct (e.g., gpt-4 vs gpt-4-turbo)
- •Check API key has access to requested model
Ollama Insufficient GPU Memory
ollama.*gpu.*memory.*insufficient
- •Use smaller quantization (Q4_0 instead of Q8_0)
- •Set OLLAMA_NUM_GPU=0 to run on CPU
PyTorch Flash Attention Dtype Error
RuntimeError: FlashAttention.*not supported.*dtype
- •Cast input to float16 or bfloat16 for Flash Attention
- •Set attn_implementation='eager' to disable Flash Attention
JWT Invalid Structure (Python)
JWT.*decode.*invalid number of segments
- •Check token has exactly 3 base64url segments separated by dots
- •Verify no Bearer prefix is included in the token value
Python JWT Not Enough Segments
jwt\.exceptions\.DecodeError: Not enough segments
- •Ensure complete token is passed (header.payload.signature)
- •Check token wasn't truncated during transmission
Python JWT Invalid Algorithm
jwt\.exceptions\.InvalidAlgorithmError
- •Specify algorithms=['RS256'] in decode() call
- •Never allow 'none' or HS256 when expecting RS256
Unsupported operand types
TypeError: unsupported operand type\(s\) for (.+): '(.+)' and '(.+)'
- •Cast operands to compatible types (e.g., int(x) + int(y))
- •Check that variables hold the expected types before the operation
Object is not callable
TypeError: '(.+)' object is not callable
- •Remove parentheses if you're accessing a property, not calling a function
- •Check if you accidentally shadowed a built-in function (e.g., list = [1,2])
Unhashable type used as dict key or in set
TypeError: unhashable type: '(.+)'
- •Convert list to tuple before using as a dict key or set element
- •Use frozenset() instead of set() for hashable set keys
Wrong type passed to function
TypeError: (.+) expected (.+), got (.+)
- •Cast the argument to the expected type (e.g., int(), str(), bytes())
- •Check function signature for expected parameter types
Wrong number of arguments
TypeError: (.+) takes (\d+) positional arguments? but (\d+) (?:was|were) given
- •Check function definition for the correct number of parameters
- •Add 'self' as the first parameter if this is an instance method
Cannot unpack non-iterable object
TypeError: cannot unpack non-iterable (.+) object
- •Ensure the function returns a tuple/list before unpacking (a, b = func())
- •Check that the right-hand side is iterable
Object has no attribute
AttributeError: '(.+)' object has no attribute '(.+)'
- •Check for typos in the attribute/method name
- •Verify the object is the type you expect (print(type(obj)))
NoneType has no attribute
AttributeError: 'NoneType' object has no attribute '(.+)'
- •A function returned None unexpectedly — check return statements
- •Add a None check before accessing the attribute: if obj is not None
Module not found
ModuleNotFoundError: No module named '(.+)'
- •Install the package: pip install <module_name>
- •Activate your virtual environment before running
Cannot import name from module
ImportError: cannot import name '(.+)' from '(.+)'
- •Check for circular imports between modules
- •Verify the name exists in the target module (may have been renamed or removed)
Unexpected indent
IndentationError: unexpected indent
- •Remove extra spaces/tabs at the beginning of the line
- •Ensure consistent indentation (all spaces or all tabs, not mixed)
Expected an indented block
IndentationError: expected an indented block
- •Add a body to the if/for/def/class block (use 'pass' as placeholder)
- •Check that the line after a colon is properly indented
Invalid syntax
SyntaxError: invalid syntax
- •Check the line above for a missing closing parenthesis, bracket, or quote
- •Ensure colons are present after if/for/while/def/class statements
Unexpected end of file
SyntaxError: unexpected EOF while parsing
- •Add a missing closing parenthesis, bracket, or brace
- •Ensure multi-line strings are properly closed with matching quotes
f-string syntax error
SyntaxError: f-string: (.+)
- •Escape braces in f-strings with double braces: {{ and }}
- •Don't use backslashes inside f-string expressions — assign to a variable first
Invalid literal for int()
ValueError: invalid literal for int\(\) with base (\d+): '(.+)'
- •Strip whitespace before conversion: int(value.strip())
- •Validate the string contains only digits before converting
Too many values to unpack
ValueError: too many values to unpack \(expected (\d+)\)
- •Add more variables on the left side to match the iterable length
- •Use *rest to capture extra values: a, b, *rest = iterable
Not enough values to unpack
ValueError: not enough values to unpack \(expected (\d+), got (\d+)\)
- •Reduce the number of variables on the left side
- •Verify the iterable contains enough elements
Dictionary key not found
KeyError: (.+)
- •Use dict.get(key, default) to provide a fallback value
- •Check key existence with 'if key in dict' before accessing
List index out of range
IndexError: list index out of range
- •Check list length before accessing: if len(lst) > index
- •Use try/except IndexError for safe access
File or directory not found
FileNotFoundError: \[Errno 2\] No such file or directory: '(.+)'
- •Use absolute paths or verify working directory with os.getcwd()
- •Check file path for typos and correct OS path separators
Name is not defined
NameError: name '(.+)' is not defined
- •Check for typos in the variable or function name
- •Ensure the variable is defined before it's used (order matters)
Maximum recursion depth exceeded
RecursionError: maximum recursion depth exceeded
- •Add or fix the base case in your recursive function
- •Convert to an iterative approach using a stack/queue
Permission denied
PermissionError: \[Errno 13\] Permission denied: '(.+)'
- •Run with elevated privileges (sudo on Linux/macOS, admin on Windows)
- •Check file permissions: os.chmod() or fix in file explorer
Address already in use
OSError: \[Errno 98\] Address already in use
- •Kill the process using the port: lsof -i :PORT then kill -9 PID
- •Use a different port for your server
pip cannot find package version
ERROR: Could not find a version that satisfies the requirement (.+)
- •Check the package name spelling on PyPI (pypi.org)
- •Upgrade pip: pip install --upgrade pip
Externally managed environment (PEP 668)
error: externally-managed-environment
- •Create a virtual environment: python -m venv .venv && source .venv/bin/activate
- •Use pipx for CLI tools: pipx install <package>
Django: no such table
django\.db\.utils\.OperationalError: no such table: (.+)
- •Run migrations: python manage.py makemigrations && python manage.py migrate
- •Ensure the app is in INSTALLED_APPS in settings.py
Django: template not found
django\.template\.exceptions\.TemplateDoesNotExist: (.+)
- •Add the template directory to TEMPLATES[0]['DIRS'] in settings.py
- •Ensure APP_DIRS is True and the app is in INSTALLED_APPS
Django/Flask: CSRF verification failed
Forbidden \(CSRF (?:cookie|token) not set\)|CSRF verification failed
- •Add {% csrf_token %} inside your <form> tag in Django templates
- •Include X-CSRFToken header in AJAX requests
Flask/Jinja2: template not found
jinja2\.exceptions\.TemplateNotFound: (.+)
- •Place templates in a 'templates/' folder relative to your app
- •Set template_folder parameter in Flask(__name__, template_folder='...')
Flask: working outside application context
RuntimeError: Working outside of application context
- •Wrap code in: with app.app_context():
- •Use @app.before_request or access within a route handler
Module not found — virtual environment not activated
ModuleNotFoundError: No module named '(.+)'\.?.*(?:Did you mean|\(venv\))
- •Activate virtual environment: source .venv/bin/activate (Linux/Mac) or .venv\Scripts\activate (Windows)
- •Ensure your IDE/terminal is using the correct Python interpreter from the venv
Unicode decode error
UnicodeDecodeError: '(.+)' codec can't decode byte
- •Specify encoding when opening files: open(file, encoding='utf-8')
- •Try 'latin-1' or 'cp1252' for legacy Windows files
JSON decode error
json\.decoder\.JSONDecodeError: (.+)
- •Validate JSON format — check for trailing commas, single quotes, or unquoted keys
- •Ensure the response is actually JSON (check Content-Type header)
Requests connection error
requests\.exceptions\.ConnectionError: (.+)
- •Check that the target server is running and accessible
- •Verify the URL scheme (http vs https) and port number
Django: database integrity constraint violation
django\.db\.utils\.IntegrityError: (.+) violates (.+) constraint
- •Check for duplicate values on unique fields before saving
- •Use get_or_create() instead of create() to avoid duplicates
Object not JSON serializable
TypeError: Object of type (.+) is not JSON serializable
- •Convert datetime to string: obj.isoformat()
- •Use a custom encoder: json.dumps(data, default=str)
Asyncio timeout
asyncio\.exceptions\.TimeoutError|asyncio\.TimeoutError
- •Increase the timeout value in asyncio.wait_for() or aiohttp session
- •Add retry logic for transient network issues
StopIteration — iterator exhausted
StopIteration
- •Use next(iterator, default_value) to provide a fallback
- •Wrap in try/except StopIteration or use a for loop instead