sql field straight out and execute it. The example uses the OpenAI SDK pointed at the gateway, so the same code runs against any model.
The example uses an in-memory SQLite database so it runs as-is.
The assistant
How it works
- The schema forces the model to return a
sqlstring (plus its reasoning). With structured output you parse the response once and runout["sql"]directly, no regex. - Passing the live
schema(db)means the model writes queries against your real tables, not guessed ones. - The
reasoningfield is optional but useful: it gives you a plain-English explanation of why the query looks the way it does, which shows up on the call’s trace once you turn tracing on.
Make it more robust
- Retry on error. Catch SQLite exceptions, send the error message back as input, and ask for a corrected query.
- Read-only safety. Run the generated SQL against a read-only connection so a bad query can’t modify data.
- Score it. Add a score check that verifies the query ran and returned rows.
What’s next
Structured output
JSON Schema, enums, and field descriptions.
Streaming
Stream the query as it generates.
Checks
Score generated SQL automatically.