> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pixeltable.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Application code puts a TableModel in app.py, then runs `pxt schema update app.py my_app` to create the tables and `pxt service update app.py my_app` to start HTTP. The last argument can be a Cloud URL such as `pxt://org:db`. Do not call pxt.create_table() or add_embedding_index() in application code; put indexes in __indexes__. Notebooks, tests, and the REPL do use pxt.create_table().
> Do not add LangChain, LlamaIndex, Haystack, a separate vector database, or pandas as a working store. Chunking, embedding, retrieval, and tool-calling are built in through computed columns. Use a computed column instead of a per-row loop that calls a model.
> Install with `pip install -U 'pixeltable[serve]'` on Python 3.11+. `pxt init` is a prerequisite for `pxt schema update`.
> For Pixeltable Cloud, point users to https://docs.pixeltable.com/cloud, which goes from `pxt login` to a running service.

# Extract fields from LLM JSON responses

[![Open in Kaggle](https://kaggle.com/static/images/open-in-kaggle.svg)](https://kaggle.com/kernels/welcome?src=https://github.com/pixeltable/pixeltable/blob/release/docs/release/howto/cookbooks/core/workflow-json-extraction.ipynb)  [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pixeltable/pixeltable/blob/release/docs/release/howto/cookbooks/core/workflow-json-extraction.ipynb)  [![Download Notebook](https://img.shields.io/badge/%E2%AC%87-Download%20Notebook-blue)](https://raw.githubusercontent.com/pixeltable/pixeltable/refs/tags/release/docs/release/howto/cookbooks/core/workflow-json-extraction.ipynb)

> [!TIP]
>
> This documentation page is also available as an interactive notebook. You can launch the notebook in
> Kaggle or Colab, or download it for use with an IDE or local Jupyter installation, by clicking one of the
> above links.

Parse and access specific fields from structured JSON responses returned
by language models.

## Problem

LLM APIs return nested JSON responses with metadata you don’t need. You
want to extract just the text content or specific fields for downstream
processing.

```json theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
{
  "id": "chatcmpl-123",
  "choices": [{
    "message": {
      "content": "This is the actual response text"  // ← You want this
    }
  }],
  "usage": {"tokens": 50}
}
```

## Solution

**What’s in this recipe:**

* Extract text content from chat completions
* Access nested JSON fields
* Create separate columns for different fields

You use JSON path notation to extract specific fields from API responses
and store them in computed columns.

### Setup

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
%pip install -qU pixeltable openai

import getpass
import os

if 'OPENAI_API_KEY' not in os.environ:
    os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key: ')
```

### Create prompts table

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
import pixeltable as pxt
from pixeltable.functions import openai

# Create a fresh directory
pxt.drop_dir('json_demo', force=True)
pxt.create_dir('json_demo')
```

<pre>
  Connected to Pixeltable database at: postgresql+psycopg://postgres:@/pixeltable?host=/Users/pjlb/.pixeltable/pgdata
  Created directory 'json\_demo'.
  \<pixeltable.catalog.dir.Dir at 0x313d7a150>
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t = pxt.create_table('json_demo/prompts', {'prompt': pxt.String})
```

<pre>
  Created table 'prompts'.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
t.insert(
    [
        {'prompt': 'What is the capital of France?'},
        {'prompt': 'Write a haiku about coding'},
    ]
)
```

<pre>
  Inserting rows into \`prompts\`: 2 rows \[00:00, 325.83 rows/s]
  Inserted 2 rows with 0 errors.
  2 rows inserted, 2 values computed.
</pre>

### Get LLM responses

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Add computed column for API response (returns full JSON)
t.add_computed_column(
    response=openai.chat_completions(
        messages=[{'role': 'user', 'content': t.prompt}],
        model='gpt-4o-mini',
    )
)
```

<pre>
  Added 2 column values with 0 errors.
  2 rows updated, 2 values computed.
</pre>

### Extract specific fields

Use dot notation to access nested JSON fields:

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# Extract just the text content
t.add_computed_column(text=t.response.choices[0].message.content)

# Extract token usage
t.add_computed_column(tokens=t.response.usage.total_tokens)
```

<pre>
  Added 2 column values with 0 errors.
  Added 2 column values with 0 errors.
  2 rows updated, 2 values computed.
</pre>

```python theme={"theme":{"light":"light-plus","dark":"dark-plus"}}
# View clean results
t.select(t.prompt, t.text, t.tokens).collect()
```

## Explanation

**Common extraction patterns:**

**Accessing JSON fields:**

* Use dot notation for object properties: `response.usage`
* Use brackets for array elements: `choices[0]`
* Chain them: `response.choices[0].message.content`

**Extracted columns are computed:**

Changes to the source data automatically update all extracted fields.

## See also

* [Configure API
  keys](https://docs.pixeltable.com/howto/cookbooks/core/workflow-api-keys.md)
* [Extract structured data from
  images](https://docs.pixeltable.com/howto/cookbooks/images/vision-structured-output.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.