2,395 questions
2
votes
1
answer
61
views
How can I validate recursive Pydantic models where the validation rules depend on dynamic nesting depth?
I'm building a FastAPI application and modeling a forum-style comment system using Pydantic v2.
Each comment can contain replies, and those replies can contain more replies, recursively, similar to ...
0
votes
0
answers
76
views
how to fix this problem with pydantic core
I have rustc, I have cargo, I have c++ build tools, I have everything! but it doesn't work(
Error: command ['maturin', 'pep517', 'build-wheel', '-i', 'C:\\Users\\Admin\\Desktop\\ааа проекты\\.venv\\...
2
votes
2
answers
75
views
Combined Pydantic settings class from multiple settings classes with individual environment files
Let's say I have 2 simple BaseSettings classes that, each, load values from their individual environment files. Let's also say that there is a combined settings class that is based on the first 2 ...
Best practices
0
votes
3
replies
51
views
How to make a Pydantic field conditionally required based on another field?
I'm building a Pydantic model where a field's requirement depends on the value of another field.
Specifically, I want the cpf field to be required only if the country field is set to "BR". ...
1
vote
1
answer
47
views
Generate Open API spec from Pydantic with references to discriminators
I am trying to create a set of POJOs from an OpenAPI specification that is generated from a pydantic data model. The problem I'm hitting is with discriminators. I am currently using the following ...
1
vote
1
answer
32
views
How do I apply multiple filters with different conditions using LlamaIndex's MetadataFilters
I am using LlamaIndex's MetadataFilters to apply a filter to my ChromaDB VectorStoreIndex as a query engine. I am able to set multiple filters if they are using the same FilterCondition but how would ...
Best practices
0
votes
2
replies
42
views
Using pydantic_settings with Pytest
Goal
How can I use pydantic_settings in pytest? I want to have a .env.test environment file that has dummy values for all the environment variables. Some code has logic that depends on those variables ...
-4
votes
0
answers
95
views
Pydantic model that can take "Any" type?
Say I have a Pydantic model that can take an Any type. If the user sends in JSON on their end, what will Pydantic do here? Will it fail, or will request be of some known type?
Ultimately, I know ...
0
votes
0
answers
57
views
How to make Pydantic Generic model type-safe with subclassed data and avoid mypy errors?
I have the following abstract Data class and some concrete subclasses:
import abc
from typing import TypeVar, Generic, Union
from pydantic import BaseModel
T = TypeVar('T')
class Data(BaseModel, abc....
0
votes
1
answer
114
views
LangChain with_structured_output causes unknown enum label "any" error
I'm trying to use LangChain’s structured output feature with a Gemini model, however, whenever I try to run the chain, I get the error:
ValueError: unknown enum label "any"
Here’s the code I ...
0
votes
1
answer
73
views
Access expected type in Pydantic within a field wrap validator using the annotated pattern
I'm using a field wrap validator in Pydantic with the Annotated pattern, and I want to access the expected/annotated type of a field from within the validator function. Here's an example of what I ...
2
votes
1
answer
161
views
How to connect to Notion's remote MCP server from your own MCP client?
I'm experimenting with Pydantic AI as agentic framework and want to use Notion's remote MCP server as tool for my agent.
Remote server's endpoint seems to require OAuth token to be accessed, but I ...
1
vote
0
answers
67
views
Why does botocore raise ValidationException with pydantic BaseModel output constraint on variable length output types?
I am using pydantic AI and use pydantic BaseModel to set the output_type of the answer. From time to time I encounter a ValidationException. I cannot accurately pinpoint the issue creating this ...
1
vote
0
answers
58
views
How do I represent relationships? I get errors anyway I try
I have a sqlmodel defined database and I'm having issues with how to use sqlmodel. This is a two-table reduction of my DB.
from __future__ import annotations
import uuid
from datetime import datetime
...
0
votes
0
answers
88
views
verify Lazy fetch with Pydantic
I am creating a API to return pydantic backed object, with optional / "fetchable" fields that might not be fetched based on the API parameter passed in.
when accessing these optional data ...
3
votes
1
answer
175
views
How to use Pydantic field in another field for serialization/deserialization purposes
I would like to solve the following problem with Pydantic (latest version), with Python 3.x.
While deserializing, I want to use the field "path", path contains another array that I want to ...
1
vote
0
answers
83
views
Defining a pydantic dynamic model field in terms of another pydantic dynamic model
If I create a dynamic model:
BarModel = create_model(
'BarModel',
apple=(str, 'russet'),
banana=(str, 'yellow')
And then I want to create another dynamic model with a field of type '...
2
votes
1
answer
181
views
How to use Temporal pydantic_data_converter while not causing a workflow validation failure?
My understanding is that to get the pydantic_data_converter to auto convert outputs, you need to pass a function reference, i.e.
This properly returns a TestModel
result: TestModel = await ...
-1
votes
1
answer
39
views
Python unittest.mock fails when using pydantic.BaseModel
I have come across this problem when making my unit tests.
from unittest.mock import AsyncMock, patch
import pydantic
# class Parent(): # Using non-pydantic class works
class Parent(pydantic....
-4
votes
1
answer
83
views
Adding Custom Validation to Pydantic Models (TypeError: Object of Type ValueError is not JSON Serializable)
I am trying to set up custom validation for pydantic models. According to the the pydantic docs, custom validators can be applied to a field using the Annotated Pattern or field_validator() decorator ...
1
vote
1
answer
68
views
Extend existing Pydantic type
I'd like to extend existing Pydantic types such as FilePath by f.i. adding a file type pattern for
validation
serialization to JSON schema.
Current approach
I'd f.i. like to define my custom type ...
1
vote
0
answers
108
views
State is not injecting properly in langchain tool calls
So i have these two tools to store and give a file_path for AI-agent
class AnalystState(AgentState):
file_path: Optional[str]
last_tool_called: Optional[str]
@tool
def update_file_path(...
0
votes
1
answer
96
views
Schema Guided Reasoning to dynamically force LLM to select one of the values from list
I am trying to use a Schema Guided Reasoning approach to develop a system which will classify for me product into one of the categories from predefined list based on its name\description. For that I ...
0
votes
1
answer
70
views
Pydantic model inserts None values in Databricks Delta table as string type instead of null type
I have the below pydantic model with 6 columns out of which 2 columns are nullable.
from pydantic import BaseModel
from typing import Optional
class Purchases(BaseModel):
customer_id: int
...
0
votes
1
answer
62
views
How to propertly check the type of a Pydantic FieldInfo?
I want to check the type of a Pydantic FieldInfo:
from pydantic import BaseModel
from pydantic.fields import FieldInfo
class Address(BaseModel):
street: str
city: str
postcode: int
class ...
1
vote
1
answer
128
views
Is it possible to set the type of a field based on the value of another field?
I want to set and instantiate the right type based on the value of another field and get typing and autocomplete on it.
I want this to happen automatically when the class is instantiated:
...
4
votes
1
answer
208
views
How to add objects/links to a set of links in beanie?
Assume that I have these Beanie Documents which are based, by the way, on Pydantic Models:
File name: models.py
from beanie import Document, Link
class A(Document):
first: int
second: str
...
1
vote
1
answer
61
views
Pydantic Model with exactly one input out of two optionals
I want a pydantic Model that can take exactly one of two optional arguments, where the missing argument will be calculated from the other.
Consider this:
from pydantic import BaseModel, ...
0
votes
0
answers
205
views
Create recursive TypeAlias at runtime
For use with pydantic, I want to create recursive type aliases at runtime.
"Normal" type aliases are possible like this:
from typing import TypeAliasType
alias = TypeAliasType("alias&...
0
votes
0
answers
30
views
Deserialize Rust-like SymType / Enum with Pydantic
Background
Rust has the ability to express tagged-union as follows:
pub enum FooBar {
Foo { a: u32 },
Bar { b: String },
}
which serialize to:
{ "foo": { "a": 123 } } // ...
2
votes
1
answer
105
views
pydantic.ValidationError: LangChainInterface credentials instance expected when using wxai_langchain
I’m building a RAG application using LangChain and Watsonx AI with Streamlit. I want to create a LangChainInterface instance using my IBM Watsonx API credentials, but I’m getting the following ...
1
vote
0
answers
97
views
Pydantic agent - the agent tool/toolset decorator does not work on top of methods which have the runcontext
I am trying to build a pydantic AI agent
When defining my tools, when I pass in my tools along with my agent as parameter as
chat_agent = Agent(
model=create_chat_model(),
output_type=...
0
votes
1
answer
84
views
Custom pydantic model as response_model make the model inline
I'm working on a basecode which has some classic pydantic models (from BaseModel). But I'm also implementing custom models through implementing __get_pydantic_core_schema__ and ...
0
votes
0
answers
139
views
using pydantic.logfire sending data to grafana-otel-container
I am using lofgire to send traces, logs and metrics to grafana-otel container. However, in the grafana UI (reachable unter http://localhost:3000 and login is pw: admin & user: admin), only traces ...
8
votes
0
answers
2k
views
GPT-OSS does not return valid structured output with Langchain
I'm using LangChain with GPT-OSS models (served via Hyperbolic) to generate and evaluate answers.
My eval model is supposed to return a JSON object (using a Pydantic schema with the class name '...
2
votes
2
answers
260
views
SQLModel and emails
I'm currently working on an api using fastapi and sqlmodel. I'm new to these two and I might have missed something.
I have a user model with an e-mail field. So no email outside my organization is ...
1
vote
2
answers
119
views
pydantic model validator raise ValueError to field
I am trying to do a validation on passwords where if they dont match, return an error. But I want to assign the error to field.
class RequestFile(
BaseModel
):
password: str = Field(..., ...
2
votes
1
answer
404
views
How to use yaml_file parameter for pydantic settings
Here is my example code:
from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
yaml_file=...
1
vote
2
answers
253
views
How to freeze time without freezegun?
I'm writing integration tests with pytest for my FastAPI/SQLModel app, and I was looking for a way to freeze time directly inside the app.
While freezegun works fine in basic scenarios like unit tests,...
1
vote
0
answers
79
views
Optional fields defaulting to "string" or 0.0 instead of null in Swagger UI
I'm using FastAPI with Pydantic's BaseModel, and I'm trying to define optional fields with a default value of None. However, in the Swagger UI (auto-generated docs), FastAPI shows "string" ...
2
votes
1
answer
123
views
python type annotation of SpecialForms with pydantic and mypy
python 3.13
pydantic 2.10.5
mypy 1.16.0
how to properly annotate return of typing._SpecialForm, specifically typing.Annotated?
I'm using mypy as type checker.
from functools import partial
from ...
0
votes
1
answer
67
views
Problem with multiple Query in view of FastAPI application endpoint
I'm trying to develop filtering/ordering/pagination functionality for FastAPI applications. For now I'm facing difficulty with separating filtering and sorting. The code below generates undesirable ...
1
vote
0
answers
159
views
In what order do model_validators run in Pydantic?
The Pydantic documentation explicitly describes the order of field validators, but what about model_validators?
In what order do model_validators run?
Specifically, how are they ordered in an ...
0
votes
1
answer
1k
views
pip and uv point to ~/.local/bin/ even after activating virtual environment
I'm working on a python project created using uv on a ubuntu system.
I activated virtual environment using
source .venv/bin/activate
which python points to
/home/username/my-project/.venv/bin/python
...
1
vote
1
answer
95
views
Pydantic does not validate dict values when assigning an unexpected type to dict values
I have the question same with link
Pydantic does not validate the key/values of dict fields
from typing import Dict
from pydantic import BaseModel
class TableModel(BaseModel):
table: Dict[str, ...
5
votes
1
answer
816
views
Pydantic: How to return user friendly validation error messages?
Is there any way to change the validation messages from pydantic? The problem is this: I want to return these validation messages to my frontend but not all of the users prefer the language english ...
0
votes
0
answers
69
views
Pydantic field_validator with FastAPI
I have been using pydantic and FastAPI (separately and together) for a couple of years now and it's been great - until now.
I am trying to setup a POST API with a body that accepts a valid URL that ...
0
votes
1
answer
220
views
What are the benefits of using an annotated class vs. a dict[str, Any] in the declaration of an MCP tool?
FastMCP's documentation states that:
When you add return type annotations, FastMCP automatically generates output schemas to validate the structured data and enables clients to deserialize results ...
2
votes
1
answer
97
views
mypy linter error (valid-type) with pydantic's Annotated pattern in a generic
Why would the following give a linter error in the second case but not the first:
# OK:
type MyAnnotatedType = Annotated[int | None, Field(strict=True)]
# Error: Invalid type alias: expression is not ...
0
votes
0
answers
159
views
Why cannot import pydantic_ai with pydantic_ai in site-packages?
Why cannot import pydantic_ai with pydantic_ai in site-packages?
enter image description here
enter image description here
"D:\PYTHON PROJ\AIFileAgent\.venv\Scripts\python.exe" "D:\...