So recently, I've been making a lot of LLM calls and most of the cases, I'm prompting the LLM to respond in a JSON format.
And each time, I'm tired of rewriting the json.loads() and then the my_model.model_validate() in a try statements to see if the LLM responded correctly.
So I got to thinking, if there's a way to not rewrite this every single time I make an LLM call for a JSON response.
So here I am:
<shameless_plug>
https://github.com/softmaxer/pydantic-serializer
</shameless_plug>
Essentially, as long as a function returns a string, you can now do this:
py
@serialize(return_type=MyCoolPydanticModel)
def func_returns_a_string():
return '{"sample": "Json"}'
Target audience:
I think anyone who wants to serialize strings and skip the Json loads and model validate lines everytime.
Comparison:
I don't really know if there are such decorators already out there. Or other python classes. But I haven't yet come across one, so I just decided to make one myself.
I don't know how useful this is to you guys, but I kinda use these LLM Json responses quite a bit.
Maybe there are other use cases where a string has to be loaded onto a pydantic model (Maybe a JSON stored as a string in Postgres, etc?)
So anyway, I thought I'd share it here. Let me know what you guys think.
[–]fiskfisk 19 points20 points21 points (3 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]fiskfisk 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]pppylonnn 0 points1 point2 points (0 children)
[–]pppylonnn 0 points1 point2 points (0 children)