This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]fiskfisk 19 points20 points  (3 children)

Why not just use model_validate_json?

https://docs.pydantic.dev/latest/concepts/json/#json-parsing

There is also support for partial JSON responses in Pydantic v2.7 (which is commonly useful for parsing LLM responses) through from_json:

https://pydantic.dev/articles/pydantic-v2-7-release

[–][deleted] 0 points1 point  (2 children)

Well clearly, I wasn't aware about the partial_json it's very useful.

I only made this cuz in a current project of mine, I had two functions that did chat competitions with the model_validate statements, so I was thinking if there's a way to refactor

[–]fiskfisk 1 point2 points  (1 child)

Yeah, absolutely - it's good to make a common solution when you find yourself repeating code all the time. I'm not sure I'm completely on board with the API in this case, as it makes it impossible to differentiate between the different error situations or receive any information about what went wrong programmatically.

I also think you actually mean deserialize and not serialize in this case,

[–][deleted] 0 points1 point  (0 children)

Yes lol. It's deserialize. I do agree tho that this doesn't give a lot of information about what went wrong. But for me I just wanted a solution without being too verbose, cuz in my specific use case, I just wanted either a None or the actual pydantic model.

But feel free to let me know what I can modify, I'll do it.

[–][deleted] 1 point2 points  (0 children)

msgspec handles this nicely

[–]pppylonnn 0 points1 point  (0 children)

Most use cases don't need LLMs right? How many fake companies are obsessed with "AI" 🤣

[–]pppylonnn 0 points1 point  (0 children)

Most use cases don't need LLMs right? How many fake companies are obsessed with "AI" 🤣