# Understanding Response Results

> This guide helps you interpret the `responses` array returned by SafeQuestionPoll, understand the meaning of each message type, and how to display them in your application.

## Overall Structure

The `responses` returned from polling is a message array that records, in chronological order, all output produced during the Agent's analysis. It is **a mixed list of incremental process messages and final results**.

A typical analysis produces the following message sequence:

```text
notify → message (knowledge retrieval) → message (execution process) → metric → code → echarts_plus → summary → finish
```

Not all types appear every time; this depends on the complexity of the question and the analysis path chosen by the Agent.

## Message Type Quick Reference

| Type | Should You Pay Attention | Description |
|------|:------------------------:|-------------|
| **summary** | Yes (required) | Final analysis summary, containing data interpretation and business insights |
| **metric** | Yes (recommended) | Metric calculation results, including DSL definitions |
| **echarts_plus** | Yes (recommended) | Chart data, can be used directly for rendering |
| **code** | Yes (recommended) | Generated code (usually SQL) |
| **message** | Depends | May contain knowledge details or execution logs |
| **notify** | Usually ignore | Progress hints, e.g., "Thinking" |
| **finish** | Status only | Marks the end of analysis |
| **finish_stop** | Status only | Marks user-initiated stop |
| **error** | Handle it | Execution error |

## Field Reading Rules

Business fields in each message may appear at different levels. Read in the following priority:

```text
1. response.fieldName        (top level)
2. response.modelRes.data.fieldName
3. JSON.parse(response.rawRes).data.fieldName
```

It is recommended to implement a unified function:

```python
def read_field(response, field_name):
    """Read the specified field from a response in priority order"""
    # Priority 1: top level
    if response.get(field_name):
        return response[field_name]
    # Priority 2: modelRes.data
    model_data = response.get("modelRes", {}).get("data", {})
    if model_data.get(field_name):
        return model_data[field_name]
    # Priority 3: rawRes
    raw_res = response.get("rawRes")
    if raw_res and isinstance(raw_res, str):
        try:
            parsed = json.loads(raw_res)
            if parsed.get("data", {}).get(field_name):
                return parsed["data"][field_name]
        except json.JSONDecodeError:
            pass
    return None
```

## Detailed Description and Display Recommendations by Type

### summary — Analysis Summary

**This is the most important message**, containing the final data insights and conclusions.

Key fields:
- `summaryData` — Summary text (Markdown format)
- If `summaryData` is empty, fall back to `message`

Display recommendation: Render directly as Markdown, supporting tables, bold, and other formatting.

Actual output example:

```text
**Beijing Second-hand Housing Total Transaction Amount by District in the Past 6 Years (2015-2021):**

- **Knowledge Retrieval**: Consulted knowledge base, confirmed "sales" in the dataset corresponds to transaction price
- **Metric Calculation**: Used the "Total Transaction Amount" metric

**District Rankings by Transaction Amount (unit: CNY 100 million):**

| Rank | District | Total Transaction Amount (CNY 100M) |
|------|----------|-------------------------------------|
| 1 | Chaoyang | 10349.27 |
| 2 | Haidian | 5850.22 |
| 3 | Fengtai | 3411.86 |
...
```

---

### metric — Metric Calculation Result

Generated when the Agent performs calculations through the metric engine.

Key fields:
- `message` — Metric name description
- `metricDsl` — Semantic layer DSL (JSON)
- `physicalMetricDsl` — Physical layer DSL (JSON)

Display recommendation: Show the metric name. For developer-facing views, DSL details can be collapsed.

Actual output example:

```text
message: Metric: Total Transaction Amount by District in the Past 6 Years

metricDsl:
{
  "metricId": { "metricType": "SQL_SIMPLE", "id": 631 },
  "name": "Total Transaction Amount by District in the Past 6 Years",
  "params": [
    { "name": "dims", "values": [{ "left": "region" }] },
    { "name": "filters", "values": [{ "exprItems": [...] }] }
  ],
  "metricDefinition": {
    "mainTable": "ns10.public.v_gpt_ns10_datagpt_buildin_beijing_house_transaction",
    "calculationLogic": "SUM(`transaction_price`)"
  }
}
```

