"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge PR #1638: suggest real field refs for unknown call ids
Haozhe Wuecc02039c848
diff --cc agent/src/agent/context.pyindex 834747d3e,fc0730b38..1791cf563--- a/agent/src/agent/context.py+++ b/agent/src/agent/context.py@@@ -205,13 -197,9 +205,15 @@@ Decide which workflow to use based on tas `ref`: `data.tail_risk.var_95` or just `var_95` from `portfolio_risk_xray`,`historical_var` from `quantlib_call`. When more than one call returned thesame field, name the exact call as `call_id::field` (for example- `q1::historical_var`); a tool name is not a call id.+ `<call_id>::historical_var`), where `<call_id>` is the tool_call_id of that+ tool result copied verbatim; never invent a short alias. A tool name is not+ a call id.+ Each element of a list is its own field: address it by index,+ `call_id::data.positions[0].contribution_pct` (`positions.0.contribution_pct`+ is read the same way). A field name without the index does not select an+ element, and one element's ref never grounds another element's value.+ A ref that names a list or object (`data.groups.positive`) grounds nothing;+ end it at the numeric field of the element you quote.Once this session holds more than one tail-risk measurement (a VaR and an ES,or 95% and 99%), EVERY tail-risk figure needs that field ref — a call id or nodeclaration at all cannot say which of them you are quoting, and the figure isdiff --cc agent/src/agent/grounding/policies.pyindex 05cadac9b,a591324a3..6dcd848c9--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@@ -1083,152 -1090,64 +1086,198 @@@ class _PolicyMixinif not scope or not field:return []records, entries = self._field_sources(field, symbol)- refs = {- self._ref_source(record.call_id, record.field, record.scope)[1]- for record in records- if record.tool == scope and record.call_id and record.field- }- refs |= {- self._ref_source(str(entry.get("call_id")), str(entry.get("field")), None)[1]- for entry in entries- if entry.get("tool") == scope and entry.get("call_id") and entry.get("field")+ found: dict[str, list[float]] = {}+ for record in records:+ if record.tool == scope and record.call_id and record.field:+ found.setdefault(self._ref_source(record.call_id, record.field, record.scope)[1], []).append(+ float(record.value)+ )+ for entry in entries:+ if entry.get("tool") == scope and entry.get("call_id") and entry.get("field"):+ found.setdefault(self._ref_source(str(entry.get("call_id")), str(entry.get("field")), None)[1], []).append(+ float(entry["value"])+ )+ if figure is None:+ return sorted(found)+ recency = {item: index for index, item in enumerate(found)}+ ranked = sorted(+ found,+ key=lambda item: (+ not self._matches_evidence(figure, found[item], found[item]),+ -recency[item],+ item,+ ),+ )+ return ranked[:_MAX_CALL_REF_CANDIDATES]++ def _indexed_field_ref_candidates(+ self, ref: str, figure: Figure, symbol: str | None = None+ ) -> list[str]:+ """Exact ``call_id::path[i]`` refs for a ``call::field`` ref that selected no value.++ Two shapes of an unresolved ref are helped, both only from the call (or+ tool) the ref names:++ * the ref names a list field without its index: paths that equal the+ declared field once every collection index is dropped are offered;+ * the ref names a container (``data.groups.positive``): its numeric+ descendants that hold the figure's value are offered, and none+ otherwise. An index written in the ref narrows the container to that+ element.++ Refs whose value matches the figure come first. These are hints for the+ next draft; a ref is never resolved through them and a container ref+ authorizes nothing.+ """+ found: dict[str, float] = {}+ containers: set[str] = set()+ for key in (part.strip() for part in re.split(r"[;,]", ref or "")):+ if "::" not in key:+ continue+ scope, field = (part.strip() for part in key.split("::", 1))+ if not scope or not field:+ continue+ wanted = _index_normalized(field)+ bare = _INDEX_RE.sub("", wanted)+ below = re.compile(r"(?:^|\.)" + re.escape(wanted) + r"(?=[.\[])")+ for call_id, tool, path, value, record in (+ *(+ (r.call_id, r.tool, r.field, r.value, r)+ for r in self._evidence+ if r.status == "observed"+ ),+ *(+ (e.get("call_id"), e.get("tool"), e.get("field"), e.get("value"), None)+ for e in self._analysis_metrics+ ),+ ):+ if not (+ call_id+ and isinstance(path, str)+ and value is not None+ and scope in (call_id, tool)+ ):+ continue+ if record is not None:+ if symbol and record.symbol and record.symbol != symbol:+ continue+ if not self._kind_fits(record, figure):+ continue+ item = f"{call_id}::{path}"+ if below.search(_index_normalized(path)):+ containers.add(item)+ found[item] = float(value)+ elif _INDEX_RE.search(path) and not _INDEX_RE.search(wanted):+ stripped = _INDEX_RE.sub("", path)+ if stripped == bare or stripped.endswith("." + bare):+ found[item] = float(value)+ matches = {+ item: self._matches_evidence(figure, [value], [value])+ for item, value in found.items()}- return sorted(refs)+ # A container is answered only by the leaf that holds the figure.+ kept = [item for item in found if item not in containers or matches[item]]+ ranked = sorted(kept, key=lambda item: (not matches[item], item))+ cap = _MAX_CONTAINER_REF_CANDIDATES if containers else _MAX_INDEXED_REF_CANDIDATES+ return ranked[:cap]++ def _other_call_field_ref_candidates(+ self, ref: str, symbol: str | None, figure: Figure+ ) -> list[str]:+ """Same-field refs from other calls of the tool whose value matches ``figure``.++ A ``call_id::field`` ref that does not hold the figure may still name the+ right field of the wrong call (scope or period). Only calls of the same+ tool as the declared call, whose value for that field matches, are+ offered, most recent first. A hint only: the declared ref stays rejected+ and the next draft must name the exact ref itself.+ """+ found: dict[str, None] = {}+ for key in (part.strip() for part in re.split(r"[;,]", ref or "")):+ if "::" not in key:+ continue+ scope, field = (part.strip() for part in key.split("::", 1))+ tools = {r.tool for r in self._evidence if r.call_id == scope}+ tools |= {e.get("tool") for e in self._analysis_metrics if e.get("call_id") == scope}+ if not scope or not field or not tools:+ continue+ records, entries = self._field_sources(field, symbol)+ for call_id, tool, path, value, record in (+ *((r.call_id, r.tool, r.field, r.value, r) for r in records),+ *((e.get("call_id"), e.get("tool"), e.get("field"), e.get("value"), None) for e in entries),+ ):+ if (+ call_id+ and call_id != scope+ and tool in tools+ and isinstance(path, str)+ and (record is None or self._kind_fits(record, figure))+ and self._matches_evidence(figure, [float(value)], [float(value)])+ ):+ found[f"{call_id}::{path}"] = None+ return list(reversed(found))[:_MAX_CALL_REF_CANDIDATES]++ @staticmethod+ def _kind_fits(record: EvidenceRecord, figure: Figure) -> bool:+ """Whether a record is of the kind ``figure`` can be grounded in.++ Mirrors the narrowing ``_referenced`` applies, so a hint never points at+ a leaf the next draft would still be rejected for.+ """+ if figure.column and record.field != figure.column:+ return False+ if figure.percent:+ return not _is_price_kind(record) and not _is_metadata_count_leaf(record.field)+ if figure.currency:+ return _is_price_kind(record)+ return True+ def _unknown_call_field_ref_candidates(+ self, ref: str, symbol: str | None, figure: Figure+ ) -> list[str]:+ """Exact ``call_id::path`` refs for a ``scope::field`` whose scope names nothing.++ A model that writes an alias (``p1::field``) instead of the call id it+ was given names no call, tool or run of this session, so the ref selects+ no evidence. This only lists where the field really lives, so the next+ draft can copy an exact ref; it grants nothing, and the figure stays+ rejected until it is re-declared with one of them. Refs whose value the+ figure matches come first; at most :data:`_MAX_FIELD_REF_CANDIDATES` are+ returned.+ """+ key = (ref or "").strip()+ if "::" not in key:+ return []+ scope, field = (part.strip() for part in key.split("::", 1))+ if not scope or not field or self._names_session_source(scope):+ return []+ records, entries = self._field_sources(field, symbol)+ found: dict[str, list[float]] = {}+ for record in records:+ if record.call_id and record.field:+ label = self._ref_source(record.call_id, record.field, record.scope)[1]+ found.setdefault(label, []).append(float(record.value))+ for entry in entries:+ if entry.get("call_id") and entry.get("field"):+ label = self._ref_source(str(entry["call_id"]), str(entry["field"]), None)[1]+ found.setdefault(label, []).append(float(entry["value"]))+ money = bool(figure.currency and not figure.percent)+ compatible = {+ label+ for label, values in found.items()+ if self._matches_evidence(figure, values, [] if money else values)+ }+ ranked = sorted(found, key=lambda label: (label not in compatible, label))+ return ranked[:_MAX_FIELD_REF_CANDIDATES]++ def _names_session_source(self, name: str) -> bool:+ """Whether ``name`` is a call id, tool name or backtest run of this session."""+ return (+ any(name in (record.call_id, record.tool) for record in self._evidence)+ or any(name in (entry.get("call_id"), entry.get("tool")) for entry in self._analysis_metrics)+ or bool(self._artifact_scope(name))+ )+def _tail_risk_ref_required(self,figure: Figure,