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(experience bank): add retry for exception and add batch-wise embedding

Haowei_Dua9944051c3f1
diff --git a/jiuwenswarm/symphony/experience/bank.py b/jiuwenswarm/symphony/experience/bank.py
index 5b95ec6abb..8864d99c9e 100644
--- a/jiuwenswarm/symphony/experience/bank.py
+++ b/jiuwenswarm/symphony/experience/bank.py
@@ -538,8 +538,15 @@ class ExperienceBank:
skill_ids: list[str],
success_count: int = 1,
) -> ExperienceItem:
- """Create an ExperienceItem with auto-generated embedding and id."""
- text_for_embedding = query_pattern + "\n" + "\n".join(query_examples)
+ """Create an ExperienceItem with auto-generated embedding and id.
+
+ The embedding is derived from ``query_pattern`` only — a generalized
+ template carries the skill's intent cleanly, while concatenating raw
+ query_examples would dilute it with concrete entities and let
+ same-domain (but wrong) skills cross the threshold. ``query_examples``
+ is still stored on the item for display / debugging, just not embedded.
+ """
+ text_for_embedding = query_pattern or ""
embedding = self._embedder.embed(text_for_embedding)
return ExperienceItem(
diff --git a/jiuwenswarm/symphony/experience/cluster.py b/jiuwenswarm/symphony/experience/cluster.py
index 525427d22b..400922065a 100644
--- a/jiuwenswarm/symphony/experience/cluster.py
+++ b/jiuwenswarm/symphony/experience/cluster.py
@@ -35,13 +35,16 @@ def cluster_traces(
embedder: EmbeddingClient,
n_clusters: int | None = None,
min_cluster_size: int = 1,
- cluster_max_examples: int | None = None,
+ max_k: int = 8,
) -> 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 buckets.
+ 2. Within each group, embed ALL distinct queries (no sampling — preserves
+ sub-ability coverage) and cluster via FAISS K-Means.
+ 3. K is adaptive per skill: min(max_k, max(2, round(sqrt(n/2)))), so small
+ skills get few clusters, large skills are capped at max_k.
+ 4. Split each semantic cluster into success buckets.
"""
if not traces:
return []
@@ -52,8 +55,6 @@ def cluster_traces(
key = frozenset(t.skills) if t.skills else frozenset()
skill_groups.setdefault(key, []).append(t)
- sampler = random.Random(42)
-
result: list[ClusteredQuery] = []
cluster_id_counter = 0
@@ -63,16 +64,23 @@ def cluster_traces(
if not group_traces:
continue
successes = [t for t in group_traces if t.success]
- if cluster_max_examples is not None:
- cap = max(1, cluster_max_examples)
- successes = (sampler.sample(successes, cap) if len(successes) > cap else successes)
+ # Cluster on the FULL set of distinct queries per skill — no sampling,
+ # so sub-abilities of large skills are preserved. LLM distillation
+ # caps its own input examples separately via max_success_examples.
queries = [t.query for t in successes]
embeddings = embedder.embed_batch(queries)
+ # Adaptive k: sqrt(n/2), capped at max_k, at least 2.
+ n = len(queries)
+ if n_clusters is not None:
+ k = n_clusters
+ else:
+ k = min(max_k, max(2, round((n / 2) ** 0.5)))
+
labels = _faiss_cluster(
embeddings,
max_iterations=50,
- n_clusters=n_clusters,
+ n_clusters=k,
min_cluster_size=min_cluster_size,
)
diff --git a/jiuwenswarm/symphony/experience/collector.py b/jiuwenswarm/symphony/experience/collector.py
index 7c70d265a3..c76a386512 100644
--- a/jiuwenswarm/symphony/experience/collector.py
+++ b/jiuwenswarm/symphony/experience/collector.py
@@ -52,7 +52,6 @@ class ExperienceBaseBuilder:
self._pattern_merge_threshold = self._config.pattern_merge_threshold
self._query_examples_count = self._config.query_examples_count
self._skill_cluster_num = self._config.skill_cluster_num
- self._cluster_max_examples = self._config.cluster_max_examples
self._lock = threading.Lock()
def build(self, traces: list[TraceRecord]) -> int:
@@ -99,7 +98,6 @@ class ExperienceBaseBuilder:
valid_traces, self._embedder,
n_clusters=self._skill_cluster_num,
min_cluster_size=self._min_cluster_size,
- cluster_max_examples=self._cluster_max_examples,
)
cluster_elapsed = time.monotonic() - t1
LOGGER.info(
@@ -316,9 +314,13 @@ class ExperienceBaseBuilder:
if len(candidates) == 0:
break
sub = local_sim[np.ix_(group, candidates)]
- weakest = sub.min(axis=0) # min sim vs group, per candidate
+ # SINGLE-LINKAGE: a candidate joins if it is ≥threshold to
+ # ANY member of the group (not ALL members). This lets
+ # transitively-similar patterns merge even when two members
+ # of the group are only loosely similar to each other.
+ best_per_candidate = sub.max(axis=0) # max sim vs group, per candidate
score = np.where(
- np.all(sub >= threshold, axis=0), weakest, -np.inf,
+ np.any(sub >= threshold, axis=0), best_per_candidate, -np.inf,
)
if not np.isfinite(score).any():
break
@@ -326,17 +328,27 @@ class ExperienceBaseBuilder:
group.append(pick)
assigned[pick] = True
+ # Re-distill a fresh pattern covering the merged group: feed the
+ # group's existing patterns + pooled representative queries to
+ # the LLM so the survivor pattern subsumes all sub-abilities
+ # rather than just copying the success_count-max one.
rep = patterns[ordered[group[0]]]
pooled: list[TraceRecord] = []
+ group_patterns: list[str] = []
for pos in group:
- cluster = cluster_by_id.get(patterns[ordered[pos]].cluster_id)
+ pat = patterns[ordered[pos]]
+ group_patterns.append(pat.pattern_description)
+ cluster = cluster_by_id.get(pat.cluster_id)
if cluster:
pooled.extend(cluster.success_traces)
+ merged_pattern = self._redistill_merged(
+ rep, group_patterns, pooled
+ )
synthetic_id = -synthetic_counter
synthetic_counter += 1
cluster_by_id[synthetic_id] = ClusteredQuery(
cluster_id=synthetic_id,
- centroid_query=rep.pattern_description,
+ centroid_query=merged_pattern,
member_traces=list(pooled),
success_traces=list(pooled),
failure_traces=[],
@@ -344,15 +356,45 @@ class ExperienceBaseBuilder:
merged.append(DistilledPattern(
cluster_id=synthetic_id,
effective_skills=rep.effective_skills,
- pattern_description=rep.pattern_description,
+ pattern_description=merged_pattern,
))
LOGGER.info(
- "TraceIndexBuilder: merged %d patterns (threshold=%.2f, similarity-first greedy, bucketed-by-skill)",
+ "TraceIndexBuilder: merged %d patterns (threshold=%.2f, single-linkage greedy, bucketed-by-skill)",
len(merged), threshold,
)
return merged
+ def _redistill_merged(
+ self,
+ rep: DistilledPattern,
+ group_patterns: list[str],
+ pooled: list[TraceRecord],
+ ) -> str:
+ """Produce a survivor pattern for a merged group via the LLM.
+
+ Feeds the group's existing clean patterns to TraceDistiller's merge
+ routine, which returns one pattern subsuming all sub-abilities. The
+ LLM also sees a sample of pooled success queries for real phrasing.
+ Falls back to the rep pattern on any failure.
+ """
+ # Dedup patterns, keep order, drop empties.
+ seen: set[str] = set()
+ uniq: list[str] = []
+ for p in group_patterns:
+ if p and p not in seen:
+ seen.add(p)
+ uniq.append(p)
+ skill = (rep.effective_skills or [""])[0] if rep.effective_skills else ""
+ distiller = TraceDistiller(
+ self._llm,
+ self._llm_model,
+ skills_info=self._skills_info,
+ max_workers=self._max_workers,
+ max_success_examples=self._max_success_examples,
+ )
+ return distiller.distill_merged_pattern(skill, uniq, rep.pattern_description)
+
# ------------------------------------------------------------------
# Internal
# ------------------------------------------------------------------
@@ -364,7 +406,12 @@ class ExperienceBaseBuilder:
force: bool = False,
) -> int:
"""Embed records, cluster by semantic similarity, name each cluster,
- and write to KB.
+ dedup against existing KB, and write to KB.
+
+ Mirrors the full-build path: adaptive K-Means clustering (via
+ ``cluster_traces``) → LLM distillation → single-linkage merge of the
+ NEW patterns → batch-dedup against existing items → one ``add_batch``
+ write (avoids the O(N) write-amplification of per-item ``add``).
Returns number of items created.
"""
@@ -373,50 +420,18 @@ class ExperienceBaseBuilder:
self._pending.extend(records)
return 0
- # Cluster by embedding
- queries = [r.query for r in records]
- embeddings = self._embedder.embed_batch(queries)
-
- cluster_labels = _faiss_cluster(embeddings, n_clusters=self._skill_cluster_num,
- min_cluster_size=self._min_cluster_size)
-
- created = 0
- clusters: dict[int, list[TraceRecord]] = defaultdict(list)
- noise: list[TraceRecord] = []
- local_clusters: dict[int, list[int]] = {}
- for i, label in enumerate(cluster_labels):
- if label >= 0:
- clusters[label].append(records[i])
- local_clusters.setdefault(label, []).append(i)
- else:
- noise.append(records[i])
-
- # Put noise back into pending (only if not forcing)
- if not force:
- self._pending.extend(noise)
-
- # Name each cluster and write to KB
- cluster_id_offset = 0
- for label, cluster_records in clusters.items():
- if len(cluster_records) < self._min_hits and not force:
- self._pending.extend(cluster_records)
- continue
- cid = self._kb.count + cluster_id_offset
- cluster_query = populate_cluster(cid, embeddings, local_clusters[label], cluster_records)
- item = self._try_merge_into_existing(cluster_query, skill_ids)
- if item:
- created += 1
- cluster_id_offset += 1
- return created
+ # Stage 1: cluster via the shared adaptive-K routine (same as full build)
+ clusters = cluster_traces(
+ records, self._embedder,
+ n_clusters=self._skill_cluster_num,
+ min_cluster_size=self._min_cluster_size,
+ )
+ if not clusters:
+ if not force:
+ self._pending.extend(records)
+ return 0
- def _try_merge_into_existing(
- self,
- cluster: ClusteredQuery,
- skill_ids: list[str],
- ) -> ExperienceItem | None:
- """Check if an experience with similar pattern and same skills already exists.
- If yes, skip (deduplication). If no, create a new item.
- """
+ # Stage 2: distill each new cluster into a pattern
distiller = TraceDistiller(
self._llm,
self._llm_model,
@@ -424,37 +439,39 @@ class ExperienceBaseBuilder:
max_workers=self._max_workers,
max_success_examples=self._max_success_examples,
)
- distilled = distiller.run([cluster])
- if not distilled:
- return None
- examples = [trace.query for trace in cluster.member_traces]
-
- # 先做 embedding 去重
- items = self._kb.search_by_embedding(distilled[0].pattern_description, threshold=self._pattern_merge_threshold)
- if items:
- # 检查是否有相同 skill 组合的 item
- for _, existing in items:
- if set(existing.skill_ids) == set(skill_ids):
- return None # 完全重复,跳过
-
- return self._create_new_item(distilled[0].pattern_description, examples, skill_ids)
-
+ distilled = distiller.run(clusters)
+ valid_patterns = [p for p in distilled if p.pattern_description]
+ if not valid_patterns:
+ return 0
+ # Stage 3: single-linkage merge among the NEW patterns (same logic as
+ # full build) so transitive duplicates within this batch collapse first.
+ cluster_by_id = {c.cluster_id: c for c in clusters}
+ merged_patterns = self._merge_similar_patterns(valid_patterns, cluster_by_id)
- def _create_new_item(
- self,
- pattern: str,
- query_examples: list[str],
- skill_ids: list[str],
- ) -> ExperienceItem:
- """Helper to create a new experience item."""
+ # Stage 4: dedup each new pattern against existing KB items with the
+ # same skill set. Skip if an existing item is already ≥threshold similar
+ # (single-linkage already collapsed within-batch duplicates; this only
+ # guards cross-batch). Collect survivors for one batched write.
sample_n = max(0, self._query_examples_count)
- item = self._kb.create_item(
- query_pattern=pattern,
- query_examples=query_examples[:sample_n],
- skill_ids=skill_ids,
- )
- self._kb.add(item)
- return item
+ new_items: list[ExperienceItem] = []
+ for pat in merged_patterns:
+ examples = [t.query for t in cluster_by_id.get(pat.cluster_id, None).success_traces] \
+ if cluster_by_id.get(pat.cluster_id) else []
+ if self._kb.exist(pat.effective_skills):
+ # Same-skill items already exist — skip if any is similar enough
+ hits = self._kb.search_by_embedding(pat.pattern_description, threshold=self._pattern_merge_threshold)
+ if any(set(it.skill_ids) == set(pat.effective_skills) for _s, it in hits):
+ continue
+ new_items.append(self._kb.create_item(
+ query_pattern=pat.pattern_description,
+ query_examples=examples[:sample_n] if sample_n else [],
+ skill_ids=list(pat.effective_skills),
+ ))
+
+ # Stage 5: ONE batched write (single index rebuild + single persist)
+ if new_items:
+ self._kb.add_batch(new_items)
+ return len(new_items)
__all__ = ["ExperienceBaseBuilder"]
diff --git a/jiuwenswarm/symphony/experience/distiller.py b/jiuwenswarm/symphony/experience/distiller.py
index db4946d77b..a734ab9643 100644
--- a/jiuwenswarm/symphony/experience/distiller.py
+++ b/jiuwenswarm/symphony/experience/distiller.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import logging
+import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any
@@ -12,41 +13,50 @@ from .models import DistilledPattern
LOGGER = logging.getLogger(__name__)
+_LLM_MAX_RETRIES = 4
+
_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.
+You are generating a query pattern for ONE target skill. The pattern must capture the TYPICAL USER INTENT for this skill, blending two sources:
-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.
+1. SKILL DESCRIPTION (semantic anchor + DISCRIMINATOR): defines what this skill does. The pattern's core meaning MUST stay within this skill's capability, AND MUST preserve the SKILL-SPECIFIC DISCRIMINATOR WORDS from the description verbatim — the skill's name, its signature objects, and its hallmark action. These words are what distinguish this skill from same-domain neighbors; do NOT generalize them into neutral placeholders.
-For Chinese queries, use Chinese placeholders: [人名], [地点], [日期], [事物], etc., and keep the rest of the sentence natural.
+2. SUCCESSFUL QUERIES (real phrasing): show how users actually phrase requests that involve this skill. Borrow natural verbs, objects, and sentence structure from them — but ONLY the clause that maps to the TARGET skill's capability.
----
+CRITICAL — compound queries: The successful queries are COMPOUND (multiple skills per sentence). Extract ONLY the clause that maps to the TARGET skill's description. Any clause belonging to a DIFFERENT skill (e.g. translation when target is docx, marketing when target is docx) must be DROPPED from the pattern entirely — do NOT mention it even as "input" or "context"; replace its output with a neutral placeholder like [内容] if needed. If no clause matches the target skill, derive the pattern purely from the description.
-CLUSTER INFO:
-Cluster ID: {cluster_id}
-Representative Query: {centroid_query}
+Discriminator principle (most important rule): same-domain skills must produce distinguishable patterns. Preserve each skill's signature word so its pattern does not collide with neighbors:
+- skill "tencent-docs" (腾讯文档): keep "腾讯文档"/"在线文档" — NOT just "[文档]"
+- skill "document-processor" (二维码生成器): keep "二维码" — NOT "[文档]"
+- skill "react-best-practices" (前端代码审计): keep "前端代码" + "审计/优化" — to distinguish from UI-design skills
+- skill "awesome-design-md" (UI设计): keep "UI设计页面" — to distinguish from code-audit skills
+Generalize ONLY truly variable entities unrelated to the skill domain (e.g. [人名][地点][日期]); keep domain entities concrete. The pattern must read like a standalone request for ONLY this skill, carrying its signature word.
-SUCCESSFUL QUERIES:
-{member_queries}
+---
-USED SKILLS IN THIS CLUSTER:
+SKILL DESCRIPTION (target):
{used_skills}
----
+REPRESENTATIVE QUERY:
+{centroid_query}
-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.
+SUCCESSFUL QUERIES (compound — extract only target-skill clauses):
+{member_queries}
-Produce a JSON object with a single key "pattern_description" whose value is the generalized query template.
+Produce a JSON object: {{"pattern_description": "<standalone pattern, preserving skill-specific discriminator words>"}}
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": "[城市][时间]的天气"}}
+- Compound queries: "拍这张法语菜单翻译并朗读,根据功效写三个促销口号,做成Word"
+Target skill: photo-translate-speak (拍照识别外文并翻译朗读)
+Output: {{"pattern_description": "帮我把这张[语言]的[菜单/标签/说明书]拍下来,识别文字翻译成中文并朗读给我听"}}
+Target skill: docx (创建编辑Word文档)
+Output: {{"pattern_description": "把[内容]做成Word文档,包含[表格/图文/排版要求]"}}
+Target skill: marketing-ideas (生成营销促销文案)
+Output: {{"pattern_description": "参考[产品信息]写一份针对[目标群体]的营销促销文案,包含[数量]个促销口号"}}
+- Discriminator examples (same domain, distinguishable):
+Target skill: tencent-docs (腾讯文档)
+Output: {{"pattern_description": "在腾讯文档里[创建/编辑]一个[在线文档/在线表格],记录[内容]"}}
+Target skill: document-processor (二维码生成器)
+Output: {{"pattern_description": "帮我把这段[网址/图片/文本]转成二维码"}}
Output ONLY valid JSON. No markdown, no explanation.
"""
@@ -105,15 +115,17 @@ class TraceDistiller:
results[idx] = future.result()
LOGGER.info("TraceDistiller: finished cluster %d", idx)
except Exception as exc:
+ # Skip the failed cluster rather than aborting the whole run.
+ # A single transient LLM error (rate limit, server hiccup, bad
+ # JSON) should not discard the patterns distilled for all other
+ # clusters. Downstream `build()` already drops empty patterns,
+ # so leaving results[idx] = None is safe.
LOGGER.error(
- "TraceDistiller: failed cluster %d (id=%d): %s (type=%s, repr=%r)",
+ "TraceDistiller: failed cluster %d (id=%d): %s (type=%s) — skipping",
idx, clusters[idx].cluster_id, exc,
- type(exc).__name__, exc,
+ type(exc).__name__,
)
- raise RuntimeError(
- f"TraceDistiller: distillation failed for cluster {idx} "
- f"(id={clusters[idx].cluster_id}): {exc}"
- ) from exc
+ results[idx] = None
return [r for r in results if r is not None]
@@ -126,24 +138,18 @@ class TraceDistiller:
prompt = self._build_prompt(cluster, success_queries, used_skill_names)
+ messages = [
+ {
+ "role": "system",
+ "content": (
+ "You are an expert at generalizing query patterns. "
+ "Output only valid JSON."
+ ),
+ },
+ {"role": "user", "content": prompt},
+ ]
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,
- extra_body={"enable_thinking": False, "thinking": {"type": "disabled"}},
- )
- content = response.choices[0].message.content
+ content = self._llm_call_with_retry(messages)
if not content:
raise RuntimeError(
f"LLM returned empty content for cluster {cluster.cluster_id}"
@@ -163,6 +169,103 @@ class TraceDistiller:
pattern_description=pattern_description,
)
+ def _llm_call_with_retry(self, messages: list[dict]) -> str:
+ """Call the LLM with retry/backoff on transient errors (429/5xx/transport).
+
+ 400-class client errors and JSON-parse issues are surfaced immediately
+ by the caller; here we only retry on rate-limit / server / transport
+ errors so a single 429 doesn't abort the whole multi-thousand-call
+ distillation run.
+ """
+ from openai import APIStatusError, RateLimitError
+
+ last_exc: Exception | None = None
+ for attempt in range(_LLM_MAX_RETRIES):
+ try:
+ response = self._llm.chat.completions.create(
+ model=self._llm_model,
+ messages=messages,
+ max_tokens=256,
+ stream=False,
+ extra_body={"enable_thinking": False, "thinking": {"type": "disabled"}},
+ )
+ return response.choices[0].message.content or ""
+ except (RateLimitError, OSError) as exc:
+ last_exc = exc
+ wait = min(2 ** attempt, 30)
+ LOGGER.warning(
+ "TraceDistiller: transient LLM error (attempt %d), retrying in %ds: %s",
+ attempt + 1, wait, exc,
+ )
+ time.sleep(wait)
+ except APIStatusError as exc:
+ status = getattr(exc, "status_code", None)
+ if status is not None and 400 <= status < 500:
+ # Client error — retrying won't fix it.
+ raise
+ last_exc = exc
+ wait = min(2 ** attempt, 30)
+ LOGGER.warning(
+ "TraceDistiller: LLM server error %s (attempt %d), retrying in %ds",
+ status, attempt + 1, wait,
+ )
+ time.sleep(wait)
+ raise RuntimeError(f"LLM call failed after {_LLM_MAX_RETRIES} retries: {last_exc}")
+
+ _MERGE_PATTERN_PROMPT = """\
+You are merging several semantically-overlapping query patterns for the SAME skill into ONE survivor pattern. Each input pattern already expresses the target skill's intent cleanly; your job is to produce a single generalized pattern that subsumes ALL of them without losing any sub-ability.
+
+Rules:
+- Preserve the SKILL-SPECIFIC DISCRIMINATOR WORDS already present in the inputs (skill name, signature objects, hallmark action).
+- Union the variable placeholders across inputs (e.g. if one pattern has [物体/文字] and another has [色泽/摆盘], combine into [物体/文字/色泽/摆盘]).
+- Keep domain entities concrete; do NOT over-generalize.
+- The output must read like a single standalone request for ONLY this skill, covering every sub-ability seen in the inputs.
+- Drop any clause that does not appear in ANY input pattern (don't invent new sub-tasks).
+
+SKILL (target):
+{skill}
+
+EXISTING PATTERNS (merge these):
+{patterns}
+
+Output JSON: {{"pattern_description": "<one merged pattern subsuming all inputs>"}}
+Output ONLY valid JSON. No markdown, no explanation.
+"""
+
+ def distill_merged_pattern(
+ self,
+ skill: str,
+ patterns: list[str],
+ fallback: str,
+ ) -> str:
+ """Merge N same-skill patterns into one survivor pattern via the LLM.
+
+ On any failure (LLM error, empty/invalid output), fall back to
+ ``fallback`` (typically the success_count-max pattern) so merging
+ never drops a group on the floor.
+ """
+ if not patterns:
+ return fallback
+ if len(patterns) == 1:
+ return patterns[0]
+ desc = self._skills_by_name.get(skill, "")
+ skill_line = f"- {skill}: {desc}" if desc else f"- {skill}"
+ pat_text = "\n".join(f"- {p!r}" for p in patterns)
+ prompt = self._MERGE_PATTERN_PROMPT.format(skill=skill_line, patterns=pat_text)
+ try:
+ content = self._llm_call_with_retry([
+ {"role": "system", "content": "Output only valid JSON."},
+ {"role": "user", "content": prompt},
+ ])
+ merged = self._parse_response(content, -1)
+ return merged or fallback
+ except Exception as exc:
+ LOGGER.warning(
+ "TraceDistiller: merge-distill failed for skill=%s (%s); using fallback pattern",
+ skill, type(exc).__name__,
+ )
+ return fallback
+
def _build_prompt(
self,
cluster: ClusteredQuery,
diff --git a/jiuwenswarm/symphony/experience/embed.py b/jiuwenswarm/symphony/experience/embed.py
index 2cae001002..1c9bda8e4e 100644
--- a/jiuwenswarm/symphony/experience/embed.py
+++ b/jiuwenswarm/symphony/experience/embed.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import logging
+import time
from typing import Any
LOGGER = logging.getLogger(__name__)
@@ -25,17 +26,28 @@ class EmbeddingClient:
model_name: str = "",
normalize: bool = True,
dimension: int | None = None,
+ api_batch_size: int | None = None,
+ api_timeout: float = 60.0,
) -> None:
self._backend: str = ""
self._normalize = bool(normalize)
self._dimension = dimension
self._total_tokens: int = 0
+ # Max texts per API call. DashScope text-embedding-v3 rejects lists longer
+ # than 10 (HTTP 400 "batch size ... should not be larger than 10"); a
+ # self-hosted OpenAI-compatible server (e.g. local bge-m3) typically has
+ # no such cap, so callers using those should pass api_batch_size=64+.
+ self._api_batch_size = 10 if api_batch_size is None else int(api_batch_size)
+ self._api_max_retries = 5
+ self._api_timeout = float(api_timeout)
# Path 1: OpenAI-compatible API
if base_url:
try:
from openai import OpenAI
- self._api_client = OpenAI(base_url=base_url, api_key=api_key or "dummy")
+ self._api_client = OpenAI(
+ base_url=base_url, api_key=api_key or "dummy", timeout=self._api_timeout,
+ )
self._api_model = str(model or "text-embedding-3-small")
self._backend = "openai_api"
LOGGER.info("EmbeddingClient: using OpenAI-compatible API, model=%s", self._api_model)
@@ -82,7 +94,7 @@ class EmbeddingClient:
def embed_batch(self, texts: list[str]) -> list[list[float]]:
"""Return embeddings for multiple texts."""
if self._backend == "openai_api":
- return [self._embed_api(t) for t in texts]
+ return self._embed_api_batch(texts)
if self._backend == "sentence_transformers":
vecs = self._st_model.encode(texts, normalize_embeddings=self._normalize, show_progress_bar=False)
return vecs.tolist()
@@ -91,20 +103,97 @@ class EmbeddingClient:
# -- private --
def _embed_api(self, text: str) -> list[float]:
- params: dict[str, Any] = {
- "input": text,
- "model": self._api_model,
- }
+ return self._embed_api_batch([text])[0]
+
+ def _embed_api_batch(self, texts: list[str]) -> list[list[float]]:
+ """Batch API embedding with retry/backoff.
+
+ Splits into sub-batches (``_api_batch_size`` each), one API call per
+ sub-batch. DashScope/OpenAI accept a list under ``input`` and return
+ one embedding per element (indexed by ``data[i].index``). Retries on
+ transient errors (429 / 5xx / connection) with exponential backoff.
+ """
+ results: list[list[float]] = [None] * len(texts) # type: ignore[list-item]
+ batch = self._api_batch_size
+ for start in range(0, len(texts), batch):
+ chunk = texts[start:start + batch]
+ vecs = self._embed_api_call(chunk)
+ for i, v in enumerate(vecs):
+ results[start + i] = v
+ # Should be fully filled by now; guard against any None just in case.
+ for i, r in enumerate(results):
+ if r is None:
+ results[i] = self._embed_api_call([texts[i]])[0]
+ return results
+
+ def _embed_api_call(self, texts: list[str]) -> list[list[float]]:
+ from openai import (
+ APITimeoutError,
+ APIStatusError,
+ APIConnectionError,
+ BadRequestError,
+ RateLimitError,
+ )
+ params: dict[str, Any] = {"input": texts, "model": self._api_model}
if self._dimension is not None:
params["dimensions"] = self._dimension
- resp = self._api_client.embeddings.create(**params)
- vec = resp.data[0].embedding
- usage = getattr(resp, "usage", None)
- if usage is not None:
- self._total_tokens += getattr(usage, "total_tokens", 0) or 0
- if self._normalize:
- vec = _l2_normalize(vec)
- return vec
+ last_exc: Exception | None = None
+ for attempt in range(self._api_max_retries):
+ try:
+ resp = self._api_client.embeddings.create(**params)
+ # Preserve input order via the data[].index field
+ by_index: dict[int, list[float]] = {}
+ for d in resp.data:
+ by_index[int(getattr(d, "index", len(by_index)))] = list(d.embedding)
+ vecs = [by_index[i] for i in range(len(texts))]
+ usage = getattr(resp, "usage", None)
+ if usage is not None:
+ self._total_tokens += getattr(usage, "total_tokens", 0) or 0
+ if self._normalize:
+ vecs = [_l2_normalize(v) for v in vecs]
+ return vecs
+ except BadRequestError as exc:
+ # 400 — caller error (e.g. too many texts, bad params).
+ # Retrying won't help; surface immediately.
+ raise RuntimeError(
+ f"EmbeddingClient: embeddings.create bad request (batch={len(texts)}): {exc}"
+ ) from exc
+ except RateLimitError as exc:
+ last_exc = exc
+ wait = min(2 ** attempt, 30)
+ LOGGER.warning(
+ "EmbeddingClient: rate limited on batch of %d (attempt %d), retrying in %ds",
+ len(texts), attempt + 1, wait,
+ )
+ time.sleep(wait)
+ except (APITimeoutError, APIConnectionError, OSError) as exc:
+ # Transient transport/timeout errors — retry with backoff.
+ last_exc = exc
+ wait = min(2 ** attempt, 30)
+ LOGGER.warning(
+ "EmbeddingClient: transient error on batch of %d (attempt %d): %s, retrying in %ds",
+ len(texts), attempt + 1, type(exc).__name__, wait,
+ )
+ time.sleep(wait)
+ except APIStatusError as exc:
+ # HTTP status error. 4xx (except rate-limit caught above) is a
+ # caller error — surface immediately. 5xx retries.
+ status = getattr(exc, "status_code", None)
+ if status is not None and 400 <= status < 500:
+ raise RuntimeError(
+ f"EmbeddingClient: embeddings.create client error {status} "
+ f"(batch={len(texts)}): {exc}"
+ ) from exc
+ last_exc = exc
+ wait = min(2 ** attempt, 30)
+ LOGGER.warning(
+ "EmbeddingClient: API error on batch of %d (attempt %d): %s, retrying in %ds",
+ len(texts), attempt + 1, exc, wait,
+ )
+ time.sleep(wait)
+ raise RuntimeError(
+ f"EmbeddingClient: embeddings.create failed after {self._api_max_retries} retries: {last_exc}"
+ )
def _embed_local(self, text: str) -> list[float]:
vec = self._st_model.encode(text, normalize_embeddings=self._normalize).tolist()
diff --git a/jiuwenswarm/symphony/experience/models.py b/jiuwenswarm/symphony/experience/models.py
index 5b41938cca..cd61f31a4e 100644
--- a/jiuwenswarm/symphony/experience/models.py
+++ b/jiuwenswarm/symphony/experience/models.py
@@ -94,7 +94,6 @@ class ExperienceBankBuildConfig:
skill_cluster_num: int | None = None
pattern_merge_threshold: float = 0.9
query_examples_count: int = 5
- cluster_max_examples: int | None = None
@dataclass
diff --git a/tests/symphony/test_experience_base.py b/tests/symphony/test_experience_base.py
index 434719c885..eb9be8890f 100644
--- a/tests/symphony/test_experience_base.py
+++ b/tests/symphony/test_experience_base.py
@@ -419,7 +419,6 @@ def test_add_propagates_flush_exception_instead_of_dropping_pending(monkeypatch)
builder._min_hits = 1
builder._skill_cluster_num = None
builder._min_cluster_size = 1
- builder._cluster_max_examples = None
builder._embedder = FakeEmbedder({"q": [1.0, 0.0]})
builder._kb = FakeBank()
builder._skills_info = None