---
title: "User Preference Profiling: Automatically Extracting Entity Attributes to State"
date: "2026-12-03T08:32:03+07:00"
description: "Use output_key and EventActions.state_delta to extract user preferences into user:-scoped state, read them back with get_user_state, and personalize every future session without re-prompting."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-user-preference-profiling-state.jpg"
alt: "User preference attributes flowing from conversation events into a user-scoped state profile"
tags: ['google-adk', 'state', 'sessions', 'personalization', 'user-profile']
---

Somewhere around message three of a forty-message conversation, a user types "just give me the short version, I hate long answers." If that preference dies with the session, every new conversation starts by re-learning it — and the user notices. The fix is not memory search or a separate profile database: ADK already has a place designed exactly for "facts about this user that outlive one chat" — **`user:`-scoped session state**.

This post builds a preference-extraction pipeline: an agent that turns natural-language hints into typed attributes, written to `user:` keys through the two sanctioned write paths (`output_key` and `EventActions.state_delta`), read back with `get_user_state`, and injected into future instructions. Along the way we handle the one real trap: prefixed keys and `{key}` templating do not mix.

## Prerequisites

- ADK installed and a working `Runner` with a persistent `SessionService` (`Database` or `VertexAI` — `InMemory` loses user state on restart).
- Understanding of state prefixes from the state docs: none, `user:`, `app:`, `temp:`.
- A `LlmAgent` you have already run once.

## 1. Where a preference belongs: `user:` state

The prefix decides scope, and scope decides whether a preference survives the conversation it was learned in:

| Prefix | Scope | Example key | Survives new session? |
| --- | --- | --- | --- |
| *(none)* | Current session | `tone_used_last_turn` | No |
| `user:` | All sessions of one user in an app | `user:answer_length` | **Yes** |
| `app:` | Every user of the app | `app:brand_voice` | Yes (shared) |
| `temp:` | Current invocation only | `temp:raw_extraction` | No — discarded |

Two rules keep the profile honest:

1. **Serializable values only.** Strings, numbers, booleans, simple lists/dicts — the `SessionService` must save and reload them.
2. **Never mutate a fetched `Session` directly.** Writing `my_session.state[...] = ...` bypasses ADK's event tracking and can lose data. State always changes *through an event*.

## 2. Extracting preferences with `output_key`

The simplest extractor is an `LlmAgent` whose final text *is* the value. Set `output_key` to the `user:`-prefixed key and the agent's response lands in the event's `state_delta` automatically:

```python
from google.adk.agents import LlmAgent

extractor = LlmAgent(
    name="PreferenceExtractor",
    model="gemini-flash-latest",
    instruction=(
        "The user may have expressed a preference in this conversation "
        "(answer length, language, tone, format). If one is explicit, reply "
        "with ONLY its normalized value, e.g. 'concise', 'thai', 'bullet-points'. "
        "If none is expressed, reply with exactly: unknown"
    ),
    output_key="user:answer_length",  # prefix = user scope across sessions
)

# After a run, the final response is already in state under the prefixed key:
#   session.state["user:answer_length"] == "concise"
```

Behind the scenes the agent writes the response into `EventActions.state_delta`, and the `Runner` passes the event to `append_event`, which applies the delta — the same flow as any other state write. Filter out the `unknown` sentinel in your own logic if you do not want it overwriting a known value.

For multi-attribute updates, build the delta yourself:

```python
from google.adk.events import Event, EventActions

async def record_preferences(session, session_service, prefs: dict, ts: float):
    delta = {f"user:{k}": v for k, v in prefs.items()}
    delta["user:profile_updated_at"] = ts   # timestamps make conflicts diagnosable
    event = Event(
        invocation_id="inv_profile_update",
        author="system",
        actions=EventActions(state_delta=delta),
        timestamp=ts,
    )
    await session_service.append_event(session, event)
```

Both routes are equivalent — `output_key` is the shortcut for "the answer is the value", `state_delta` is the standard way for multi-key, non-string, or timestamped updates.

## 3. Reading the profile back: `get_user_state`

Before a session exists (login screen, onboarding), Python lets you read user-scoped keys directly — with the `user:` prefix stripped:

```python
profile = await session_service.get_user_state(app_name=APP_NAME, user_id=user_id)
# {"answer_length": "concise", "language": "thai", "profile_updated_at": 1764759123.0}
```

