File size: 6,468 Bytes
9ad4b87 c72f0a1 9ad4b87 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | """Database actions with separate read and write operations."""
import json
from core import external_tools
from . import legacy_action
GROUPING_EXAMPLE = {
"action": "query_database", "arguments": {
"database": "ut_odoo_order_lines", "fields": [],
"groupBy": ["pricelist"],
"aggregates": [{"fn": "count"}, {"fn": "sum", "field": "price_subtotal"}],
"limit": 2,
},
}
def query_guide(rows):
"""Explain query results and offer an example only with readable fields."""
lines = [
"## Grouping and paging", "",
"Use groupBy with 1 to 4 readable field keys. For calendar months, use an object with "
"field set to a readable date field's key and unit set to month. Grouping needs a connected database, "
"at least one aggregate and no sorts. Groups arrive in key order.",
"The top-level aggregates cover the whole permitted, filtered result, never one page. "
"Each groups entry has keys and aggregates for that entire group. "
"page.returned counts groups on the current page. records is empty for grouped queries. "
"A null group key means the field has no value. It remains a separate group and counts toward the total.",
"count without a field counts records. count with a field counts non-null values. "
"Other functions are count_distinct, sum, avg, min and max. sum and avg need numeric fields.",
"Use page.next_cursor as cursor with the same arguments to get the next page. "
"Stop when page.has_more is false. Do not add the repeated top-level aggregates across pages. "
"Connected database pages use one completed sync. If a sync completes between pages, "
"query_cursor_stale asks you to start again. Call query_database with error.retry_query "
"for a fresh first page. It keeps the original query and removes only cursor. "
"Discard earlier pages before collecting the new result. "
"query_cursor_invalid means the cursor cannot be read. Start again without cursor. "
"query_source_unavailable means the database is temporarily unavailable. Try the same query again shortly. "
"If the result or permissions change, start again without a cursor.",
"Limits: 500 rows or groups per page, default 100. At most 200 selected fields, "
"16 aggregates and 8 sorts. Filters allow 3 levels, 100 nodes and 50 conditions per group. "
"A sorted row query can hold at most 200,000 matching rows. Above that, narrow the filter "
"or omit sorts. Unsorted pages and aggregates can cover larger connected databases.", "",
]
args = GROUPING_EXAMPLE["arguments"]
visible = next((row for row in rows if row["database"] == args["database"]), {})
keys = {field.get("key") for field in visible.get("fields", [])}
if (visible.get("answerable") and visible.get("schema", {}).get("source_kind") == "mirror_user_table"
and {"pricelist", "price_subtotal"} <= keys):
lines += ["### Example: Odoo sales lines by pricelist", "",
"Call data with this JSON. It counts sales lines and sums their amounts using your current access.",
"```json", json.dumps(GROUPING_EXAMPLE, indent=2), "```",
"Collect every page. Add each group's count aggregate and compare it with the count in this ungrouped call:",
"```json", json.dumps({"action": "query_database", "arguments": {
"database": args["database"], "fields": [], "aggregates": args["aggregates"], "limit": 1,
}}, indent=2), "```",
"The grouped and ungrouped counts and sums must agree. A null pricelist is included."]
else:
lines += ["The Odoo grouping example needs access to Sales order lines and its Pricelist and Line $ fields. "
"This connection cannot currently use that example. Describe a listed database before choosing fields."]
return "\n".join(lines)
def _report_limitation(ctx, args):
"""Send an AI's bounded question to the team without changing tenant data."""
from routes_feedback import record_limitation
recorded = record_limitation(ctx.session, tool=args["tool"], action=args["action"],
code=args.get("code", "capability_unavailable"), question=args["question"])
return {"recorded": recorded}
def _operation_status(ctx, args):
"""Read the result of this connection's proposed change."""
from routes_external import _operation_status as read_status
return read_status(ctx.session, args)
GROUP = {
"name": "data", "title": "Data",
"guide": "List databases, read fields, group and page records, propose changes or report a limitation. Read loopable_guide(group='data') for actions and a grouping example.",
"actions": {
"operation_status": {
"read": True, "destructive": False, "confirm": False,
"schema": {"type": "object", "properties": {
"operation_id": {"type": "string", "pattern": "^[a-f0-9]{64}$"},
}, "required": ["operation_id"], "additionalProperties": False},
"handler": _operation_status,
},
"report_limitation": {
"read": True, "destructive": False, "confirm": False,
"schema": {"type": "object", "properties": {
"tool": {"type": "string", "minLength": 1, "maxLength": 100},
"action": {"type": "string", "minLength": 1, "maxLength": 100},
"code": {"type": "string", "maxLength": 100},
"question": {"type": "string", "minLength": 1, "maxLength": 500,
"description": "Your question in plain words. Omit records, cell values, filters and credentials."},
}, "required": ["tool", "action", "question"], "additionalProperties": False},
"handler": _report_limitation,
},
"list_databases": legacy_action("list_databases"),
"describe_database": legacy_action("describe_database"),
"query_database": legacy_action("query_database"),
**{"database." + action: legacy_action(
"database_object", action=action,
read=action in external_tools._OBJECT_READ_ACTIONS["database_object"],
destructive=action in {"record_delete", "field_delete"})
for action in external_tools._DATABASE_ACTIONS},
},
}
|