TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Show HN: GPT-JSON – Structured and typehinted GPT responses in Python

174 pointsby icyfoxabout 2 years ago
Hey HN, I&#x27;ve been using GPT a lot lately in some side projects around data generation and benchmarking. During the course of prompt tuning I ended up with a pretty complicated request: the value that I was looking for, an explanation, a criticism, etc. JSON was the most natural output format for this but results would often be broken, have wrong types, or contain missing fields.<p>There&#x27;s been some positive movement in this space, like with jsonformer (<a href="https:&#x2F;&#x2F;github.com&#x2F;1rgs&#x2F;jsonformer">https:&#x2F;&#x2F;github.com&#x2F;1rgs&#x2F;jsonformer</a>) the other day. But nothing that was plug and play with GPT.<p>This library consolidates the separate logic that I built across 5 different projects. It lets you prompt the model for how it should return fields, inject variable prompts, handle common formatting errors, then cast to pydantic when you&#x27;re done for typehinting and validation in your IDE. If you&#x27;re able to play around with it, let me know what you think.

24 comments

crazyedgarabout 2 years ago
I like the idea, but I think a library that focuses on producing requests and parsing responses according to schema is better. Sending requests to the server is orthogonal to the purpose.<p>What we&#x27;ve found useful in practice in dealing with similar problems:<p>- Use json5 instead of json when parsing. It allows trailing commas.<p>- Don&#x27;t let it respond in true&#x2F;false. Instead, ask it for a short sentence explaining whether it is true or false. Afterwards, use a small embedding model such as sbert to extract true&#x2F;false from the sentence. We&#x27;ve found that GPT is able to reason better in this case, and it is much more robust.<p>- For numerical scores, do a similar thing by asking GPT for a description, then with the small embedding model write a few examples matching your score scale, and for each response use the score of the best matched example. If you let GPT give you scores directly without explanation, 20% of the time it will give you nonsense.
评论 #35826593 未加载
评论 #35825127 未加载
评论 #35827750 未加载
评论 #35829222 未加载
评论 #35825364 未加载
评论 #35831779 未加载
评论 #35825587 未加载
wskishabout 2 years ago
Here&#x27;s 40 lines of python code that I&#x27;ve found to be unreasonably effective at accomplishing something similar:<p><a href="https:&#x2F;&#x2F;github.com&#x2F;jiggy-ai&#x2F;pydantic-chatcompletion&#x2F;blob&#x2F;master&#x2F;pydantic_chatcompletion&#x2F;__init__.py">https:&#x2F;&#x2F;github.com&#x2F;jiggy-ai&#x2F;pydantic-chatcompletion&#x2F;blob&#x2F;mas...</a>
评论 #35831626 未加载
评论 #35828214 未加载
评论 #35826254 未加载
评论 #35826566 未加载
评论 #35827645 未加载
btbuildemabout 2 years ago
I&#x27;ve been interfacing with GPT programmatically for a little while now, leveraging it&#x27;s &quot;soft and fuzzy&quot; interface to produce hard &#x2F; machine-readable results. JSON was the format that felt best-suited for the job.<p>I see a ton of code in this project, and I don&#x27;t know what most of it does. As far as GPT troubles with JSON, I&#x27;ll add a couple: sometimes it likes to throw comments in there as if it was JS. And sometimes it&#x27;ll triple-quote the JSON string as if it was Python.<p>My approach to solve these problems was via prompt engineering - using the system message part of the API call. Asking it to &quot;return valid json, do not wrap it in text, do not preface it with text, do not include follow-up explanations, make sure it&#x27;s valid json, do not include comments&quot; - seems to work 99% of the time. For the remainder, a try-and-catch block with some fallback code that &quot;extracts&quot; json (via dumb REs) from whatever text was returned. Hasn&#x27;t failed yet.<p>It&#x27;s fascinating to watch the new paradigm arrive, and people using old habits to deal with it. This entire project is kind of pointless, you can just ask GPT to return the right kind of thing.
评论 #35831209 未加载
评论 #35866752 未加载
评论 #35830954 未加载
mmaiaabout 2 years ago
I&#x27;m having success with simple YAML schema. One thing that&#x27;s very helpful for the prompt is to include &quot;description&quot; and &quot;example&quot;:<p><pre><code> - column name: salary_max format: number example: 150,000 description: Salary Maximum - column name: keywords format: string example: engineer, python, docker, remote description: Relevant Keywords (Comma separated keywords used for filtering and matching jobs to candidates)</code></pre>
评论 #35828941 未加载
评论 #35831795 未加载
olupabout 2 years ago
I built zod-chatgpt <a href="https:&#x2F;&#x2F;github.com&#x2F;olup&#x2F;zod-chatgpt">https:&#x2F;&#x2F;github.com&#x2F;olup&#x2F;zod-chatgpt</a> a couple of weeks ago to serve same purpose in typescript
评论 #35830894 未加载
teleforceabout 2 years ago
I asked ChatGPT (GPT-4) about the idea of integrating GPT-JSON with CUE language (<a href="https:&#x2F;&#x2F;cuelang.org&#x2F;" rel="nofollow">https:&#x2F;&#x2F;cuelang.org&#x2F;</a>) for potential improvements and the answers are quite impressive:<p>&quot;Yes, integrating the CUE language with GPT-JSON can potentially lead to improvements in its capability. CUE, short for Configuration, Unification, and Environment, is an open-source data constraint language designed to simplify the definition, generation, and validation of data in structured formats, like JSON, YAML, and others.<p>Integrating CUE with GPT-JSON can bring several benefits:<p>1) Validation: By using CUE, you can define schemas for the input and output JSON, which helps in validating the data structure and ensuring it adheres to the expected format. This can help reduce errors and improve the quality of the interaction with the GPT model.<p>2) Simplification: CUE can help simplify the process of defining and generating JSON inputs and outputs for GPT-JSON. By providing a more concise and expressive syntax, CUE can make it easier to craft structured inputs and outputs, which can be especially helpful when working with complex data structures.<p>3) Interoperability: Integrating CUE can improve the interoperability between GPT-JSON and other systems or applications. With CUE&#x27;s ability to work with multiple data formats (such as JSON, YAML, or HCL), it becomes easier to integrate GPT-JSON with various tools and platforms.<p>To integrate CUE with GPT-JSON, you would need to follow these general steps:<p>1) Define CUE schemas for the input and output JSON structures used by GPT-JSON.<p>2) Use the CUE language to validate and generate input JSON for GPT-JSON.<p>3) Process the output JSON generated by GPT-JSON using CUE to ensure it adheres to the defined schema and transform it as needed.<p>Integrating CUE with GPT-JSON can improve the overall robustness and ease of use of the library, making it more accessible and useful for a wider range of applications.&quot;
评论 #35830258 未加载
评论 #35826981 未加载
评论 #35831721 未加载
reissbakerabout 2 years ago
Hey, this is really neat! I&#x27;ve taken a very similar approach in TypeScript. +1 to the sibling comment that recommended parsing with json5 (but don&#x27;t tell the AI you&#x27;re doing that, it&#x27;s a waste of context space and it might get more confused anyway).<p>I&#x27;ve had luck doing chain-of-thought prompting in the JSON payload as you&#x27;ve described, too. Cheers, really validating to see someone taking a similar approach.
armcatabout 2 years ago
Have you considered Guardrails, <a href="https:&#x2F;&#x2F;shreyar.github.io&#x2F;guardrails&#x2F;" rel="nofollow">https:&#x2F;&#x2F;shreyar.github.io&#x2F;guardrails&#x2F;</a>, it’s like Pydantic but for LLMs?
killthebuddhaabout 2 years ago
In the last 24 hours I&#x27;ve seen a bunch of projects doing LLM -&gt; JSON. I think we want to be focusing on markdown instead. An intuition I have developed is that an ideal prompt has a very clear narrative structure and very tight &quot;semantic locality&quot; (the instruction is at the end, the most salient data is close to the instruction, etc).<p>JSON is admittedly way easier to work with up front, but markdown seems to be a more scaleable choice.<p>Of course, this is all very much an opinion and highly anecdotal at the moment.
pigcatabout 2 years ago
Since others are sharing their prompt-only solutions to get JSON, I&#x27;ll share what I&#x27;ve been using. Has been working reliably:<p>&quot;Do not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.<p>{<p><pre><code> &quot;author&quot;: &quot;string describing the author full name&quot;, &quot;year&quot;: &quot;number describing the year the book was written&quot;, &quot;isFiction&quot;: &quot;boolean describing if the book is a work of fiction&quot; ... </code></pre> } &quot;
robflahertyabout 2 years ago
Is there a reason we won’t have LLMs that only speak in JSON? These JSON hacks are clever and cool but feel like they’ll be obsolete in 6 weeks.
评论 #35831449 未加载
评论 #35830347 未加载
Loeffelmannabout 2 years ago
I Found that LLMs are pretty good with TOML. The multiline strings are also a real bonus. One thing I thought that was interesting is that sometimes the LLM will mistake the triple quoutes for the backticks so it will output something like this<p><pre><code> ``` [TOML] key=&quot;&quot;&quot; value &quot;&quot;&quot; &quot;&quot;&quot;</code></pre>
评论 #35830291 未加载
fswdabout 2 years ago
Ha, I just spent two hours hacking something up similar and I eventually just sent a system role with zod schema in the content
CupofChineseTeaabout 2 years ago
I happen to have a very similar idea recently and created this GPT-logic package for node. It basically transforms GPT generated results into JS data types. Check it out if you are interested. <a href="https:&#x2F;&#x2F;github.com&#x2F;wayneshn&#x2F;gpt-logic">https:&#x2F;&#x2F;github.com&#x2F;wayneshn&#x2F;gpt-logic</a>
knowsuchagencyabout 2 years ago
Nice project! I took some inspiration from this as well as <a href="https:&#x2F;&#x2F;github.com&#x2F;jiggy-ai&#x2F;pydantic-chatcompletion&#x2F;blob&#x2F;master&#x2F;pydantic_chatcompletion&#x2F;__init__.py">https:&#x2F;&#x2F;github.com&#x2F;jiggy-ai&#x2F;pydantic-chatcompletion&#x2F;blob&#x2F;mas...</a> to create the following:<p><a href="https:&#x2F;&#x2F;github.com&#x2F;knowsuchagency&#x2F;struct-gpt">https:&#x2F;&#x2F;github.com&#x2F;knowsuchagency&#x2F;struct-gpt</a><p>I tried to make the API as intuitive as possible and added the ability to provide examples to improve the reliability and quality of the LLM&#x27;s output.
lharriesabout 2 years ago
Langchain also has a built in Pydantic output parser <a href="https:&#x2F;&#x2F;python.langchain.com&#x2F;en&#x2F;latest&#x2F;modules&#x2F;prompts&#x2F;output_parsers&#x2F;examples&#x2F;pydantic.html" rel="nofollow">https:&#x2F;&#x2F;python.langchain.com&#x2F;en&#x2F;latest&#x2F;modules&#x2F;prompts&#x2F;outpu...</a><p>However I&#x27;ve found it to be generally unreliable and adds a lot of text to each call.<p>I suspect this can be improved by: - Only writing the parts of the spec which are needed, rather than the full JSON schema spec - Including relevant examples rather than arbitrary JSON schema examples
m3kw9about 2 years ago
Wasn’t there a yesterday proj that asks gpt to output non json but then it turns it into json after? Thus making it less prone to json errors
评论 #35825122 未加载
评论 #35825413 未加载
jumploopsabout 2 years ago
I built a toy[0] for Typescript that works similarly to this.<p>It takes the expected return type of a function, translates it into a JSON Schema, queries OpenAI, validates the response, and then magically returns the response as typed output.<p>[0]<a href="https:&#x2F;&#x2F;github.com&#x2F;jumploops&#x2F;magic">https:&#x2F;&#x2F;github.com&#x2F;jumploops&#x2F;magic</a>
senkoabout 2 years ago
I wait for the day someone fine-tunes an open model to always respond in JSON. I suspect it won&#x27;t be long now.
BiteCode_devabout 2 years ago
You can use simpler types. Instead of :<p><pre><code> messages=[ GPTMessage( role=GPTMessageRole.SYSTEM, content=SYSTEM_PROMPT, ), GPTMessage( role=GPTMessageRole.USER, content=&quot;Text: I love this product. It&#x27;s the best thing ever!&quot;, ) ] </code></pre> Try:<p><pre><code> messages=( (&quot;system&quot;, SYSTEM_PROMPT), (&quot;user&quot;, &quot;Text: I love this product. It&#x27;s the best thing ever!&quot;) ) </code></pre> Or:<p><pre><code> messages=( SystemMsg(SYSTEM_PROMPT), UserMsg(&quot;Text: I love this product. It&#x27;s the best thing ever!&quot;) ) </code></pre> This is still Python, not Java.
评论 #35830395 未加载
评论 #35826889 未加载
andrewstuartabout 2 years ago
Typed ChatGPT.<p>Someone had to come along and spoil the fun.<p>Next it&#x27;ll be ChatGPT&#x2F;XML.
评论 #35830295 未加载
KingOfCodersabout 2 years ago
Idiot question, I&#x27;d like to register and pay for the ChatGPT API but can&#x27;t find the link to get an API token :-)
评论 #35825726 未加载
评论 #35825724 未加载
AmazingTurtleabout 2 years ago
What about few shot learning, e.g. injecting 1 or 2 examples of JSON in the prompt? That should be fine as well
评论 #35831963 未加载
valyagolevabout 2 years ago
the dirtyjson library has been doing this work for me quite well