**The exception to remember:** `VertexAiSessionService` always raises `NotImplementedError`, because the Agent Runtime API does not expose user state independently of a session. There, enumerate with `list_sessions` and call `get_session` on each result to collect the prefixed keys yourself. Guard the call so local development and production behave the same:

```python
async def load_profile(session_service, app_name: str, user_id: str) -> dict:
    try:
        return await session_service.get_user_state(app_name=app_name, user_id=user_id)
    except NotImplementedError:          # VertexAiSessionService
        profile = {}
        listing = await session_service.list_sessions(app_name=app_name, user_id=user_id)
        for summary in listing.sessions:
            s = await session_service.get_session(
                app_name=app_name, user_id=user_id, session_id=summary.id
            )
            profile.update(
                {k[len("user:"):]: v for k, v in s.state.items()
                 if k.startswith("user:")}
            )
        return profile
```

## 4. Personalizing without re-prompting

Here is the trap: `{key}` templating in `LlmAgent` instructions matches **valid Python identifiers**, and `user:answer_length` contains a colon — so `{user:answer_length}` is not a placeholder ADK will substitute. Read the profile yourself and inject it through an `InstructionProvider`:

```python
from google.adk.agents import LlmAgent
from google.adk.agents.readonly_context import ReadonlyContext

def build_instruction(context: ReadonlyContext) -> str:
    state = context.state
    length = state.get("user:answer_length", "medium")
    language = state.get("user:language", "english")
    return (
        f"You are a helpful assistant. Answer in {language}, "
        f"and match this length preference: {length}. "
        "Use literal JSON braces carefully when needed."
    )

assistant = LlmAgent(
    name="PersonalAssistant",
    model="gemini-flash-latest",
    instruction=build_instruction,   # InstructionProvider — no state templating
)
```

For plain session-scoped keys the `{key}` / `{key?}` templating remains the cleaner route; reach for a provider only when the key is prefixed or the prompt contains literal braces.

## 5. Profiling choices compared

| Approach | Scope | Freshness | Cost | Verdict |
| --- | --- | --- | --- | --- |
| `user:` state + `output_key` | Per user, per app | Live — same session service | One agent turn, no extra infra | **Default choice** |
| `user:` state + explicit `state_delta` | Per user, per app | Live | Manual delta, full control | Multi-attribute writes |
| Memory (`add_session_to_memory` + search) | Cross-session knowledge | Needs explicit ingestion + retrieval | LLM extraction + search | Fuzzy recall, not typed attributes |
| External profile DB | Global | You own sync | Your schema, your migrations | Only when non-agent systems need it |

Keep attributes small and typed (`concise` vs `verbose`, not a paragraph of prose): profile values are read on every turn, so every extra token is paid repeatedly. Large or sensitive payloads belong in artifacts or a dedicated store, with only a reference kept in state.

## Checklist

- [ ] Preferences live under `user:` keys — never unprefixed keys that vanish with the session.
- [ ] All writes go through `output_key` or `EventActions.state_delta` + `append_event`, never a fetched `Session` object.
- [ ] Values are serializable and small (normalized enums over free-form paragraphs).
- [ ] An `unknown`/no-op path exists so a turn without a preference does not clobber a known value.
- [ ] `user:profile_updated_at` (or similar) is written so conflicts and staleness are diagnosable.
- [ ] Profile reads handle `NotImplementedError` from `VertexAiSessionService` with the `list_sessions` fallback.
- [ ] Personalization uses an `InstructionProvider` for prefixed keys instead of `{key}` templating.
- [ ] The `SessionService` is persistent — `InMemorySessionService` cannot hold a profile across restarts.

## Conclusion

A user preference is an entity attribute with a natural home: `user:`-scoped state, written as part of an event so it is tracked, persisted, and replayable. Extract with `output_key` when the response is the value, with an explicit `state_delta` when it is not; read back with `get_user_state` (and the `list_sessions` fallback on Vertex AI); inject via an `InstructionProvider` because prefixed keys are not identifiers. Do that and the user never has to say "just keep it short" twice.

## References

- https://adk.dev/sessions/state/
- https://adk.dev/sessions/session/
- https://adk.dev/events/