---

### echarts_plus — Chart Data

Visualization chart configuration generated by the Agent.

Key fields:
- `message` — Chart title
- `chartType` — Chart type (e.g., ECHARTS)
- `columns` — Column definitions
- `calculateSql` — SQL used to retrieve chart data

Display recommendation: Use the `calculateSql` query results with `chartType` for frontend rendering.

Actual output example:

```text
message: Beijing Second-hand Housing Total Transaction Amount by District in the Past 6 Years (2015-2021)
chartType: ECHARTS
columns: District (STRING), Total Transaction Amount (10K CNY) (LONG)
calculateSql:
SELECT region AS district, SUM(transaction_price) AS total_transaction_amount
FROM ns10.public.v_gpt_ns10_datagpt_buildin_beijing_house_transaction
WHERE transaction_date >= '2015.01.01' AND transaction_date <= '2021.01.09'
GROUP BY region ORDER BY total_transaction_amount DESC
```

---

### code — Code Block

Code generated by the Agent, usually SQL.

Key fields:
- `codeType` — Code language (e.g., `sql`)
- `code` — Code content

Actual output example:

```text
codeType: sql
code:
SELECT
  region AS district,
  SUM(transaction_price) AS total_transaction_amount
FROM ns10.public.v_gpt_ns10_datagpt_buildin_beijing_house_transaction
WHERE transaction_date >= '2015.01.01' AND transaction_date <= '2021.01.09'
GROUP BY region
ORDER BY total_transaction_amount DESC
```

---

### message — General Message

This is a "catch-all" type that may contain various content. The content should be further evaluated based on its context.

#### Contains Knowledge Details

When the message contains `knowledgeData.detailItems`, or the text includes `Knowledge details:` or `Viewed knowledge details:`, it represents knowledge retrieval results.

Display recommendation: Extract and display the knowledge entries to help users understand which business rules the Agent referenced.

Actual output example:

```text
source: get_knowledge_detail
items:
- id=51, keys=Beijing Second-hand Housing 10-year Transaction Data, value={"desc": "If no time is explicitly specified in the question, use yesterday"}, type=TEXT
- id=52, keys=Beijing Second-hand Housing 10-year Transaction Data 2, value={"desc":"The answer must include a time range"}, type=TEXT
```

#### Contains Execution Process

When the text contains `Executing metric calculation:` or similar text, it represents metric execution logs.

Display recommendation: Show in developer-facing debugging interfaces; hide from business users.

---

### notify — Progress Notification

Messages such as "Thinking next step" or "Searching knowledge base".

Display recommendation: Can be used to show status text in a loading animation, or ignored entirely.

---

### error — Error

An exception occurred during analysis.

Display recommendation: Show the error message to the user and suggest retrying or rephrasing the question.

## Recommended Display Priority

If you only need to show core results to end users, filter and display in the following order:

1. **summary** — Primary display content
2. **echarts_plus** — Paired with chart rendering
3. **code** — SQL view (collapsible)
4. **metric** — Metric details (collapsible)
5. **message (knowledge type)** — Referenced knowledge (collapsible)

Other types need not be shown to end users.

## Real Complete Output Example

The following is the key returned messages from a real Q&A session ("Beijing second-hand housing sales over the past 6 years, by district"):

```text
[response#61] type=knowledge
Knowledge retrieval: consulted 2 business rules
- Rule 1: If no time is explicitly specified in the question, use yesterday
- Rule 2: The answer must include a time range

[response#93] type=execution log
Executing metric calculation: Total transaction amount by district in the past 6 years (Metric ID: 631)

[response#95] type=metric
Metric result: Total transaction amount by district in the past 6 years
Contains metricDsl and physicalMetricDsl

[response#99] type=code
SQL: SELECT region AS district, SUM(transaction_price) AS total_transaction_amount FROM ... GROUP BY region

[response#101] type=summary
Complete analysis summary including district ranking table and key findings

[response#103] type=finish
Analysis complete
```

## Next Steps

- Return to [API Overview](open-api-overview) to view the interface list
- View the complete parameter definitions for [SafeQuestionPoll](open-api-safe-question-poll)
