2,379 questions
0
votes
1
answer
19
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
22
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
78
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:
...
0
votes
0
answers
36
views
Represent datetime and enum in JSON for Pydantic [closed]
I am trying to create a Pydantic schema via Python.
Not with the data themselves but the JSON reprensentation of a schema and then I pass it to the generate method of datamodel_code_generator module.
...
3
votes
1
answer
93
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
46
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
52
views
Create recursive TypeAlias at runtime [duplicate]
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&...
-3
votes
0
answers
54
views
What is better Optional or | None in python type hints? [duplicate]
There are two equeal ways to specify optional field, e.g. pydantic.
class MyCLass(Baseodel):
field1: Optional[StrInt]
field2: StrInt| None
Which way is better: field1 or field2?
0
votes
0
answers
21
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
93
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
50
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
59
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
71
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 ...
6
votes
0
answers
1k
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
139
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
96
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(..., ...
1
vote
1
answer
174
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
133
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
43
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" ...
1
vote
1
answer
69
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
56
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
75
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
312
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
68
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, ...
4
votes
1
answer
289
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
48
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
117
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
69
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
111
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:\...
0
votes
1
answer
66
views
FastAPI + Enum validation on endpoint
I have a custom enum class:
class CustomEnum(Enum):
ONE = 1
TWO = 2
I have a fastapi endpoint:
@router.post(...)
async def example(request: Request, param: CustomEnum = Body(...)):
print(...
3
votes
1
answer
125
views
Cannot send a request through FastAPI in Python (Failed to connect to localhost port 8000 after 0 ms: Couldn't connect to server)
I devised a spam detecter for my example but I cannot send any request through Postman
Here is the requirement.txt file
fastapi
uvicorn[standard]
transformers
torch
Here is my python file shown below
...
1
vote
0
answers
86
views
Pydantic v2 + Python 3.13: PEP 695 type-alias of a generic model returns TypeAliasType (no model_rebuild()) — how can I keep a real BaseModel?
I’m experimenting with Python 3.13 and Pydantic v2.11.7.
My goal is to avoid writing
GenericTraining[Discriminate[L1LossConfig]]
over and over—I’d like a terse alias such that I can do
TrainingLike[...
0
votes
0
answers
36
views
Handle shadowed attribute in multiple inheritance
What is the best way to handle attribute shadowing from multiple inheritance?
Intended behavior is to end up with a Field.
from pydantic import BaseModel
class Parent(object):
value: int = 1
...
1
vote
0
answers
108
views
How to define a Pydantic model that extracts nested attribute values from an ORM object when using from_attributes=True?
I'm using Pydantic v2 to define different response models depending on the use case. Some models reflect the structure of the ORM model exactly, and .model_validate(obj) works fine in those cases.
...
0
votes
0
answers
17
views
FastAPI returns 422 Unprocessable Entity when posting JSON payload, even though data matches Pydantic model [duplicate]
I'm working on a monitoring project where a client script collects system metrics and posts them to a FastAPI server. However, I'm consistently getting a 422 Unprocessable Entity error even though the ...
3
votes
1
answer
474
views
Google ADK Building Agent - Pydantic Validation Error
I am trying to build an agent in Google adk by passing in some JSON formatted input to one agent as input_schema but for some reason the error keeps popping up.
QAAgentPrompt = "Checks the ...
-3
votes
2
answers
326
views
Python Pydantic: Optional non-nullable field
from pydantic import BaseModel
class MyModel(BaseModel):
id: int
name: str # this should be optional
MyModel(id=1)
This raises a ValidationError. Setting name: str | None = None is ...
0
votes
1
answer
137
views
How to manipulate a model (Pydantic) which just is defined at runtime
I have a situation like this: I know there will be a Person object model. But I haven't know it's attribute yet, until run time. a Person object will be defined and write into a Python file in project ...
0
votes
0
answers
67
views
How to use response_format with dynamic Pydantic attributes (Mistral LARGE API)
I'm using Mistral Large to analyze PDFs. As input, I provide the PDF and a response-format, which is a Pydantic class defining the output structure.
Here is my api call:
chat_response = self.client....
1
vote
0
answers
132
views
How can I extend an annotated type
Using Python 3.10, I have a base type definition that I use in many models:
Alpha = Annotated[str, Field(pattern=r'[A-Za-z]')]
I want to create additional specialised types based on this type, for ...
0
votes
0
answers
24
views
The Type Point in geojson_pydantic is not hashable
I'm using Python 3.11 and I am struggling a lot to understand this.
When I try to access to the Swagger documentation of my service, in localhost, I have this error:
generate_definitions ...
3
votes
0
answers
91
views
Remove exeption type in Pydantic field validator error message [duplicate]
I am using FastAPI with Pydantic.
Let's say I have this little code:
from pydantic import BaseModel, Field, model_validator
class Product(BaseModel):
price: float = Field(ge=0, description="...
-1
votes
2
answers
78
views
Error with file_search tool in langchain python library
I have an error with my langchain-openai when I use the file_search tool:
File "/backend/.venv/lib/python3.11/site-packages/langchain_openai/chat_models/base.py", line 3386, in ...
1
vote
0
answers
145
views
How to get full, raw, serialized prompt that is sent to LLM using Instructor
My question is specifically for use with the Python Instructor library. Is there a way to get the full, raw, serialized prompt that is sent to an the LLM? I saw that this has come up before in this ...
1
vote
1
answer
60
views
What do I need to do in pydantic to support a FastAPI endpoint involving a sparse matrix?
I am aware of apparently similar questions, such as
Defining custom types in Pydantic v2
Pydantic v2 custom type validators with info
These questions do not cover my specific needs.
I need to make a ...
0
votes
2
answers
63
views
How to access model method in enumerate of list in Python?
I'm new to python and I've managed to populate a list with instances of my model.
# requisition.py
from pydantic import BaseModel
from app.schemas.job_information import JobInformation
class ...
1
vote
0
answers
317
views
Defining a type that is both a Protocol and a Pydantic BaseModel
I need to define a type that is both a Protocol and a BaseModel.
In detail:
The model Foo has a field data that can receive any model that has an id attribute ( let's call the type HasId).
class Foo(...
1
vote
1
answer
223
views
Unable to create a nested DefaultDict in a pydantic BaseModel
Consider:
#!/usr/bin/env -S uv run --script
# /// script
# dependencies = [ "pydantic>=2.10.5,<3" ]
# requires-python = ">=3.12,<3.13"
# ///
import pydantic
from ...
0
votes
0
answers
188
views
Error implementing MCP Python sandbox with asyncio on Windows: NotImplementedError
I am trying to implement an MCP Python Sandbox for my agent to run the Python scripts, but I am getting errors like this:
File "C:\\Users\\f\\anaconda3\\Lib\\asyncio\\base_events.py", line ...
0
votes
1
answer
128
views
How to match and populate a generic Pydantic model with deeply nested fields from similar but ref-inconsistent schemas?
I'm building a generalized Pydantic model (let's call it model X) that I want to use to match and extract values from multiple different JSON schemas (model A, B, C, etc.). These schemas are fetched ...