# query-writing

Adopt this skill: https://proskills.md/skills/other/idun-group-idun-agent-platform-examples-tutorials-text-to-sql-deep-agent-skills

Page: https://proskills.md/skills/other/idun-group-idun-agent-platform-examples-tutorials-text-to-sql-deep-agent-skills
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: examples/tutorials/text-to-sql-deep-agent/skills/query-writing/SKILL.md
size: 2218
upstream: https://github.com/idun-group/idun-agent-platform/blob/main/examples/tutorials/text-to-sql-deep-agent/skills/query-writing/SKILL.md

````text
---
name: query-writing
description: Writes and executes SQL queries from simple SELECTs to complex multi-table JOINs, aggregations, and subqueries. Use when the user asks to query a database, write SQL, run a SELECT statement, retrieve data, filter records, or generate reports from database tables.
---

# Query Writing Skill

## Workflow for Simple Queries

For straightforward questions about a single table:

1. **Identify the table** - Which table has the data?
2. **Get the schema** - Use `sql_db_schema` to see columns
3. **Write the query** - SELECT relevant columns with WHERE/LIMIT/ORDER BY
4. **Execute** - Run with `sql_db_query`
5. **Format answer** - Present results clearly

## Workflow for Complex Queries

For questions requiring multiple tables:

### 1. Plan Your Approach
**Use `write_todos` to break down the task:**
- Identify all tables needed
- Map relationships (foreign keys)
- Plan JOIN structure
- Determine aggregations

### 2. Examine Schemas
Use `sql_db_schema` for EACH table to find join columns and needed fields.

### 3. Construct Query
- SELECT - Columns and aggregates
- FROM/JOIN - Connect tables on FK = PK
- WHERE - Filters before aggregation
- GROUP BY - All non-aggregate columns
- ORDER BY - Sort meaningfully
- LIMIT - Default 5 rows

### 4. Validate and Execute
Check all JOINs have conditions, GROUP BY is correct, then run query.

## Example: Revenue by Country
```sql
SELECT
    c.Country,
    ROUND(SUM(i.Total), 2) as TotalRevenue
FROM Invoice i
INNER JOIN Customer c ON i.CustomerId = c.CustomerId
GROUP BY c.Country
ORDER BY TotalRevenue DESC
LIMIT 5;
```

## Error Recovery

If a query fails or returns unexpected results:
1. **Empty results** — Verify column names and WHERE conditions against the schema; check for case sensitivity or NULL values
2. **Syntax error** — Re-examine JOINs, GROUP BY completeness, and alias references
3. **Timeout** — Add stricter WHERE filters or LIMIT to reduce result set, then refine

## Quality Guidelines

- Query only relevant columns (not SELECT *)
- Always apply LIMIT (5 default)
- Use table aliases for clarity
- For complex queries: use write_todos to plan
- Never use DML statements (INSERT, UPDATE, DELETE, DROP)
````

## File: README.md
upstream: https://github.com/idun-group/idun-agent-platform/blob/main/README.md

````text
<div align="center">

<img alt="Idun Agent Platform" src="docs/images/readme/banner.png">

<p>
  <strong>English</strong> | <a href="docs/readme/README.fr.md">Français</a> | <a href="docs/readme/README.es.md">Español</a> | <a href="docs/readme/README.zh.md">中文</a> | <a href="docs/readme/README.ar.md">العربية</a>
</p>

<br/>

### Productionize LangGraph & ADK agents.

Self-hosted. Open source. No vendor lock-in.

<br/>

