Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(skill): Experience-based enhancement of skill distribution

chunbs_cbs080477cc9dba
diff --git a/jiuwenswarm/symphony/experience/cluster.py b/jiuwenswarm/symphony/experience/cluster.py
new file mode 100644
index 0000000000..4c1e742e3c
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/cluster.py
@@ -0,0 +1,181 @@
+"""
+Semantic clustering of execution traces.
+
+Groups traces first by skill set, then clusters queries within each group
+via FAISS K-Means (cosine distance).
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+
+import numpy as np
+
+from .embed import EmbeddingClient
+from .models import TraceRecord
+
+LOGGER = logging.getLogger(__name__)
+
+
+@dataclass
+class ClusteredQuery:
+ """One semantic cluster of traces."""
+
+ cluster_id: int
+ centroid_query: str
+ member_traces: list[TraceRecord]
+ success_traces: list[TraceRecord]
+ failure_traces: list[TraceRecord]
+
+
+def cluster_traces(
+ traces: list[TraceRecord],
+ embedder: EmbeddingClient,
+ min_cluster_size: int = 1,
+) -> list[ClusteredQuery]:
+ """Cluster traces: first by skill set, then by semantic similarity.
+
+ 1. Partition traces by their skill set (frozenset of skill_ids).
+ 2. Within each group, embed queries and cluster via FAISS K-Means.
+ 3. Split each semantic cluster into success / failure buckets.
+ """
+ if not traces:
+ return []
+
+ # Stage 1: group by skill set
+ skill_groups: dict[frozenset, list[TraceRecord]] = {}
+ for t in traces:
+ key = frozenset(t.skills) if t.skills else frozenset()
+ skill_groups.setdefault(key, []).append(t)
+
+ result: list[ClusteredQuery] = []
+ cluster_id_counter = 0
+
+ # Stage 2: semantic clustering within each skill group
+ for skill_key in sorted(skill_groups.keys(), key=lambda s: sorted(s)):
+ group_traces = skill_groups.get(skill_key, [])
+ if not group_traces:
+ continue
+ queries = [t.query for t in group_traces]
+ embeddings = embedder.embed_batch(queries)
+
+ # Use min_cluster_size=2 for FAISS so small groups still form clusters;
+ # the outer `min_cluster_size` parameter controls discarding, not FAISS.
+ labels = _faiss_cluster(
+ embeddings,
+ max_iterations=50,
+ min_cluster_size=min_cluster_size,
+ )
+
+ local_clusters: dict[int, list[int]] = {}
+ for i, label in enumerate(labels):
+ if label >= 0:
+ local_clusters.setdefault(label, []).append(i)
+
+ for _local_id in sorted(local_clusters.keys()):
+ indices = local_clusters.get(_local_id, [])
+ members = [group_traces[i] for i in indices]
+
+ # Filter clusters smaller than the configured min_cluster_size
+ if len(members) < min_cluster_size:
+ continue
+
+ cluster_query = populate_cluster(cluster_id_counter, embeddings, indices, members)
+ result.append(cluster_query)
+ cluster_id_counter += 1
+
+ return result
+
+
+def populate_cluster(
+ cluster_id_counter: int,
+ embeddings: list[list[float]],
+ indices: list[int],
+ members: list[TraceRecord],
+) -> ClusteredQuery:
+ success_traces = [t for t in members if t.success]
+ failure_traces = [t for t in members if not t.success]
+
+ # Find centroid: member whose embedding is closest to the group mean
+ member_embeddings = np.array(
+ [embeddings[i] for i in indices],
+ dtype=np.float32,
+ )
+ centroid = member_embeddings.mean(axis=0)
+ sims = member_embeddings @ centroid
+ centroid_idx = int(sims.argmax())
+ cluster_query = ClusteredQuery(
+ cluster_id=cluster_id_counter,
+ centroid_query=members[centroid_idx].query,
+ member_traces=members,
+ success_traces=success_traces,
+ failure_traces=failure_traces,
+ )
+ return cluster_query
+
+
+def _faiss_cluster(
+ embeddings: list[list[float]],
+ *,
+ n_clusters: int | None = None,
+ max_iterations: int = 50,
+ min_cluster_size: int = 2,
+) -> list[int]:
+ """Cluster embeddings using FAISS K-Means with cosine distance.
+
+ Returns list of cluster labels (-1 = noise / too-small cluster).
+ Falls back to all-in-one cluster if FAISS is unavailable.
+ """
+ n = len(embeddings)
+ if n == 0:
+ return []
+ if n < min_cluster_size:
+ return [-1] * n
+
+ try:
+ import faiss
+ except ImportError:
+ LOGGER.debug("FAISS not available, falling back to single-cluster")
+ return [0] * n
+
+ # Normalize vectors for inner-product = cosine similarity
+ arr = np.array(embeddings, dtype=np.float32)
+ norms = np.linalg.norm(arr, axis=1, keepdims=True)
+ norms[norms == 0] = 1.0
+ arr = arr / norms
+
+ # Auto-determine k: aim for clusters of 3-8 items
+ if n_clusters is None:
+ k = max(2, min(n // 3, n))
+ else:
+ k = max(2, min(n_clusters, n))
+ k = min(k, n)
+ if k < 2:
+ # Too few points for meaningful clustering — treat as single cluster
+ return [0] * n
+
+ # FAISS K-Means with cosine distance (via inner product on normalized vectors)
+ dim = arr.shape[1]
+ kmeans = faiss.Kmeans(
+ dim,
+ k,
+ niter=max_iterations,
+ verbose=False,
+ gpu=False,
+ spherical=True, # enforces cosine similarity
+ min_points_per_centroid=min_cluster_size,
+ seed=42,
+ )
+ kmeans.train(arr)
+ _, labels = kmeans.index.search(arr, 1)
+ labels = labels.flatten().tolist()
+
+ # Mark clusters smaller than min_cluster_size as noise (-1)
+ from collections import Counter
+ counts = Counter(labels)
+ final = [-1 if counts[x] < min_cluster_size else x for x in labels]
+ return final
+
+
+__all__ = ["ClusteredQuery", "cluster_traces"]
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/collector.py b/jiuwenswarm/symphony/experience/collector.py
new file mode 100644
index 0000000000..0b60c7c6fc
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/collector.py
@@ -0,0 +1,2 @@
+class ExperienceBaseBuilder:
+ pass
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/distiller.py b/jiuwenswarm/symphony/experience/distiller.py
new file mode 100644
index 0000000000..f61c1e2742
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/distiller.py
@@ -0,0 +1,262 @@
+"""LLM-based distillation of skill patterns from clustered traces."""
+
+from __future__ import annotations
+
+import json
+import logging
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from typing import Any
+
+from .cluster import ClusteredQuery
+from .models import DistilledPattern, TraceRecord
+
+LOGGER = logging.getLogger(__name__)
+
+_DISTILL_PATTERN_PROMPT = """\
+You are an expert at generalizing query patterns. Given a cluster of semantically similar successful queries and the skills used to handle them, produce a generalized query template that captures their common intent.
+
+Use bracketed placeholders like [Entity], [Attribute], [Player], etc. for variable parts. Keep the result close to the original queries — only replace specific entities/names/values that vary across the cluster. Do NOT over-generalize: preserve the original sentence structure and as much concrete wording as possible. For example, avoid patterns like "[Action] on my [Platform] feed [Details]" — keep it readable and natural.
+
+For Chinese queries, use Chinese placeholders: [人名], [地点], [日期], [事物], etc., and keep the rest of the sentence natural.
+
+---
+
+CLUSTER INFO:
+Cluster ID: {cluster_id}
+Representative Query: {centroid_query}
+
+SUCCESSFUL QUERIES:
+{member_queries}
+
+USED SKILLS IN THIS CLUSTER:
+{used_skills}
+
+---
+
+Guidelines for generalization:
+- For domain-specific skills (e.g., a weather skill for weather queries), keep domain-related entities concrete. Do NOT generalize them into placeholders like [City], [Date], etc. This preserves matching accuracy for future queries.
+- Only replace variable entities that are truly unrelated to the skill's domain.
+- The output should be a fluent, natural-sounding query template.
+
+Produce a JSON object with a single key "pattern_description" whose value is the generalized query template.
+
+Examples:
+- Input queries: "Find Messi's goal record", "Find Tom Brady's career stats"
+Used skills: web_search (search the web for information)
+Output: {{"pattern_description": "Find [Player]'s career statistics/records"}}
+- Input queries: "上海明天的天气", "北京下周的天气"
+Used skills: weather_api (查询天气)
+Output: {{"pattern_description": "[城市][时间]的天气"}}
+
+Output ONLY valid JSON. No markdown, no explanation.
+"""
+
+
+class TraceDistiller:
+ """Extract effective/ineffective skill patterns from clustered execution traces.
+
+ Usage::
+
+ distiller = TraceDistiller(
+ llm_client=llm,
+ llm_model="qwen3-32b",
+ skills_info=[{"name": "web_search", "description": "..."}],
+ max_workers=8,
+ )
+ patterns = distiller.run(clusters)
+ """
+
+ def __init__(
+ self,
+ llm_client: Any | None,
+ llm_model: str,
+ *,
+ skills_info: list[dict[str, str]] | None = None,
+ max_workers: int = 8,
+ max_success_examples: int = 20,
+ ) -> None:
+ self._llm_model = llm_model
+ if llm_client is not None and llm_model:
+ self._llm = llm_client
+ else:
+ self._llm = None
+ self._max_workers = max_workers
+ self._max_examples = max_success_examples
+
+ # Build skill name → description map
+ self._skills_by_name: dict[str, str] = {}
+ if skills_info:
+ for s in skills_info:
+ self._skills_by_name[s["name"]] = s.get("description", "")
+
+ def run(self, clusters: list[ClusteredQuery]) -> list[DistilledPattern]:
+ """Run distillation in parallel across clusters."""
+ results: list[DistilledPattern | None] = [None] * len(clusters)
+
+ with ThreadPoolExecutor(max_workers=self._max_workers) as executor:
+ future_to_idx: dict[Any, int] = {}
+ for i, cluster in enumerate(clusters):
+ LOGGER.info("TraceDistiller: submitting cluster %d (id=%d)", i, cluster.cluster_id)
+ future = executor.submit(self._distill_one, cluster)
+ future_to_idx[future] = i
+
+ for future in as_completed(future_to_idx):
+ idx = future_to_idx[future]
+ try:
+ results[idx] = future.result()
+ LOGGER.info("TraceDistiller: finished cluster %d", idx)
+ except Exception as exc:
+ LOGGER.error(
+ "TraceDistiller: failed cluster %d (id=%d): %s (type=%s, repr=%r)",
+ idx, clusters[idx].cluster_id, exc,
+ type(exc).__name__, exc,
+ )
+
+ return [r for r in results if r is not None]
+
+ def _distill_one(self, cluster: ClusteredQuery) -> DistilledPattern | None:
+ metrics = self._compute_metrics(cluster.success_traces, cluster.failure_traces)
+
+ success_queries = [t.query for t in cluster.success_traces]
+ used_skill_names = {
+ s for combo in metrics["effective_skills"] for s in combo
+ }
+
+ prompt = self._build_prompt(cluster, success_queries, used_skill_names)
+
+ pattern_description = ""
+ if self._llm and self._llm_model:
+ try:
+ response = self._llm.chat.completions.create(
+ model=self._llm_model,
+ messages=[
+ {
+ "role": "system",
+ "content": (
+ "You are an expert at generalizing query patterns. "
+ "Output only valid JSON."
+ ),
+ },
+ {"role": "user", "content": prompt},
+ ],
+ max_tokens=256,
+ stream=False,
+ )
+ content = response.choices[0].message.content
+ if content:
+ pattern_description = self._parse_response(content, cluster.cluster_id)
+ except Exception as exc:
+ LOGGER.debug(
+ "TraceDistiller: LLM call failed for cluster %d: %s",
+ cluster.cluster_id, exc,
+ )
+ else:
+ # No LLM available — use centroid query as the pattern
+ pattern_description = cluster.centroid_query
+ LOGGER.info(
+ "TraceDistiller: no LLM client, using centroid query as pattern for cluster %d",
+ cluster.cluster_id,
+ )
+
+ if not pattern_description:
+ return None
+
+ return DistilledPattern(
+ cluster_id=cluster.cluster_id,
+ pattern_description=pattern_description,
+ **metrics,
+ )
+
+ @staticmethod
+ def _compute_metrics(
+ success_traces: list[TraceRecord],
+ failure_traces: list[TraceRecord],
+ ) -> dict[str, Any]:
+ effective_skills_map: dict[tuple[str, ...], int] = {}
+ for t in success_traces:
+ key = tuple(sorted(t.skills))
+ effective_skills_map[key] = effective_skills_map.get(key, 0) + 1
+ effective_skills = [
+ list(k)
+ for k, _ in sorted(effective_skills_map.items(), key=lambda x: -x[1])
+ ]
+
+ ineffective_skills: list[dict[str, str | list[str]]] = []
+ seen: set[tuple[str, ...]] = set()
+ for t in failure_traces:
+ key = tuple(sorted(t.skills))
+ if key not in seen:
+ seen.add(key)
+ ineffective_skills.append(
+ {
+ "skills": list(key),
+ "reason": t.error_type or "unknown",
+ }
+ )
+
+ avg_success = 0.0
+ avg_failure = 0.0
+
+ total = len(success_traces) + len(failure_traces)
+ success_rate = len(success_traces) / total if total > 0 else 0.0
+
+ return {
+ "effective_skills": effective_skills,
+ "ineffective_skills": ineffective_skills,
+ "avg_token_cost_success": avg_success,
+ "avg_token_cost_failure": avg_failure,
+ "success_rate": success_rate,
+ "raw_trace_count": total,
+ }
+
+ def _build_prompt(
+ self,
+ cluster: ClusteredQuery,
+ success_queries: list[str],
+ used_skill_names: set[str] | None = None,
+ ) -> str:
+ queries_text = "\n".join(f"- {q!r}" for q in success_queries[: self._max_examples])
+ if not queries_text:
+ queries_text = " (no successful traces)"
+
+ skills_text = ""
+ if self._skills_by_name and used_skill_names:
+ lines = []
+ for name in sorted(used_skill_names):
+ desc = self._skills_by_name.get(name, "")
+ if desc:
+ lines.append(f"- {name}: {desc}")
+ else:
+ lines.append(f"- {name}")
+ if lines:
+ skills_text = "\n".join(lines)
+ if not skills_text:
+ skills_text = " (no skill descriptions available)"
+
+ return _DISTILL_PATTERN_PROMPT.format(
+ cluster_id=cluster.cluster_id,
+ centroid_query=cluster.centroid_query,
+ member_queries=queries_text,
+ used_skills=skills_text,
+ )
+
+ @staticmethod
+ def _parse_response(response: str, cluster_id: int) -> str:
+ raw = response.strip()
+ if raw.startswith("```"):
+ raw = raw.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
+ if raw.startswith("json"):
+ raw = raw[4:].strip()
+
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ LOGGER.error(
+ "TraceDistiller: failed to parse JSON for cluster %d", cluster_id
+ )
+ return ""
+
+ return data.get("pattern_description", "")
+
+
+__all__ = ["TraceDistiller"]
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/embed.py b/jiuwenswarm/symphony/experience/embed.py
new file mode 100644
index 0000000000..e227dd1fcd
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/embed.py
@@ -0,0 +1,10 @@
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+LOGGER = logging.getLogger(__name__)
+
+
+class EmbeddingClient:
+ pass
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/evaluator.py b/jiuwenswarm/symphony/experience/evaluator.py
new file mode 100644
index 0000000000..48416adbf0
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/evaluator.py
@@ -0,0 +1,56 @@
+"""LLM-based trace processor: judge whether the skills used in a trace were correctly selected."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any
+
+from .models import TraceRecord
+
+LOGGER = logging.getLogger(__name__)
+
+
+class TraceEvaluator:
+ """Judge whether the skills used in each TraceRecord were correctly selected via LLM.
+
+ When ``messages`` are available, uses an enhanced prompt that includes
+ the full interaction process and skill selection context. Otherwise, falls back
+ to the simple query+result prompt.
+
+ ``success=True`` means the skill selection was correct — these traces are
+ used to build experience patterns. ``success=False`` means the skills were
+ incorrectly chosen or the execution failed — these traces are excluded from
+ the experience bank.
+
+ Usage::
+
+ processor = TraceEvaluator(llm_client=openai_client, llm_model="qwen3-32b")
+ records = parse_session("session_abc")
+ processor.process(records)
+ # records[0].success / .error_type / .error_detail are now filled
+ """
+
+ def __init__(
+ self,
+ llm_client: Any | None = None,
+ llm_model: str = "",
+ ) -> None:
+ self._llm_model = str(llm_model or "").strip()
+ self._llm = llm_client if llm_client is not None else None
+
+ def process(self, records: list[TraceRecord]) -> list[TraceRecord]:
+ """Judge skill correctness for each record, skip those with empty skills, return a new processed list."""
+ result = []
+ for record in records:
+ if not record.skills:
+ continue
+ self._judge_one(record)
+ result.append(record)
+ return result
+
+ def _judge_one(self, record: TraceRecord) -> None:
+ pass
+
+
+__all__ = ["TraceEvaluator"]
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/models.py b/jiuwenswarm/symphony/experience/models.py
new file mode 100644
index 0000000000..c59cdb731e
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/models.py
@@ -0,0 +1,123 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+
+@dataclass
+class ExperienceItem:
+ """One entry in the experience base.
+
+ Each item represents a class of queries that map to one or more skills.
+ """
+
+ id: str
+ query_pattern: str = ""
+ query_examples: list[str] = field(default_factory=list)
+ skill_ids: list[str] = field(default_factory=list)
+ success_count: int = 1
+ embedding: list[float] = field(default_factory=list)
+ created_at: float = 0.0
+ last_hit_at: float = 0.0
+
+ def to_dict(self) -> dict:
+ return {
+ "id": self.id,
+ "query_pattern": self.query_pattern,
+ "query_examples": self.query_examples,
+ "skill_ids": self.skill_ids,
+ "success_count": self.success_count,
+ "created_at": self.created_at,
+ "last_hit_at": self.last_hit_at,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict) -> ExperienceItem:
+ return cls(
+ id=data["id"],
+ query_pattern=data.get("query_pattern", ""),
+ query_examples=list(data.get("query_examples", [])),
+ skill_ids=list(data.get("skill_ids", [])),
+ success_count=int(data.get("success_count", 1)),
+ embedding=list(data.get("embedding", [])),
+ created_at=float(data.get("created_at", 0.0)),
+ last_hit_at=float(data.get("last_hit_at", 0.0)),
+ )
+
+
+@dataclass
+class TraceRecord:
+ trace_id: str
+ query: str
+ skills: list[str] = field(default_factory=list)
+ messages: list[dict] = field(default_factory=list)
+ result: str = ""
+ error_type: str | None = None
+ error_detail: str | None = None
+ success: bool = False
+
+ def to_dict(self) -> dict:
+ return {
+ "trace_id": self.trace_id,
+ "query": self.query,
+ "skills": self.skills,
+ "messages": self.messages,
+ "result": self.result,
+ "error_type": self.error_type,
+ "error_detail": self.error_detail,
+ "success": self.success,
+ }
+
+ @classmethod
+ def from_dict(cls, data: dict) -> TraceRecord:
+ return cls(
+ trace_id=data["trace_id"],
+ query=data.get("query", ""),
+ skills=list(data.get("skills", [])),
+ messages=list(data.get("messages", [])),
+ result=data.get("result", ""),
+ error_type=data.get("error_type"),
+ error_detail=data.get("error_detail"),
+ success=bool(data.get("success", False)),
+ )
+
+
+@dataclass
+class DistilledPattern:
+ """Distilled knowledge pattern from one cluster."""
+
+ cluster_id: int
+ effective_skills: list[list[str]] = field(default_factory=list)
+ ineffective_skills: list[dict[str, str | list[str]]] = field(default_factory=list)
+ success_rate: float = 0.0
+ avg_token_cost_success: float = 0.0
+ avg_token_cost_failure: float = 0.0
+ raw_trace_count: int = 0
+ pattern_description: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ """Serialize to a JSON-serializable dict."""
+ return {
+ "cluster_id": self.cluster_id,
+ "effective_skills": self.effective_skills,
+ "ineffective_skills": self.ineffective_skills,
+ "success_rate": self.success_rate,
+ "avg_token_cost_success": self.avg_token_cost_success,
+ "avg_token_cost_failure": self.avg_token_cost_failure,
+ "raw_trace_count": self.raw_trace_count,
+ "pattern_description": self.pattern_description,
+ }
+
+ @classmethod
+ def from_dict(cls, d: dict) -> DistilledPattern:
+ """Deserialize from a dict."""
+ return cls(
+ cluster_id=d["cluster_id"],
+ effective_skills=list(d.get("effective_skills", [])),
+ ineffective_skills=list(d.get("ineffective_skills", [])),
+ success_rate=float(d.get("success_rate", 0.0)),
+ avg_token_cost_success=float(d.get("avg_token_cost_success", 0.0)),
+ avg_token_cost_failure=float(d.get("avg_token_cost_failure", 0.0)),
+ raw_trace_count=int(d.get("raw_trace_count", 0)),
+ pattern_description=str(d.get("pattern_description", "")),
+ )
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/trace/parser.py b/jiuwenswarm/symphony/experience/trace/parser.py
new file mode 100644
index 0000000000..7f566c5992
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/trace/parser.py
@@ -0,0 +1,239 @@
+"""Session trace parser for experience distillation."""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+
+from jiuwenswarm.common.utils import get_agent_sessions_dir
+
+from ..models import TraceRecord
+
+LOGGER = logging.getLogger(__name__)
+
+_SESSION_DIR = get_agent_sessions_dir()
+
+
+def list_session_ids() -> list[str]:
+ """Return all session IDs from the sessions directory, excluding heartbeat directories."""
+ if not _SESSION_DIR.exists() or not _SESSION_DIR.is_dir():
+ return []
+ return [
+ d.name
+ for d in _SESSION_DIR.iterdir()
+ if d.is_dir() and not d.name.startswith("heartbeat_")
+ ]
+
+
+def _read_json(path: Path) -> object | None:
+ if not path.exists():
+ return None
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ LOGGER.error("Failed to read trace file")
+ return None
+
+
+def _extract_text(content) -> str:
+ """Extract plain text from content which may be None, str, or a list of content blocks."""
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ texts = []
+ for block in content:
+ if isinstance(block, str):
+ texts.append(block)
+ elif isinstance(block, dict) and block.get("type") == "text":
+ texts.append(block.get("text", ""))
+ return "".join(texts)
+ return str(content)
+
+
+def _extract_skills_from_tool_call(tool_call: dict) -> list[str]:
+ """Extract skill names from a tool_call record.
+
+ Recognizes several patterns:
+ - ``skill_tool``: arguments contain ``skill_name``
+ - ``symphony_compose_score``: arguments contain ``candidate_skill_ids``
+ or the result's ``raw_output.plan.steps[].skill_id``
+ """
+ name = tool_call.get("name", "")
+ args_raw = tool_call.get("arguments", "{}")
+ try:
+ args = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
+ except json.JSONDecodeError:
+ args = {}
+
+ if name == "skill_tool":
+ skill_name = args.get("skill_name", "")
+ return [skill_name] if skill_name else []
+
+ if name == "symphony_compose_score":
+ # Primary: candidate_skill_ids from arguments
+ candidate_ids = args.get("candidate_skill_ids", [])
+ if isinstance(candidate_ids, list) and candidate_ids:
+ return [s for s in candidate_ids if isinstance(s, str) and s]
+ # Fallback: skill_ids from the result's raw_output.plan.steps
+ result_raw = tool_call.get("result")
+ raw_output = tool_call.get("raw_output")
+ # result may be a string representation of a dict
+ if raw_output is None and result_raw is not None:
+ if isinstance(result_raw, str):
+ try:
+ raw_output = json.loads(result_raw)
+ except json.JSONDecodeError:
+ # Python-style repr (single quotes); try ast.literal_eval
+ try:
+ import ast
+ raw_output = ast.literal_eval(result_raw)
+ except Exception:
+ raw_output = None
+ elif isinstance(result_raw, dict):
+ raw_output = result_raw
+ if isinstance(raw_output, dict):
+ plan = raw_output.get("plan")
+ if isinstance(plan, dict):
+ steps = plan.get("steps", [])
+ if isinstance(steps, list):
+ skill_ids = []
+ for step in steps:
+ if isinstance(step, dict):
+ sid = step.get("skill_id") or step.get("name")
+ if sid and isinstance(sid, str) and sid not in skill_ids:
+ skill_ids.append(sid)
+ if skill_ids:
+ return skill_ids
+
+ return []
+
+
+def _extract_skills_from_raw_output(raw_output: dict) -> list[str]:
+ """Extract skill names from a tool_result's raw_output.
+
+ Used for ``symphony_compose_score`` results where the plan.steps
+ contain the selected skill_ids.
+ """
+ skill_ids: list[str] = []
+ plan = raw_output.get("plan")
+ if isinstance(plan, dict):
+ steps = plan.get("steps", [])
+ if isinstance(steps, list):
+ for step in steps:
+ if isinstance(step, dict):
+ sid = step.get("skill_id") or step.get("name")
+ if sid and isinstance(sid, str) and sid not in skill_ids:
+ skill_ids.append(sid)
+ return skill_ids
+
+
+def parse_session(session_id: str) -> list[TraceRecord]:
+ """Parse a single session directory into TraceRecords.
+
+ Uses request_id as traceId. A new request_id indicates a new user query segment.
+ Skill names are extracted from ``skill_tool`` and ``symphony_compose_score`` calls.
+ """
+ session_dir = _SESSION_DIR / session_id
+ if not session_dir.is_dir():
+ return []
+
+ metadata = _read_json(session_dir / "metadata.json")
+ if metadata is None or not isinstance(metadata, dict):
+ return []
+
+ history_data = _read_json(session_dir / "history.json")
+ if history_data is None:
+ history_data = []
+ if not isinstance(history_data, list):
+ history_data = []
+
+ current_request_id = ""
+ query = ""
+ reasoning = ""
+ assistant_content = ""
+ skills = []
+ trace_records = []
+ messages = []
+
+ def _flush_record():
+ # Commit accumulated assistant_content/reasoning before flushing
+ if assistant_content:
+ messages.append({"role": "assistant", "content": assistant_content, "reasoning": reasoning})
+ if not query or not current_request_id:
+ return
+ # result from the last assistant message, not tool result
+ result = ""
+ for msg in reversed(messages):
+ if msg.get("role") == "assistant":
+ result = _extract_text(msg.get("content", ""))
+ break
+ trace_records.append(TraceRecord(
+ trace_id=current_request_id,
+ query=query,
+ skills=skills,
+ messages=messages,
+ result=result,
+ ))
+
+ for record in history_data:
+ if not isinstance(record, dict):
+ continue
+ request_id = record.get("request_id", "")
+ if request_id and request_id != current_request_id:
+ _flush_record()
+ current_request_id = request_id
+ query = ""
+ messages = []
+ skills = []
+ reasoning = ""
+ assistant_content = ""
+ if record.get("role") == "user":
+ query = _extract_text(record.get("content")).strip()
+ elif record.get("role") == "assistant":
+ event_type = record.get("event_type", "")
+ if event_type == "chat.reasoning":
+ reasoning += _extract_text(record.get("content")).strip()
+ elif event_type == "chat.delta":
+ assistant_content += _extract_text(record.get("content")).strip()
+ elif event_type == "chat.final":
+ assistant_content = _extract_text(record.get("content")).strip()
+ elif event_type == "chat.tool_call":
+ tool_call = record.get("tool_call") or {}
+ if isinstance(tool_call, dict):
+ extracted = _extract_skills_from_tool_call(tool_call)
+ for s in extracted:
+ if s and s not in skills:
+ skills.append(s)
+ messages.append({"role": "assistant", "content": assistant_content, "reasoning": reasoning,
+ "tool_call": tool_call})
+ assistant_content = ""
+ reasoning = ""
+ elif event_type == "chat.tool_result":
+ tool_result = _extract_text(record.get("result")).strip()
+ messages.append({"role": "tool", "content": tool_result})
+ # Extract skills from raw_output (e.g. symphony_compose_score plan)
+ raw_output = record.get("raw_output")
+ if isinstance(raw_output, dict):
+ tool_name = record.get("tool_name", "")
+ if tool_name == "symphony_compose_score":
+ extracted = _extract_skills_from_raw_output(raw_output)
+ for s in extracted:
+ if s and s not in skills:
+ skills.append(s)
+ elif event_type == "chat.error":
+ messages.append({"role": "assistant", "content": _extract_text(record.get("content")).strip()})
+ _flush_record()
+ return trace_records
+
+
+def parse_all_sessions() -> list[TraceRecord]:
+ """Parse all sessions into TraceRecords, skipping unparseable ones."""
+ records: list[TraceRecord] = []
+ for session_id in list_session_ids():
+ trace_records = parse_session(session_id)
+ if trace_records:
+ records.extend(trace_records)
+ return records
\ No newline at end of file
diff --git a/pyproject.toml b/pyproject.toml
index fc3698cbf0..3953cd49e6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -45,6 +45,8 @@ dependencies = [
"httpx[socks]>=0.27",
"json-repair>=0.30.0",
"gitcode-api>=1.2.20",
+ "faiss-cpu>=1.7.0",
+ "numpy>=1.24.0",
]
[project.optional-dependencies]
diff --git a/uv.lock b/uv.lock
index f17d22af63..f01c71d065 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1016,6 +1016,26 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },
]
+[[package]]
+name = "faiss-cpu"
+version = "1.14.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "numpy" },
+ { name = "packaging" },
+]
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/83/b0/48c083d01b7b68c463c1d56507147a9d733f791e1c469a77215a872a9fb5/faiss_cpu-1.14.3-cp310-abi3-macosx_14_0_arm64.whl", hash = "sha256:a9369863290a3f0e033757e4c10577b6ef7431f1cede394dabd0a137e4e2ed45", size = 4768290, upload-time = "2026-06-13T02:19:03.427Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/34/6b04ef5bae3eada6b5a9457d7875cce041c040d53c890815cbd1e9821c65/faiss_cpu-1.14.3-cp310-abi3-macosx_15_0_x86_64.whl", hash = "sha256:f9d0e84d909194f63f027bbd3c1e35e905e48c9345c2db6e6f24da09a6bc5906", size = 6925734, upload-time = "2026-06-13T02:19:05.232Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/8a/b451af4b3c6dd18749ecfb58ccb68503b77e49c9aa4a89d950e9d521e058/faiss_cpu-1.14.3-cp310-abi3-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d734cfa9ac90b6a5dfed3a27cb706d05f22824703dafc3969b4e2071877a31c", size = 9661210, upload-time = "2026-06-13T02:19:06.99Z" },
+ { url = "https://files.pythonhosted.org/packages/a0/ed/57335bc18c9e18677587bec9bf070c675b29c8e683e13f4def0440731ca0/faiss_cpu-1.14.3-cp310-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8780b526c06e57aad90a8c4655dfba2ff1b3195bd600ff4499752fc45159c9fc", size = 18506292, upload-time = "2026-06-13T02:19:09.621Z" },
+ { url = "https://files.pythonhosted.org/packages/e7/d3/c6ca8c44a63b909e78aa8a69e14501c79c89613e62261d58455ea603d710/faiss_cpu-1.14.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b28ba083e8c02f2c9be03783402537fd3f00d27e68799c44bf88931500ee12ec", size = 11238800, upload-time = "2026-06-13T02:19:12.821Z" },
+ { url = "https://files.pythonhosted.org/packages/93/5f/b405692913a301251749cb175cb3f564ed257fdaa80a22c9a36444d0095d/faiss_cpu-1.14.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:cdcb90850cb4b7c27d270839b37bcc0dc8d1fb6a62d1e13053e51ac95061ca25", size = 19237637, upload-time = "2026-06-13T02:19:15.531Z" },
+ { url = "https://files.pythonhosted.org/packages/78/6c/bbf670ad727502102fa90c52f9b47c73753f0adda880d30427ac1d48b37b/faiss_cpu-1.14.3-cp311-cp311-win_amd64.whl", hash = "sha256:f278003d00c30c90cf118b98428bb96f73eba4b9dadac6993c788966d2e983bd", size = 16159350, upload-time = "2026-06-13T02:19:20.601Z" },
+ { url = "https://files.pythonhosted.org/packages/59/aa/bfa53255a6aa6e79b2471bb5af895f662feb02b612e1e0f9efc3d893286e/faiss_cpu-1.14.3-cp312-cp312-win_amd64.whl", hash = "sha256:0a5eb27184123c7ac1060c6b862978eabf0e30c1369ccf8bdb1497d35c06ad3d", size = 16164699, upload-time = "2026-06-13T02:19:22.969Z" },
+ { url = "https://files.pythonhosted.org/packages/1d/c1/2fb14f58ff74d7a7d6fd13084c016d9b144ce0bcdf77f6526cc2e4828278/faiss_cpu-1.14.3-cp313-cp313-win_amd64.whl", hash = "sha256:ea2340f675db59af8db6da4535b541ce6948d68a008989c656c292c7b0c77127", size = 16162836, upload-time = "2026-06-13T02:19:25.529Z" },
+]
+
[[package]]
name = "fakeredis"
version = "2.34.1"
@@ -1687,6 +1707,7 @@ dependencies = [
{ name = "croniter" },
{ name = "dingtalk-stream" },
{ name = "discord-py" },
+ { name = "faiss-cpu" },
{ name = "fastapi" },
{ name = "gitcode-api" },
{ name = "google-genai" },
@@ -1696,6 +1717,7 @@ dependencies = [
{ name = "lark-oapi" },
{ name = "loguru" },
{ name = "mutagen" },
+ { name = "numpy" },
{ name = "openjiuwen" },
{ name = "opentelemetry-api" },
{ name = "opentelemetry-exporter-otlp-proto-grpc" },
@@ -1795,6 +1817,7 @@ requires-dist = [
{ name = "discord-py", specifier = ">=2.4.0" },
{ name = "fastapi", specifier = ">=0.115" },
{ name = "gitcode-api", specifier = ">=1.2.20" },
+ { name = "faiss-cpu", specifier = ">=1.7.0" },
{ name = "google-genai", specifier = ">=1.68.0" },
{ name = "greenlet", specifier = ">=3.3.2" },
{ name = "httpx", extras = ["socks"], specifier = ">=0.27" },
@@ -1803,6 +1826,7 @@ requires-dist = [
{ name = "lark-oapi", specifier = ">=1.5.3" },
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "mutagen", specifier = ">=1.47.0" },
+ { name = "numpy", specifier = ">=1.24.0" },
{ name = "openjiuwen", git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop" },
{ name = "openjiuwen", extras = ["postgres", "zmq"], marker = "extra == 'distribute'" },
{ name = "opentelemetry-api", specifier = ">=1.25.0" },