跳到正文
DEV Community· Hernan Chilabert·· 1 小時前AI 評分49

構建 AI SQL 助手第 1 天:只呼叫 LLM 的收穫

Day 1 of Building an AI SQL Assistant: What I Learned Just Calling the LLM

AI 導讀

作者在構建 AI SQL 助手的第 1 天,以 FastAPI、AsyncOpenAI 和本機 Ollama 上的 qwen3:4b 建立後端呼叫流程,並整理 Responses API 的相容邊界及輸出 token 預算。

正文

I'm building a small AI SQL assistant to learn text-to-SQL properly. The final idea: you ask a question in plain English, and it becomes a query that is safe to run against Postgres (or another engine).

But there is no SQL yet. Day 1 was only about one thing: calling an LLM from a backend and understanding what comes back. I thought it would be a quick setup day. It wasn't, and I learned more than I expected.

This is my learning log, not a tutorial. If something here is wrong, please tell me in the comments.

What I built

A tiny FastAPI app with one endpoint, POST /api/chat:

FastAPI (app/api/chat.py)
   ↓
LLMService (app/services/llm.py)
   ↓
AsyncOpenAI client → Responses API
   ↓
Ollama on localhost, running qwen3:4b
  • FastAPI validates the body against a Pydantic ChatRequest before my code runs (the message must be 1 to 4000 characters).
  • LLMService creates the AsyncOpenAI client once, in __init__, not on every request.
  • get_llm_service() is cached with @lru_cache, so every request reuses the same instance.
  • Each call goes through self._client.responses.create(...).

I use AsyncOpenAI because FastAPI runs on async/await. A sync HTTP client would block the event loop for the whole LLM call (seconds), and every other request on that worker would wait.

Each layer speaks its own language

One rule I kept: app/api/chat.py never imports anything from openai, and app/services/llm.py never raises HTTPException.

Why it matters:

  • If the service knew about HTTPException, it would depend on FastAPI. I couldn't reuse it from a CLI or another interface without dragging FastAPI along.
  • If the HTTP layer knew about openai.* errors, I'd have to touch it every time the provider changes.

So the service raises its own domain errors, and the HTTP layer maps them to status codes.

Why the OpenAI SDK can talk to Ollama

This surprised me a bit. The SDK is not hardcoded to OpenAI. It builds HTTP requests with the shape of the Responses API and sends them to whatever base_url you give it:

LLM_BASE_URL=http://localhost:11434/v1/
LLM_MODEL=qwen3:4b

Point it to https://api.openai.com/v1 or to Ollama's endpoint, and as long as the server speaks the same contract, the SDK doesn't care who answers. (The SDK also requires an api_key, even if Ollama ignores it.)

So is it provider-agnostic?

Only at the protocol level. My business code doesn't change if I switch provider; only the config does (base_url, api_key, model). But the code assumes the response has the Responses API shape: output_text, usage.input_tokens / output_tokens / total_tokens, status, incomplete_details.

A provider that only supports the older Chat Completions API (choices[0].message.content, prompt_tokens / completion_tokens) would break it. Not with a clean domain error, but with an unhandled exception. There is no adapter layer per provider, and that is fine for now. I just want to be honest about where the boundary is.

instructions vs input

  • instructions is the system-level framing. It is the same in every call, and I write it once.
  • input is the user's message for that specific request.

Keeping them separate means I can change the question without touching the assistant's behavior, and the other way around.

The output token budget is shared

The usage object has input_tokens (what I send), output_tokens (what the model generates) and total_tokens (the sum).

The part I didn't get at first: with a reasoning ("thinking") model like Qwen3, output_tokens also includes the hidden reasoning. And max_output_tokens limits only output_tokens. So the same budget is shared between reasoning you never see and the answer you do see.

That is why I made the cap configurable:

LLM_MAX_OUTPUT_TOKENS=1024

My first benchmark was measuring the cap

I wrote a small script that sends the same prompt N times and prints tokens and latency.

With max_output_tokens=500, all 5 runs returned exactly 500 output tokens. Every single one.

When I raised the cap to 1024, output went between 392 and 866 tokens depending on the run, and no run hit the limit.

So the first benchmark wasn't measuring the model at all. It was measuring my configured ceiling. The model never had room to finish its natural process (reasoning plus answer), so "always 500" was just the number I had set.

This also explains why identical calls differ: generation is non-deterministic, and how much the model reasons changes on each run. Same prompt, different output_tokens, latency and content.

Empty vs truncated: same signal, two cases

When the model runs out of budget, the Responses API gives you two signals:

  • response.status == "incomplete"
  • response.incomplete_details.reason == "max_output_tokens"

But this can happen at two different moments.

Case 1: the budget runs out while the model is still reasoning. It never started the visible answer. output_text is empty, so I check response.output_text.strip(). There is nothing useful to show, so I raise a domain error and the API returns 502: the upstream provider answered in an invalid way. It's not 422, because the client's input was fine.

Case 2: the budget runs out after the model started answering. Same signal, but output_text has content, cut in the middle. For a chat answer, half a message can still be useful to a person. So here the API returns 200 OK with truncated: true.

The only difference between the two cases is whether output_text has content.

And here is the note I wrote for my future self: this rule won't work for SQL. A query cut in half is useless at best. At worst, it still runs, with a different meaning than the model wanted. So when I get to SQL generation, the same signal should be a hard error, not a flag.

Tests: fake the model, keep the real one out of CI

My API tests in tests/test_chat.py never call Ollama. With app.dependency_overrides, I swap get_llm_service for fake classes that expose the same interface (async generate(message) -> LLMResult) and return fixed results.

That way I test what my API does with each kind of model response (happy path, empty answer, provider errors, the 50x mappings) and the tests are fast, free and deterministic.

The real model only runs in two places: the benchmark script and manual curl experiments. They stay out of the automated suite for the same reason as above: a real model doesn't give the same output twice, so you can't write an exact assert against it. And they need Ollama running.

Where the security boundary is today

Honestly: almost nowhere yet. The only real validation is Pydantic on the input (1 to 4000 characters). There is no database, so nothing the model says gets executed. It's just text shown to the user.

That changes as soon as SQL appears, and that's the interesting part of this project.

What's next

Next I'm working on prompt and context engineering: giving the model explicit rules and the real schema as context, before asking it for any SQL.

How do you handle truncated LLM output in your backends? Retry, fail, or pass it through with a flag? I'd like to hear what worked for you.

來源:DEV Community · dev.to