[![License: GPLv3](https://img.shields.io/badge/License-GPLv3-purple.svg)](https://www.gnu.org/licenses/gpl-3.0.html)
[![CI](https://github.com/Idun-Group/idun-agent-platform/actions/workflows/ci.yml/badge.svg)](https://github.com/Idun-Group/idun-agent-platform/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/idun-agent-engine?color=purple)](https://pypi.org/project/idun-agent-engine/)
[![Discord](https://img.shields.io/badge/Discord-Join%20Us-purple?logo=discord&logoColor=white)](https://discord.gg/KCZ6nW2jQe)
[![Stars](https://img.shields.io/github/stars/Idun-Group/idun-agent-platform?style=social)](https://github.com/Idun-Group/idun-agent-platform)
[![Commits](https://img.shields.io/github/commit-activity/m/Idun-Group/idun-agent-platform?color=purple)](https://github.com/Idun-Group/idun-agent-platform)

<br/>

[Cloud](https://cloud.idunplatform.com) · [Try the demos](https://idun-group.com/demo) · [Quickstart](https://docs.idun-group.com/quickstart) · [Docs](https://docs.idun-group.com) · [Discord](https://discord.gg/KCZ6nW2jQe) · [Book a demo](https://calendar.app.google/RSzm7EM5VZY8xVnN9)

⭐ If you find this useful, please star the repo. It helps others discover the project.

</div>

<br/>

<p align="center">Idun Agent Platform is an open-source, self-hosted production wrapper for <b>LangGraph</b> and <b>Google ADK</b> agents. <code>pip install idun-agent-engine</code> and your agent runs as a FastAPI process with built-in chat UI, admin panel, traces, observability, guardrails, memory persistence, MCP tool governance, and prompt management.</p>

<p align="center">
  <img src="docs/images/readme/demo.webp" alt="Idun Agent Platform demo" width="100%"/>
</p>

> **Why Idun?** Teams building agents face a tradeoff: build the production wrapper yourself (FastAPI + traces + guardrails + admin UI — slow), or adopt a SaaS like LangGraph Cloud or LangSmith (sovereignty trade-off). Idun is the third path: pip install a self-sufficient FastAPI process that bundles your agent with chat UI, admin, traces, and guardrails — all open source, all on your infrastructure.

---

## Quick start

> **Prerequisites**: Python 3.12 or 3.13.

Create a new directory and install the engine:

```bash
mkdir my-agent && cd my-agent
pip install idun-agent-engine langgraph langchain-google-genai
```

Save the three files below inside `my-agent/`.

**`my-agent/agent.py`**

```python
from typing import Annotated, TypedDict

from idun_agent_engine.mcp import get_langchain_tools_sync
from langchain_google_genai import ChatGoogleGenerativeAI
from langgraph.graph import StateGraph, START
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition

class State(TypedDict):
    messages: Annotated[list, add_messages]

tools = get_langchain_tools_sync()
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash").bind_tools(tools)

def chatbot(state: State):
    return {"messages": [llm.invoke(state["messages"])]}

graph = StateGraph(State)
graph.add_node("chatbot", chatbot)
graph.add_node("tools", ToolNode(tools))
graph.add_edge(START, "chatbot")
graph.add_conditional_edges("chatbot", tools_condition)
graph.add_edge("tools", "chatbot")
```

**`my-agent/config.yaml`**

```yaml
server:
  api:
    port: 8000

agent:
  type: LANGGRAPH
  config:
    name: "my-agent"
    graph_definition: "./agent.py:graph"
    checkpointer:
      type: sqlite
      db_url: "sqlite:///conversations.db"

mcp_servers:
  - name: idun-docs
    transport: streamable_http
    url: https://docs.idun-group.com/mcp
```

**`my-agent/.env`** — get a Gemini key at [aistudio.google.com/apikey](https://aistudio.google.com/apikey):

```
GEMINI_API_KEY=your-key-here
```

From inside `my-agent/`, run:

```bash
idun init
```

> `graph_definition: "./agent.py:graph"` is resolved against the directory where you run `idun init`. Stay inside `my-agent/` when you launch it, or use an absolute path.

A browser opens at [http://localhost:8000](http://localhost:8000) for the chat UI. The agent already has tools from the Idun docs MCP wired in. Visit [/admin](http://localhost:8000/admin) to configure more MCP servers, managed prompts, guardrails, observability, messaging integrations, and SSO. Visit [/admin/traces](http://localhost:8000/admin/traces) for the trace store.

<p align="center">
  <img src="docs/images/readme/welcome-ui.png" alt="Idun Agent chat UI welcome screen" width="100%"/>
</p>

<p align="center">
  <img src="docs/images/readme/chat-mcp.png" alt="Chat answering an MCP-backed question with tool-call reasoning" width="100%"/>
</p>

> **What `pip install idun-agent-engine` delivers**
>
> A single wheel that bundles three Python packages:
>
> - **`idun_agent_engine`** — the engine SDK (FastAPI app factory, MCP registry, observability, guardrails).
> - **`idun_agent_standalone`** — the `idun` CLI, the admin REST API, and the chat / admin / traces UIs.
> - **`idun_agent_schema`** — the Pydantic config schemas.
>
> The `idun` command on your `$PATH` (`setup`, `serve`, `init`, `hash-password`, `agent serve`) is provided by the bundled standalone — it is not a separately published package. You won't see `idun-agent-standalone` in the engine's declared PyPI dependencies because it ships co-installed inside the wheel, not as a transitive dep.
>
> See [docs.idun-group.com/architecture](https://docs.idun-group.com/architecture) for the full layering.

## What's inside

<table>
<tr>
<td width="50%" valign="top">

### Observability

Langfuse · Arize Phoenix · LangSmith · GCP Trace · GCP Logging

Trace every agent run. Connect multiple providers at the same time through config.

<img src="docs/images/readme/observability.png" alt="Observability" width="100%"/>

</td>
<td width="50%" valign="top">

### Guardrails

PII detection · Toxic language · Ban lists · Topic restriction · Bias checks · NSFW · 9 more

Apply policies per agent on input, output, or both. Powered by Guardrails AI.

<img src="docs/images/readme/guardrails.png" alt="Guardrails" width="100%"/>

</td>
</tr>
<tr>
<td width="50%" valign="top">

### MCP tool governance

Register MCP servers and control which tools each agent can access. Supports stdio, SSE, streamable HTTP, and WebSocket.

<img src="docs/images/readme/mcp.png" alt="MCP" width="100%"/>

</td>
<td width="50%" valign="top">

### Memory and persistence

PostgreSQL · SQLite · In-memory · Vertex AI · ADK Database

Conversations persist across restarts. Pick a backend per agent.

<img src="docs/images/readme/memory.png" alt="Memory" width="100%"/>

</td>
</tr>
<tr>
<td colspan="2" valign="top" align="center">

### Prompt management

Versioned templates with Jinja2 variables. Assign prompts to agents from the UI or API.

<img src="docs/images/readme/prompts.png" alt="Prompts" width="50%"/>

</td>
</tr>
</table>

> [!NOTE]
> **AG-UI streaming** — Every agent gets a standards-based streaming API, compatible with CopilotKit clients. Built-in chat playground for testing.

<p align="center">
  <img src="docs/images/readme/agent-detail.png" alt="Agent detail" width="100%"/>
</p>

---

## Architecture

Idun ships as one process: **`idun-agent-standalone`**. It bundles the engine SDK, a Next.js chat UI, an admin panel, and a traces viewer — your agent runs inside this process, configured from a YAML file and re-loaded live from the admin REST.

```mermaid
flowchart LR
  subgraph Idun["idun-agent-standalone (one process)"]
    direction TB
    UI["Chat UI / Admin / Traces"] --> ENG["Engine SDK"]
    ENG --> DB[(Postgres / SQLite)]
  end
  Users --
````
