Lesson 4 of 4 Retrieval-Augmented Generation in SQL

Extracting Language Model Responses

This lesson explains the response JSON structure and how to extract answers, structured output and usage data.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify the JSON paths for the answer, finish reason and token usage.
  • Explain how to parse structured output with OPENJSON.
  • Describe how to validate answers before returning them.

The response structure

@response contains a response object with the HTTP status and headers, and a result object with the body returned by the model. For chat completions, the paths in the following table are the most useful.

PathContains
$.response.status.http.codeThe HTTP status code
$.result.choices[0].message.contentThe answer text (or a JSON string with structured output)
$.result.choices[0].finish_reasonstop when complete; length when cut off by the token limit; content_filter when filtered
$.result.usage.prompt_tokens and completion_tokensToken counts for cost monitoring
$.result.data[0].embeddingThe vector, for embeddings requests
SELECT JSON_VALUE(@response, '$.response.status.http.code')       AS http_status,
       JSON_VALUE(@response, '$.result.choices[0].finish_reason') AS finish_reason,
       JSON_VALUE(@response, '$.result.usage.total_tokens')       AS total_tokens;

SELECT answer
FROM OPENJSON(@response, '$.result.choices[0].message')
     WITH (answer nvarchar(max) '$.content');

JSON_VALUE returns nvarchar(4000) and returns NULL in lax mode when the value is longer, so long answers are read with OPENJSON and an nvarchar(max) column, as in the example.

Match the pairs

Response paths

Exam skills 3.3.5

Match each value with its JSON path in @response.

Log in to try this activity Interactive activities are free with an account.

Structured output

When the request includes a response_format with a JSON schema, the content is a JSON string that follows the schema. A second OPENJSON parses it into typed columns, which can be returned, joined or inserted into tables, for example to store extracted attributes or classifications.

-- Request: 'response_format': {"type":"json_schema","json_schema":{"name":"recommendation","strict":true,
--   "schema":{"type":"object","properties":{"answer":{"type":"string"},
--             "product_ids":{"type":"array","items":{"type":"integer"}}},
--             "required":["answer","product_ids"],"additionalProperties":false}}}
DECLARE @content nvarchar(max) =
    (SELECT c FROM OPENJSON(@response, '$.result.choices[0].message') WITH (c nvarchar(max) '$.content'));

SELECT JSON_VALUE(@content, '$.answer') AS answer;
SELECT CAST(value AS int) AS ProductID
FROM OPENJSON(@content, '$.product_ids');
Scenario questions

Reading structured output

Exam skills 3.3.5

Choose how to read each part of a structured response.

Log in to try this activity Interactive activities are free with an account.

Validating and returning answers

Before using an answer, the procedure checks the HTTP status and the finish reason: length means the answer was truncated, so it should be retried with a higher token limit or less context, and content_filter means content safety blocked part of it. Cited IDs can be validated against the retrieved rows, so the application never shows a product that was not in the grounding data. Logging the question, retrieved IDs, token usage, latency and status in a table supports monitoring, cost tracking and evaluation.

Select all that apply

Before showing an answer

Exam skills 3.3.5

Identify the checks a RAG procedure should make before returning an answer.

Log in to try this activity Interactive activities are free with an account.
Worked example

Answers that end mid-sentence

Some answers returned by a RAG procedure stop mid-sentence. The HTTP status is 200 and no error is raised. What should the developer check, and how should the procedure react?

Read $.result.choices[0].finish_reason; a value of length means the answer hit max_completion_tokens. The procedure should treat it as incomplete and retry with a higher limit or fewer retrieved rows (or ask for a shorter answer in the system message). Also confirm the answer is read with OPENJSON and nvarchar(max), because JSON_VALUE would return NULL, not a partial sentence, for long values. Raising the HTTP timeout does not change the token limit.

Check yourself

What does a finish_reason of length mean?

Show answer

The answer was cut off by the token limit, so it is incomplete.

Exam Tips

Remember for the exam

  • Answer text: $.result.choices[0].message.content; status: $.response.status.http.code.
  • finish_reason length means truncated output.
  • Long values: OPENJSON with nvarchar(max), not JSON_VALUE.
  • Structured output: parse the content JSON with OPENJSON into typed columns.