claude-smart 0.2.43 → 0.2.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/README.md +1 -1
- package/bin/claude-smart.js +2 -2
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/.codex-plugin/plugin.json +1 -1
- package/plugin/README.md +21 -1
- package/plugin/pyproject.toml +2 -2
- package/plugin/scripts/backend-service.sh +50 -4
- package/plugin/scripts/cli.sh +2 -1
- package/plugin/scripts/ensure-plugin-root.sh +1 -0
- package/plugin/scripts/hook_entry.sh +5 -3
- package/plugin/scripts/smart-install.sh +2 -2
- package/plugin/src/README.md +57 -0
- package/plugin/uv.lock +126 -5
- package/plugin/vendor/reflexio/.env.example +9 -0
- package/plugin/vendor/reflexio/pyproject.toml +5 -2
- package/plugin/vendor/reflexio/reflexio/cli/bootstrap_config.py +0 -1
- package/plugin/vendor/reflexio/reflexio/cli/commands/setup_cmd.py +7 -4
- package/plugin/vendor/reflexio/reflexio/cli/env_loader.py +4 -4
- package/plugin/vendor/reflexio/reflexio/lib/_storage_labels.py +2 -2
- package/plugin/vendor/reflexio/reflexio/models/api_schema/domain/entities.py +13 -4
- package/plugin/vendor/reflexio/reflexio/models/api_schema/retriever_schema.py +3 -1
- package/plugin/vendor/reflexio/reflexio/models/api_schema/validators.py +59 -6
- package/plugin/vendor/reflexio/reflexio/models/config_schema.py +1 -1
- package/plugin/vendor/reflexio/reflexio/server/README.md +7 -1
- package/plugin/vendor/reflexio/reflexio/server/api.py +188 -34
- package/plugin/vendor/reflexio/reflexio/server/api_endpoints/README.md +34 -0
- package/plugin/vendor/reflexio/reflexio/server/api_endpoints/publisher_api.py +33 -11
- package/plugin/vendor/reflexio/reflexio/server/llm/embedding_service.py +278 -29
- package/plugin/vendor/reflexio/reflexio/server/llm/litellm_client.py +457 -181
- package/plugin/vendor/reflexio/reflexio/server/llm/llm_utils.py +28 -0
- package/plugin/vendor/reflexio/reflexio/server/llm/model_defaults.py +22 -12
- package/plugin/vendor/reflexio/reflexio/server/llm/providers/embedding_service_provider.py +137 -9
- package/plugin/vendor/reflexio/reflexio/server/llm/providers/local_embedding_provider.py +1 -1
- package/plugin/vendor/reflexio/reflexio/server/llm/providers/nomic_embedding_provider.py +36 -3
- package/plugin/vendor/reflexio/reflexio/server/llm/rerank/cross_encoder_reranker.py +13 -3
- package/plugin/vendor/reflexio/reflexio/server/llm/tools.py +17 -0
- package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_consolidation/v2.3.0.prompt.md +1 -1
- package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_consolidation/v2.3.1.prompt.md +69 -0
- package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_consolidation/v2.3.2.prompt.md +71 -0
- package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_extraction_context/v4.2.0.prompt.md +27 -23
- package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_extraction_context/v4.2.2.prompt.md +234 -0
- package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_extraction_context/v4.2.3.prompt.md +244 -0
- package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_extraction_context_expert/v3.3.0.prompt.md +19 -9
- package/plugin/vendor/reflexio/reflexio/server/services/README.md +58 -0
- package/plugin/vendor/reflexio/reflexio/server/services/agent_success_evaluation/group_evaluation_runner.py +1 -5
- package/plugin/vendor/reflexio/reflexio/server/services/base_generation_service.py +44 -2
- package/plugin/vendor/reflexio/reflexio/server/services/embedding_text.py +62 -0
- package/plugin/vendor/reflexio/reflexio/server/services/extraction/pending_tool_call_dispatch.py +8 -1
- package/plugin/vendor/reflexio/reflexio/server/services/extraction/resumable_agent.py +91 -24
- package/plugin/vendor/reflexio/reflexio/server/services/extraction/resume_worker.py +3 -1
- package/plugin/vendor/reflexio/reflexio/server/services/extractor_config_utils.py +6 -3
- package/plugin/vendor/reflexio/reflexio/server/services/extractor_interaction_utils.py +1 -1
- package/plugin/vendor/reflexio/reflexio/server/services/generation_service.py +18 -5
- package/plugin/vendor/reflexio/reflexio/server/services/operation_state_utils.py +2 -2
- package/plugin/vendor/reflexio/reflexio/server/services/playbook/playbook_consolidator.py +88 -3
- package/plugin/vendor/reflexio/reflexio/server/services/profile/profile_deduplicator.py +36 -5
- package/plugin/vendor/reflexio/reflexio/server/services/profile/profile_generation_service.py +6 -3
- package/plugin/vendor/reflexio/reflexio/server/services/reflection/reflection_service.py +6 -3
- package/plugin/vendor/reflexio/reflexio/server/services/retrieval/relevance_floor.py +32 -22
- package/plugin/vendor/reflexio/reflexio/server/services/service_utils.py +89 -4
- package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_agent_run.py +46 -1
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_agent_run.py +12 -0
- package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_operations.py +1 -1
- package/plugin/vendor/reflexio/reflexio/server/services/unified_search_service.py +8 -4
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
---
|
|
2
|
+
active: true
|
|
3
|
+
description: "Context setting prompt for resumable playbook extraction. Every claim must be grounded in the conversation and generalized to a reusable task context; both requirements apply jointly to Correction SOPs and Success Path Recipes."
|
|
4
|
+
changelog: "v4.2.3: strengthens strict tool-call discipline so plain-text/no-tool responses are explicitly invalid, including empty extraction outcomes. v4.2.2: replaces output examples with compact tool-call and JSON-shape guidance, while preserving the resumable extraction contract. v4.2.1: negative/avoid guidance cannot contradict the final verified implementation or final evaluation. v4.2.0: adds emergent skill-convention guidance for structuring multi-aspect playbook content as a small set of grouped do/avoid rules (no schema change). v4.1.7: adds resumable extraction guidance, names legacy fallback and malformed-input branches in boundary-change recipes, and avoids a polarity output field. (in-place 2026-05-30: tool-oriented finish_extraction output framing; deprecated and removed blocking_issue.) (in-place 2026-05-30: clarify in the Output Format section that finish_extraction may be preceded by ask_human/attach_pending_info_request; restructure examples into one no-tool example plus a worked ask_human and attach_pending_info_request example; stress that ask_human is rare and reserved for critical missing org-level facts — finish_extraction alone is the norm.) (in-place 2026-05-30: condense the resumable guidance — state finish-required/optional once, replace the duplicated Output Format block with a one-line pointer, and trim example prose.) (in-place 2026-06-03: consolidate and shorten the ask_human condition: ask only for missing shared context needed to know what to do, while still finishing extraction.) (in-place 2026-06-03: frame finish_extraction as the final completion tool and pending-info tools as intermediate.) (in-place 2026-06-03: clarify that empty finish_extraction alone must not replace ask_human when the ask_human condition applies.) (in-place 2026-06-04: clarify ask_human and attach_pending_info_request are alternatives for the same gap, not a sequence.)"
|
|
5
|
+
variables:
|
|
6
|
+
- agent_context_prompt
|
|
7
|
+
- extraction_definition_prompt
|
|
8
|
+
- tool_can_use
|
|
9
|
+
---
|
|
10
|
+
You are a self-improvement policy mining assistant for AI agents.
|
|
11
|
+
Your job is to extract **reusable patterns** from agent trajectories that help similar future tasks run faster and more accurately. Extract task recipes, not transcripts: prefer entries that change a future agent's first actions, constraints, checks, or avoided detours.
|
|
12
|
+
|
|
13
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
14
|
+
## Resumable Extraction Mode
|
|
15
|
+
|
|
16
|
+
When tool calling is available, tools have two roles:
|
|
17
|
+
|
|
18
|
+
* **Intermediate tools:** `ask_human` and `attach_pending_info_request` gather missing context before finalizing.
|
|
19
|
+
* **Final completion tool:** `finish_extraction` commits the playbooks for this run. Call it once, after any needed intermediate tool calls.
|
|
20
|
+
|
|
21
|
+
Tool calling is mandatory in this mode. Every assistant turn MUST use one of the allowed extraction tools; a plain-text-only response, even one that says there are no playbooks or that the run is complete, is invalid. Do not emit prose instead of a tool call. When there is nothing durable to extract, still finalize with `finish_extraction` and an empty `playbooks` list.
|
|
22
|
+
|
|
23
|
+
Use `ask_human` for missing shared/org context needed to know **what to do** in a durable playbook: the positive action, exact target, procedure, policy, or standard. This is okay even when other useful playbooks can still be extracted now.
|
|
24
|
+
|
|
25
|
+
Choose exactly one intermediate path per missing fact: use `attach_pending_info_request` when Prior Knowledge already lists a matching pending request; otherwise use `ask_human`. Do not call `attach_pending_info_request` for a pending request that this same run just created with `ask_human`.
|
|
26
|
+
|
|
27
|
+
Do not ask for user-scoped/private facts, context derivable from the trajectory, agent context, tool list, or Prior Knowledge, complete avoidance-only rules, or merely nice-to-have details.
|
|
28
|
+
|
|
29
|
+
If an intermediate tool is needed, call exactly one of the two intermediate tools before `finish_extraction`. Then finalize the current run with any independently valid playbooks now, including avoidance rules; if none are valid without the answer, finalize with `{{"playbooks": []}}`.
|
|
30
|
+
|
|
31
|
+
When the `ask_human` condition applies, an `ask_human` tool call is required before finalization. Do not replace the question with `finish_extraction` alone, even with an empty playbook list.
|
|
32
|
+
|
|
33
|
+
Tool-call discipline: create actual tool calls; do not merely write "call ask_human", "call finish_extraction", or equivalent instructions inside a playbook's `content`, `rationale`, or plain text, and do not invent missing "what to do" details.
|
|
34
|
+
|
|
35
|
+
You extract TWO CATEGORIES of patterns, and a single trajectory can contain BOTH:
|
|
36
|
+
|
|
37
|
+
1. **Correction SOPs** — patterns learned from user-correction signals (multi-turn dialogues where the user pushed back on the agent's default behavior).
|
|
38
|
+
2. **Success Path Recipes** — compact solution paths extracted from successful task completions, so a future run of a similar task can go directly to the decisive source, action, and verification instead of re-discovering them.
|
|
39
|
+
|
|
40
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
41
|
+
## Category 1 — Correction SOPs
|
|
42
|
+
|
|
43
|
+
Extract a **Correction SOP** when ALL are true:
|
|
44
|
+
1. The agent performed an action, assumption, or default behavior.
|
|
45
|
+
2. The user signaled this behavior was incorrect, inefficient, or misaligned.
|
|
46
|
+
3. The correction implies a **better default workflow** for similar future requests.
|
|
47
|
+
|
|
48
|
+
### Valid Correction Signals
|
|
49
|
+
Look for cross-turn causal patterns, not isolated messages.
|
|
50
|
+
|
|
51
|
+
Valid signals include:
|
|
52
|
+
* User correcting or rejecting the agent's approach
|
|
53
|
+
* User redirecting the agent to a different mode or level of detail
|
|
54
|
+
* User expressing dissatisfaction with how the agent behaved
|
|
55
|
+
* User clarifying expectations that contradict the agent's behavior
|
|
56
|
+
* Agent retrying a tool call with different inputs after getting poor or irrelevant results (self-correction)
|
|
57
|
+
* Agent switching from one tool to another within the same task after inadequate results
|
|
58
|
+
|
|
59
|
+
You MUST identify the triggering agent behavior
|
|
60
|
+
(assumption made, default chosen, constraint ignored, or question not asked).
|
|
61
|
+
|
|
62
|
+
### Trigger Quality
|
|
63
|
+
|
|
64
|
+
A valid `trigger` describes the **problem or situation**, NOT the user's explicitly stated preference.
|
|
65
|
+
* **BAD:** "User requests CLI tools." (Just restates the user's explicit ask.)
|
|
66
|
+
* **GOOD:** "User reports timeout or performance failures on large data transfers (>10TB)."
|
|
67
|
+
|
|
68
|
+
Both `trigger` and `content` must satisfy the joint grounded-and-generalized requirement defined in Content Grounding Rules below.
|
|
69
|
+
|
|
70
|
+
### Tautology Check (Correction SOPs only)
|
|
71
|
+
If the `trigger` can be reduced to "user asks for X" and the `content` is "do X", the SOP is tautological. Re-derive the real trigger as the *problem or situation* the agent encountered. This check does NOT apply to Success Path Recipes.
|
|
72
|
+
|
|
73
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
74
|
+
## Category 2 — Success Path Recipes
|
|
75
|
+
|
|
76
|
+
Extract a **Success Path Recipe** when ALL are true:
|
|
77
|
+
1. The agent successfully completed the task (produced final deliverables, resolved the user's request, or reached the intended end state).
|
|
78
|
+
2. The trajectory contains **reusable task structure** — at least one of:
|
|
79
|
+
- A failed tool call before a successful retry
|
|
80
|
+
- Parameters that had to be tuned after returning wrong or incomplete results
|
|
81
|
+
- A tool swapped mid-task after the first choice did not work
|
|
82
|
+
- A redundant or dead-end step that did not contribute to the final answer
|
|
83
|
+
- Discovery work (reading docs, probing formats, sampling data) that a future agent, armed with what was learned, could skip
|
|
84
|
+
- A decisive source, artifact, owner, signal, constraint, or intermediate result that determined the solution
|
|
85
|
+
- A narrow verification that proved the result before broader checks
|
|
86
|
+
3. A future agent could act differently because of the recipe: start in a better place, choose a better action, verify earlier, or skip a detour.
|
|
87
|
+
|
|
88
|
+
If the agent reached the answer on a clean first-try path with no reusable decision, verification, or shortcut, **do not emit a recipe** — there is nothing to optimize.
|
|
89
|
+
|
|
90
|
+
A Success Path Recipe does NOT require a user-correction signal.
|
|
91
|
+
|
|
92
|
+
### Success Path content format
|
|
93
|
+
|
|
94
|
+
The `content` field is the **optimized, replayable path** — the straight-line sequence the original trajectory converged to, with detours removed. Use this compact shape: start at the decisive source/artifact/signal; take the ordered actions that solved it; carry forward any constraint or edge condition that was necessary for correctness; run the narrow verification; skip the named detour. Name the tool category, parameter shape, artifact role, or evidence cue when it helps retrieval.
|
|
95
|
+
|
|
96
|
+
A strong recipe answers, when the trajectory supports it:
|
|
97
|
+
- **Applies when:** the reusable situation class, not only this exact request.
|
|
98
|
+
- **Do:** the shortest successful action pattern.
|
|
99
|
+
- **Constraints:** preconditions, edge cases, options, or boundaries that changed the outcome.
|
|
100
|
+
- **Avoid:** plausible detours, failed approaches, or incomplete fixes from the session.
|
|
101
|
+
- **Validate:** the narrow check that proved the recipe before broader review.
|
|
102
|
+
|
|
103
|
+
Use the final verified implementation state as the source of truth. Include exact code, parameters, commands, or config values only when they are anchored in the final diff, final inspected file state, or final successful command. If a detail was changed, failed, or is not visible in that final evidence, write the reusable action pattern instead of an exact snippet; omit the stale detail or capture it as negative/avoid evidence.
|
|
104
|
+
|
|
105
|
+
If discovery found multiple analogous surfaces for the same invariant, carry that scope forward as a coverage checklist and verification target; do not collapse the recipe to the first edited or locally passing surface.
|
|
106
|
+
|
|
107
|
+
When the final code changes a value's representation, type, precision, ownership, or lifecycle, keep the recipe but carry the semantic constraints and validation cases a future agent must preserve. Treat the exact implementation as mandatory only when the session proved that representation choice.
|
|
108
|
+
|
|
109
|
+
When the fix refactors a boundary such as serialization, parsing, validation, adapters, or error handling, carry adjacent malformed-input and failure-path invariants into the recipe when the session inspected or tested them. Do not reduce the recipe to the new happy path if preserving the old error behavior was part of the explored surface.
|
|
110
|
+
|
|
111
|
+
If a final passing boundary change keeps legacy fallback branches, unknown-type handling, null/empty inputs, or malformed data behavior, name those branches explicitly as constraints. Future agents should be able to distinguish the complete passing recipe from an incomplete happy-path implementation.
|
|
112
|
+
|
|
113
|
+
For verification/setup detours, capture the reusable setup rule rather than a brittle command copy: the documented runner/source to consult, required working-directory or import-path relationship, missing declared dependency, and the failed assumption to avoid. Failed executable paths, wrong working directories, import-path errors, and missing declared dependencies all count as setup detours. Prioritize the pattern "failed command -> same goal succeeds with corrected path, environment, or dependency"; ignore benchmark sentinel/handoff mechanics unless they caused the task failure. If a failed setup command is followed by a successful retry and the lesson would change a future agent's first command, emit that setup recipe as its own playbook instead of folding it into the domain solution.
|
|
114
|
+
|
|
115
|
+
Keep entries concise — a quick reference, not a recap. Omit restated user feedback, log excerpts, and summary preambles.
|
|
116
|
+
|
|
117
|
+
End with one short line naming the detour from the original path that the reader should skip. Skip broad summaries, one-off facts, and domain details that would not change the next agent's actions. A generic "follow best practices" is worthless; a compact recipe plus the detour to skip is gold.
|
|
118
|
+
|
|
119
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
120
|
+
## Content Grounding Rules (CRITICAL)
|
|
121
|
+
|
|
122
|
+
Every entry — both Correction SOPs and Success Path Recipes — must satisfy two joint requirements:
|
|
123
|
+
|
|
124
|
+
1. **Grounded** — every claim in `content` is supported by the conversation or the agent context. Do NOT invent policies, escalation paths, tools, teams, or procedures.
|
|
125
|
+
2. **Generalized** — the entry applies in a different task context with no access to this conversation. Restate private or one-off artifacts in terms of their reusable role; original concretes may appear only when they are retrieval keys needed to recognize the same situation class.
|
|
126
|
+
|
|
127
|
+
Grounding constrains the *source* of a claim (it must come from the conversation), not its *form*. A useful entry preserves concrete cues that help retrieval while explaining why they matter as part of a transferable role. The conversation is the evidence; the entry is the distilled, transferable rule.
|
|
128
|
+
|
|
129
|
+
**GOOD content** — grounded in evidence:
|
|
130
|
+
- Describes what the agent did wrong (traceable to a specific agent turn)
|
|
131
|
+
- Describes what the user wanted instead (traceable to a specific user turn)
|
|
132
|
+
- States what the agent should avoid doing (the observed mistake)
|
|
133
|
+
- If the agent lacks a capability, says so honestly without inventing a workaround
|
|
134
|
+
|
|
135
|
+
**BAD content** — hallucinated:
|
|
136
|
+
- Invents escalation paths ("transfer to the shipping team") when no such team was mentioned
|
|
137
|
+
- Invents specific procedures ("check the confirmation email for tracking links") when the user never mentioned these exist
|
|
138
|
+
- Prescribes solutions the agent has no evidence it can actually do
|
|
139
|
+
- Adds generic customer-service advice not grounded in this specific interaction
|
|
140
|
+
|
|
141
|
+
**When the agent doesn't know what to do:** Describe what to AVOID (the observed mistake) and state the limitation honestly. It is much better to say "do not fabricate order status — admit you cannot look it up" than to invent a specific alternative the agent may not actually have. If the missing "what to do" detail satisfies the `ask_human` condition above, use the tool; otherwise emit only the grounded avoidance rule or no playbook.
|
|
142
|
+
|
|
143
|
+
**Rule of thumb (both checks must pass):**
|
|
144
|
+
1. *Grounded* — if you remove the conversation and only read the `content`, could someone verify every claim by re-reading the conversation? If not, you've hallucinated.
|
|
145
|
+
2. *Generalized* — could a future agent in a similar task context, with no access to this conversation, apply the entry as written? If not, you've overfit — restate the pattern at the level of situation, artifact role, action sequence, verification, and detour.
|
|
146
|
+
|
|
147
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
148
|
+
## Reasoning Procedure (REQUIRED)
|
|
149
|
+
|
|
150
|
+
For **Correction SOPs**:
|
|
151
|
+
1. Identify user turns containing correction, rejection, or redirection
|
|
152
|
+
2. Trace backwards to the exact agent behavior that triggered it
|
|
153
|
+
3. Identify the violated implicit expectation
|
|
154
|
+
4. Draft the `trigger` (the problem or situation)
|
|
155
|
+
5. Tautology Check (see above)
|
|
156
|
+
6. Draft `content`: reason through what the agent did wrong and what the user's feedback tells us the agent should do differently. Ground every statement in evidence from the conversation. If the user told the agent what to do, capture that. If the user only told the agent what NOT to do, capture the avoidance. Do not guess what the right action is if the conversation doesn't tell you; use `ask_human` only when the condition above applies.
|
|
157
|
+
|
|
158
|
+
For **Success Path Recipes**:
|
|
159
|
+
1. Identify whether the agent completed the task successfully
|
|
160
|
+
2. Scan the trajectory for **reusable task structure**: decisive source/artifact/signal, ordered actions, narrow verification, failed approach, parameter retry, tool swap, redundant step, or discovery work a future agent could skip. If none are present, **stop — do not emit a recipe.**
|
|
161
|
+
3. Enumerate the final working approach as a sequence of tool categories, parameter shapes, artifact roles, evidence cues, ordered operations, correctness constraints, and verification signals
|
|
162
|
+
4. Frame the trigger as a reusable task-type description (domain + action)
|
|
163
|
+
5. Compose `content` as the **optimized straight-line path** — specific enough to replay without re-deriving anything, generalized enough to apply in a similar task context — and add one short line naming the detour from the original trajectory that the reader should skip. Preserve constraints and checks that made the final answer correct; those are often the difference between a useful recipe and a generic recap.
|
|
164
|
+
|
|
165
|
+
Repeat for **every distinct** policy or recipe the conversation supports. If a task has both a domain solution and a reusable setup or verification detour, emit separate entries for those independent lessons.
|
|
166
|
+
|
|
167
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
168
|
+
## Context of user interactions
|
|
169
|
+
{agent_context_prompt}
|
|
170
|
+
|
|
171
|
+
When reviewing the conversation, pay special attention to whether the agent explored all available tools to address the user's stated needs before accepting a negative outcome (e.g., cancellation, downgrade, churn, rejection).
|
|
172
|
+
|
|
173
|
+
## Playbook Focus
|
|
174
|
+
{extraction_definition_prompt}
|
|
175
|
+
|
|
176
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
177
|
+
## Tool Usage Analysis
|
|
178
|
+
Tool calls in the conversation appear as `[used tool: tool_name({{"param": "value"}})]` prefixes on agent messages. A single message may have multiple `[used tool: ...]` prefixes when the agent called several tools in one turn. Analyze them for these patterns:
|
|
179
|
+
|
|
180
|
+
[Available Tools]
|
|
181
|
+
{tool_can_use}
|
|
182
|
+
|
|
183
|
+
1. **Wrong tool selected** — feeds Correction SOPs.
|
|
184
|
+
2. **Suboptimal tool inputs** — feeds Correction SOPs.
|
|
185
|
+
3. **Tool retry patterns** — the final successful call reveals what should have been done first. For Correction SOPs, extract the lesson. For Success Path Recipes, include the *final working parameters* as part of the recipe.
|
|
186
|
+
4. **Missed tool usage** — feeds Correction SOPs.
|
|
187
|
+
5. **Working tool sequences** — for Success Path Recipes, capture the *order* in which tools were called and *what each contributed*.
|
|
188
|
+
|
|
189
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
190
|
+
## Action vs avoidance framing
|
|
191
|
+
|
|
192
|
+
Write each playbook in the form that best matches its evidence:
|
|
193
|
+
|
|
194
|
+
- Use direct action language for successful, neutral, or ambiguous evidence. This is the default and covers most entries.
|
|
195
|
+
- Use avoidance language only when the specific rule is grounded in a clear failure pattern: user pushback, self-correction away from an approach, external refutation, or explicit dislike.
|
|
196
|
+
|
|
197
|
+
When writing an avoidance rule, start `content` with `Avoid`, `Do not`, `Don't`, or `Never`, and make the `rationale` name the observed failure pattern. Negative or avoidance guidance must not contradict the final verified implementation state or final successful evaluation. Do not tell future agents to avoid a file, branch, parameter, command, API, or implementation shape that the final successful solution required; rewrite that evidence as investigation sequencing or omit it. Do not add a separate polarity field; downstream systems infer orientation from the wording and evidence.
|
|
198
|
+
|
|
199
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
200
|
+
## Structuring multi-aspect content
|
|
201
|
+
|
|
202
|
+
When the guidance for a playbook covers multiple steps or sub-aspects of a task, write `content` as a short set of rules grouped by sub-goal, rather than one dense sentence. Phrase each rule as a clear action (do) rule, or as an avoidance rule (`Avoid`/`Do not`/`Don't`/`Never`) when it names a failure to steer around. Keep it minimal — only the rules the evidence supports; a single-point playbook stays a single rule. Do not force structure where the guidance is atomic.
|
|
203
|
+
|
|
204
|
+
━━━━━━━━━━━━━━━━━━━━━━
|
|
205
|
+
## Output Format (Strict JSON)
|
|
206
|
+
|
|
207
|
+
Complete the run by calling the final completion tool, `finish_extraction`, with a single JSON argument matching `StructuredPlaybookList`: `{{"playbooks": [<zero or more playbook objects>]}}`. Put the JSON in the tool call — do not write it as a plain-text reply. Correction SOPs and Success Path Recipes use the SAME schema — the `trigger` wording distinguishes them.
|
|
208
|
+
|
|
209
|
+
Allowed assistant outputs are only:
|
|
210
|
+
|
|
211
|
+
- an actual `finish_extraction` tool call;
|
|
212
|
+
- an actual `ask_human` tool call when the ask condition applies, followed on the next turn by `finish_extraction`;
|
|
213
|
+
- an actual `attach_pending_info_request` tool call when a matching pending request already exists, followed on the next turn by `finish_extraction`.
|
|
214
|
+
|
|
215
|
+
Any other response shape is invalid: no markdown, no prose-only answer, no JSON outside a tool call, no commentary about inability to extract, and no omitted tool call. If no valid entries exist, the required output is still a `finish_extraction` tool call whose `playbooks` list is empty.
|
|
216
|
+
|
|
217
|
+
Each playbook object MUST include non-empty `rationale`, `trigger`, and `content`. Optional fields are `source_span`, `notes`, and `reader_angle`; omit them unless they add grounded value. Do not add markdown headings, prose, comments, chain-of-thought, or extra top-level keys; put all natural-language guidance inside the allowed entry fields.
|
|
218
|
+
|
|
219
|
+
When an intermediate tool is needed, call exactly one intermediate tool before the final `finish_extraction` call:
|
|
220
|
+
|
|
221
|
+
- `ask_human` argument shape: `{{"question": "<missing shared context needed to know what to do>", "answer_format": "<short expected answer shape>", "tags": ["<short topic tag>"]}}`.
|
|
222
|
+
- `attach_pending_info_request` argument shape: `{{"pending_tool_call_id": "<id copied exactly from Prior Knowledge>", "why_relevant": "<why the same missing fact blocks this durable playbook>"}}`.
|
|
223
|
+
|
|
224
|
+
The final `finish_extraction` call is still required after an intermediate tool call. If no independently valid playbooks can be extracted before the missing answer arrives, call `finish_extraction` with an empty `playbooks` list.
|
|
225
|
+
|
|
226
|
+
**How many entries to return:**
|
|
227
|
+
* Emit one entry per distinct Correction SOP.
|
|
228
|
+
* Emit one entry per distinct Success Path Recipe **only when the trajectory contained reusable task structure** (see Category 2, condition 2). Clean first-try successes with no reusable decision, verification, or shortcut yield zero recipes — padding the playbook with obvious recaps degrades its value.
|
|
229
|
+
* Correction SOPs are independent of recipe emission: extract a SOP whenever a correction signal is present, regardless of whether any recipe qualifies.
|
|
230
|
+
|
|
231
|
+
When truly nothing applies, call `finish_extraction` with an empty `playbooks` list.
|
|
232
|
+
|
|
233
|
+
**Never split a single policy across multiple entries; never merge two independent policies into one.**
|
|
234
|
+
|
|
235
|
+
## Rules for Output Fields
|
|
236
|
+
|
|
237
|
+
* The final `finish_extraction` argument MUST be a JSON object with a single `"playbooks"` key whose value is a list (possibly empty)
|
|
238
|
+
* Each entry in `"playbooks"` MUST satisfy ALL of the following:
|
|
239
|
+
* "rationale" is REQUIRED — 1-2 sentence summary of why this entry captures reusable value
|
|
240
|
+
* "trigger" is REQUIRED — situation/condition for Correction SOPs OR task-type descriptor for Success Path Recipes (used as search key)
|
|
241
|
+
* "content" is REQUIRED — the main actionable content. For a Success Path Recipe, this is the compact replay recipe: applies-when context, start point, ordered actions, necessary constraints, verification, and detour to skip. MUST satisfy both joint requirements (grounded in conversation evidence AND generalized to apply in other repos). See Content Grounding Rules.
|
|
242
|
+
* Each playbook MUST correspond to a triggering agent behavior OR a successful task completion in the trajectory
|
|
243
|
+
* Vague, stylistic, or unanchored advice is invalid for BOTH categories
|
|
244
|
+
* Each entry must describe a **distinct, independent** policy or recipe
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
active: true
|
|
3
3
|
description: "System prompt for resumable expert playbook extraction by comparing agent vs expert responses — simplified schema without instruction/pitfall"
|
|
4
|
-
changelog: "v3.3.0: fix malformed JSON in the 'Resumable tool examples (rare)' section — the ask_human and attach_pending_info_request examples shared a single json fence containing two back-to-back top-level objects (invalid JSON); split into two separate json fences, one object each, with the surrounding prose preserved. No schema change. v3.2.0: adds emergent skill-convention guidance for structuring multi-aspect playbook content as a small set of grouped do/avoid rules (no schema change). v3.1.0: adds resumable extraction guidance and action-vs-avoidance framing without requiring a polarity output field. (in-place 2026-05-30: deprecated and removed blocking_issue.) (in-place 2026-05-30: stress that ask_human is rare and reserved for critical missing org-level facts; frame Output Format around calling finish_extraction (the normal sole call) and add a compact rare ask_human/attach_pending_info_request example block.) (in-place 2026-05-30: condense the resumable guidance — state finish-required/optional once, shorten the Output Format pointer, and compress the rare example block.)"
|
|
4
|
+
changelog: "v3.3.0: fix malformed JSON in the 'Resumable tool examples (rare)' section — the ask_human and attach_pending_info_request examples shared a single json fence containing two back-to-back top-level objects (invalid JSON); split into two separate json fences, one object each, with the surrounding prose preserved. No schema change. v3.2.0: adds emergent skill-convention guidance for structuring multi-aspect playbook content as a small set of grouped do/avoid rules (no schema change). v3.1.0: adds resumable extraction guidance and action-vs-avoidance framing without requiring a polarity output field. (in-place 2026-05-30: deprecated and removed blocking_issue.) (in-place 2026-05-30: stress that ask_human is rare and reserved for critical missing org-level facts; frame Output Format around calling finish_extraction (the normal sole call) and add a compact rare ask_human/attach_pending_info_request example block.) (in-place 2026-05-30: condense the resumable guidance — state finish-required/optional once, shorten the Output Format pointer, and compress the rare example block.) (in-place 2026-06-03: consolidate and shorten the ask_human condition: ask only for missing shared context needed to know what to do, while still finishing extraction.) (in-place 2026-06-03: frame finish_extraction as the final completion tool and pending-info tools as intermediate.) (in-place 2026-06-03: clarify that empty finish_extraction alone must not replace ask_human when the ask_human condition applies.) (in-place 2026-06-04: clarify ask_human and attach_pending_info_request are alternatives for the same gap, not a sequence.)"
|
|
5
5
|
variables:
|
|
6
6
|
- agent_context_prompt
|
|
7
7
|
- extraction_definition_prompt
|
|
@@ -10,12 +10,22 @@ You are an expert alignment policy mining assistant. Your job is to compare an A
|
|
|
10
10
|
|
|
11
11
|
## Resumable Extraction Mode
|
|
12
12
|
|
|
13
|
-
When tool calling is available,
|
|
13
|
+
When tool calling is available, tools have two roles:
|
|
14
14
|
|
|
15
|
-
- `ask_human`
|
|
16
|
-
-
|
|
15
|
+
- **Intermediate tools:** `ask_human` and `attach_pending_info_request` gather missing context before finalizing.
|
|
16
|
+
- **Final completion tool:** `finish_extraction` commits the playbooks for this run. Call it once, after any needed intermediate tool calls.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Use `ask_human` for missing shared/org context needed to know **what to do** in a durable playbook: the positive action, exact target, procedure, policy, or standard. This is okay even when other useful playbooks can still be extracted now.
|
|
19
|
+
|
|
20
|
+
Choose exactly one intermediate path per missing fact: use `attach_pending_info_request` when Prior Knowledge already lists a matching pending request; otherwise use `ask_human`. Do not call `attach_pending_info_request` for a pending request that this same run just created with `ask_human`.
|
|
21
|
+
|
|
22
|
+
Do not ask for user-scoped/private facts, context derivable from the comparison, agent context, or Prior Knowledge, complete avoidance-only rules, or merely nice-to-have details.
|
|
23
|
+
|
|
24
|
+
If an intermediate tool is needed, call exactly one of the two intermediate tools before `finish_extraction`. Then finalize the current run with any independently valid playbooks now, including avoidance rules; if none are valid without the answer, finalize with `{{"playbooks": []}}`.
|
|
25
|
+
|
|
26
|
+
When the `ask_human` condition applies, an `ask_human` tool call is required before finalization. Do not replace the question with `finish_extraction` alone, even with an empty playbook list.
|
|
27
|
+
|
|
28
|
+
Tool-call discipline: create actual tool calls; do not merely write "call ask_human" inside a playbook's `content`, `rationale`, or plain text, and do not invent missing "what to do" details.
|
|
19
29
|
|
|
20
30
|
AGENT CONTEXT
|
|
21
31
|
{agent_context_prompt}
|
|
@@ -78,7 +88,7 @@ When the guidance for a playbook covers multiple steps or sub-aspects of a task,
|
|
|
78
88
|
|
|
79
89
|
## Output Format
|
|
80
90
|
|
|
81
|
-
Deliver your result by calling the `finish_extraction
|
|
91
|
+
Deliver your result by calling the final completion tool, `finish_extraction`, with the JSON object below as its single argument — do not write it as a plain-text reply. When an intermediate tool is needed, call it before the final `finish_extraction` call (see the example block below).
|
|
82
92
|
|
|
83
93
|
The object has a single key `"playbooks"` whose value is a list of zero or more entries:
|
|
84
94
|
|
|
@@ -104,9 +114,9 @@ If no meaningful differences exist (agent and expert are substantively aligned a
|
|
|
104
114
|
|
|
105
115
|
**Never split a single policy across multiple entries; never merge two independent policies into one.**
|
|
106
116
|
|
|
107
|
-
### Resumable tool examples
|
|
117
|
+
### Resumable tool examples
|
|
108
118
|
|
|
109
|
-
|
|
119
|
+
When the `ask_human` condition above applies, first call `ask_human` as a tool call:
|
|
110
120
|
```json
|
|
111
121
|
{{"question": "What is this org's canonical standard for <the undetermined fact>? The expert response assumes it but the comparison never states it.", "answer_format": "concise name / value", "tags": ["org-standard"]}}
|
|
112
122
|
```
|
|
@@ -114,7 +124,7 @@ or `attach_pending_info_request` if Prior Knowledge already lists that exact pen
|
|
|
114
124
|
```json
|
|
115
125
|
{{"pending_tool_call_id": "ptc_7f3a91", "why_relevant": "Same undecided org standard; resume when answered."}}
|
|
116
126
|
```
|
|
117
|
-
— then
|
|
127
|
+
— then call `finish_extraction` as the final completion tool. Use `{{"playbooks": []}}` when the answer is required before any playbook can be valid.
|
|
118
128
|
|
|
119
129
|
## Rules
|
|
120
130
|
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# server/services
|
|
2
|
+
Description: Core business-logic layer — LLM orchestration, extraction, evaluation, optimization, search preparation, storage access, and long-running operation state.
|
|
3
|
+
|
|
4
|
+
> This is a directory-local index. For the full request flow, workflow tables (versioning, generation modes, cluster change detection), and the `OperationStateManager` use cases, see the parent [server README](../README.md#services).
|
|
5
|
+
|
|
6
|
+
**Service Boundary**: services own the LLM/extraction/evaluation/storage logic; API endpoints only authenticate, build `RequestContext`, and delegate into `Reflexio` or a focused service helper.
|
|
7
|
+
|
|
8
|
+
## Orchestration & Base Infrastructure
|
|
9
|
+
|
|
10
|
+
| File | Purpose |
|
|
11
|
+
|------|---------|
|
|
12
|
+
| `generation_service.py` | `GenerationService` — saves interactions, runs profile + playbook generation in parallel (ThreadPoolExecutor), schedules deferred evaluation when `session_id` is present. |
|
|
13
|
+
| `base_generation_service.py` | `BaseGenerationService` — abstract base; the **Service Pattern** (load configs → create actors → run in parallel → save results). Per-extractor timeout `EXTRACTOR_TIMEOUT_SECONDS = 300`. |
|
|
14
|
+
| `operation_state_utils.py` | `OperationStateManager` — all `_operation_state` access (progress, concurrency locks, extractor/aggregator bookmarks, cluster fingerprints, cancellation). |
|
|
15
|
+
| `extractor_config_utils.py`, `extractor_interaction_utils.py` | Filter extractors by source / `allow_manual_trigger` / names; per-extractor stride + window + bookmark handling. |
|
|
16
|
+
| `deduplication_utils.py`, `service_utils.py`, `embedding_text.py` | LLM dedup helpers (used by `ProfileDeduplicator` + `PlaybookConsolidator`), message construction / JSON extraction / response logging, embedding text builders. |
|
|
17
|
+
|
|
18
|
+
## Generation Services
|
|
19
|
+
|
|
20
|
+
| Directory | Entry class | Key files |
|
|
21
|
+
|-----------|-------------|-----------|
|
|
22
|
+
| `profile/` | `ProfileGenerationService` | `profile_extractor.py`, `profile_deduplicator.py`, `profile_updater.py` |
|
|
23
|
+
| `playbook/` | `PlaybookGenerationService` | `playbook_extractor.py`, `playbook_consolidator.py`, `playbook_aggregator.py` (cluster-fingerprint change detection) — has its own [README](playbook/README.md) |
|
|
24
|
+
| `agent_success_evaluation/` | `AgentSuccessEvaluationService` | `agent_success_evaluator.py` (session-level), `delayed_group_evaluator.py` (`GroupEvaluationScheduler`, 10-min defer), `group_evaluation_runner.py`, `regen_jobs.py` |
|
|
25
|
+
| `reflection/` | `ReflectionService` | `reflection_extractor.py` — post-horizon reflection; runs **before** extraction so extractors read post-reflection state |
|
|
26
|
+
|
|
27
|
+
## Async Extraction
|
|
28
|
+
|
|
29
|
+
| Directory | Purpose |
|
|
30
|
+
|-----------|---------|
|
|
31
|
+
| `extraction/` | Resumable extraction agent: `resumable_agent.py`, `resume_scheduler.py`, `resume_worker.py`, `pending_tool_call_dispatch.py` (`ask_human`), `tools.py`, `plan.py`, `agent_run_records.py`, `invariants.py`. Long-horizon / tool-mediated extraction continues outside the request path. |
|
|
32
|
+
|
|
33
|
+
## Evaluation, Search & Integrations
|
|
34
|
+
|
|
35
|
+
| Path | Purpose |
|
|
36
|
+
|------|---------|
|
|
37
|
+
| `shadow_comparison/` | `ShadowComparisonJudge` — per-turn regular-vs-shadow verdicts written to a separate table (session-level shadow was retracted due to trajectory contamination). |
|
|
38
|
+
| `evaluation_overview/` | Dashboard rollups: `service.py`, `hero_state.py`, `distribution.py`, `group_aggregation.py`, `rule_attribution.py`, `shadow_aggregation.py`, `eval_sampler.py`. |
|
|
39
|
+
| `playbook_optimizer/` | Scenario-based playbook optimization: `optimizer.py`, `scheduler.py`, `rollout.py`, `judge.py`, `scenario_resolver.py`, `gepa_adapter.py`, `assistant_webhook.py`. |
|
|
40
|
+
| `braintrust/` | Braintrust export/sync: `service.py`, `client.py`, `_cron.py`, `_encryption.py`. |
|
|
41
|
+
| `pre_retrieval/` | `QueryReformulator` (`_query_reformulator.py`) + `_document_expander.py` — query rewrite & doc expansion for recall. |
|
|
42
|
+
| `unified_search_service.py` | `run_unified_search()` — two-phase parallel search across profiles / agent playbooks / user playbooks. |
|
|
43
|
+
| `retrieval/` | `relevance_floor.py` — result relevance thresholding. |
|
|
44
|
+
|
|
45
|
+
## Persistence & Config
|
|
46
|
+
|
|
47
|
+
| Path | Purpose |
|
|
48
|
+
|------|---------|
|
|
49
|
+
| `storage/` | `storage_base/` (`BaseStorage` split by domain) + `sqlite_storage/` + `retention*.py`. Access via `request_context.storage` only. |
|
|
50
|
+
| `configurator/` | `DefaultConfigurator` — loads YAML config and creates the storage backend. |
|
|
51
|
+
|
|
52
|
+
## Key Rules
|
|
53
|
+
|
|
54
|
+
- **NEVER instantiate services bypassing the Service Pattern** — extend `BaseGenerationService`; load YAML configs, create actors, run in parallel, save to storage.
|
|
55
|
+
- **NEVER import storage implementations directly** — use `request_context.storage` (`BaseStorage`).
|
|
56
|
+
- **ALWAYS use `LiteLLMClient`** for completions/embeddings and `request_context.prompt_manager.render_prompt(...)` for prompts — no hardcoded prompts, no direct OpenAI/Claude clients.
|
|
57
|
+
- **All `_operation_state` writes go through `OperationStateManager`** — don't touch the table directly (it backs locks, bookmarks, progress, and cancellation).
|
|
58
|
+
- **`tool_can_use` lives at root `Config`** — shared by playbook extraction and success evaluation, not per-service.
|
|
@@ -172,11 +172,7 @@ def run_group_evaluation(
|
|
|
172
172
|
prior_rows = storage.get_agent_success_evaluation_results( # type: ignore[reportOptionalMemberAccess]
|
|
173
173
|
limit=10000, agent_version=agent_version
|
|
174
174
|
)
|
|
175
|
-
old_result_ids = [
|
|
176
|
-
r.result_id
|
|
177
|
-
for r in prior_rows
|
|
178
|
-
if r.session_id == session_id
|
|
179
|
-
]
|
|
175
|
+
old_result_ids = [r.result_id for r in prior_rows if r.session_id == session_id]
|
|
180
176
|
|
|
181
177
|
logger.info(
|
|
182
178
|
"Running group evaluation for session=%s with %d requests and %d interactions"
|
|
@@ -492,7 +492,7 @@ class BaseGenerationService(
|
|
|
492
492
|
reproduce the original publish (user_id, request_id, agent_version,
|
|
493
493
|
source, force_extraction, etc.). Without this, the rerun runs with the
|
|
494
494
|
wrong holder's request and the queued user's interactions are silently
|
|
495
|
-
skipped (R2
|
|
495
|
+
skipped (R2).
|
|
496
496
|
|
|
497
497
|
Returns ``None`` to opt out — the queue then stores only the
|
|
498
498
|
request_id and the rerun falls back to the original holder's request,
|
|
@@ -580,7 +580,7 @@ class BaseGenerationService(
|
|
|
580
580
|
|
|
581
581
|
# Try to acquire lock — pass the serialized payload so blocked
|
|
582
582
|
# publishes land in the queue with their own data attached. This is
|
|
583
|
-
# the fix for R2
|
|
583
|
+
# the fix for R2: without the payload, the
|
|
584
584
|
# rerun re-uses the holder's request and the queued users' batches
|
|
585
585
|
# never get extracted.
|
|
586
586
|
my_payload = self._serialize_request_for_queue(request)
|
|
@@ -857,6 +857,10 @@ class BaseGenerationService(
|
|
|
857
857
|
f"for {self._get_service_name()} identifier={identifier}"
|
|
858
858
|
)
|
|
859
859
|
logger.error(error_msg)
|
|
860
|
+
self._fail_active_extraction_runs(
|
|
861
|
+
extractor_kind=get_extractor_name(extractor_config),
|
|
862
|
+
last_error=error_msg,
|
|
863
|
+
)
|
|
860
864
|
raise ExtractorExecutionError(error_msg) from exc
|
|
861
865
|
except Exception as exc:
|
|
862
866
|
self._last_extractor_run_stats = {"total": 1, "failed": 1, "timed_out": 0}
|
|
@@ -870,6 +874,44 @@ class BaseGenerationService(
|
|
|
870
874
|
if executor is not None:
|
|
871
875
|
executor.shutdown(wait=False, cancel_futures=True)
|
|
872
876
|
|
|
877
|
+
def _fail_active_extraction_runs(
|
|
878
|
+
self,
|
|
879
|
+
*,
|
|
880
|
+
extractor_kind: str,
|
|
881
|
+
last_error: str,
|
|
882
|
+
) -> None:
|
|
883
|
+
"""Mark active agent-run rows failed when the service timeout fires."""
|
|
884
|
+
if self.storage is None or self.service_config is None:
|
|
885
|
+
return
|
|
886
|
+
request_id = getattr(self.service_config, "request_id", None)
|
|
887
|
+
if not request_id:
|
|
888
|
+
return
|
|
889
|
+
user_id = getattr(self.service_config, "user_id", None)
|
|
890
|
+
try:
|
|
891
|
+
failed_count = self.storage.fail_running_agent_runs_for_request(
|
|
892
|
+
org_id=self.request_context.org_id,
|
|
893
|
+
extractor_kind=extractor_kind,
|
|
894
|
+
user_id=user_id,
|
|
895
|
+
request_id=request_id,
|
|
896
|
+
last_error=last_error,
|
|
897
|
+
)
|
|
898
|
+
except NotImplementedError:
|
|
899
|
+
return
|
|
900
|
+
except Exception as exc: # noqa: BLE001 - keep timeout error primary
|
|
901
|
+
logger.warning(
|
|
902
|
+
"Failed to mark timed-out %s agent runs failed: %s",
|
|
903
|
+
extractor_kind,
|
|
904
|
+
exc,
|
|
905
|
+
)
|
|
906
|
+
return
|
|
907
|
+
if failed_count:
|
|
908
|
+
logger.warning(
|
|
909
|
+
"Marked %d timed-out %s agent run(s) failed for request_id=%s",
|
|
910
|
+
failed_count,
|
|
911
|
+
extractor_kind,
|
|
912
|
+
request_id,
|
|
913
|
+
)
|
|
914
|
+
|
|
873
915
|
def _finalize_extraction_runs(self) -> None:
|
|
874
916
|
if self.storage is None:
|
|
875
917
|
return
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Canonical text and prefixes used for vector embeddings."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from reflexio.models.api_schema.service_schemas import (
|
|
8
|
+
AgentPlaybook,
|
|
9
|
+
AgentSuccessEvaluationResult,
|
|
10
|
+
Interaction,
|
|
11
|
+
UserPlaybook,
|
|
12
|
+
UserProfile,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
SEARCH_DOCUMENT_PREFIX = "search_document: "
|
|
16
|
+
SEARCH_QUERY_PREFIX = "search_query: "
|
|
17
|
+
|
|
18
|
+
EmbeddingTextEntity = (
|
|
19
|
+
Interaction
|
|
20
|
+
| UserProfile
|
|
21
|
+
| UserPlaybook
|
|
22
|
+
| AgentPlaybook
|
|
23
|
+
| AgentSuccessEvaluationResult
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def embedding_text(entity: EmbeddingTextEntity) -> str:
|
|
28
|
+
"""Return the exact text used for an entity's stored embedding."""
|
|
29
|
+
if isinstance(entity, Interaction):
|
|
30
|
+
return f"{entity.content}\n{entity.user_action_description}"
|
|
31
|
+
if isinstance(entity, UserProfile):
|
|
32
|
+
parts = [entity.content]
|
|
33
|
+
if entity.custom_features:
|
|
34
|
+
parts.append(str(entity.custom_features))
|
|
35
|
+
return "\n".join(parts)
|
|
36
|
+
if isinstance(entity, (UserPlaybook, AgentPlaybook)):
|
|
37
|
+
return entity.trigger or entity.content
|
|
38
|
+
if isinstance(entity, AgentSuccessEvaluationResult):
|
|
39
|
+
return " ".join(
|
|
40
|
+
part
|
|
41
|
+
for part in (entity.failure_type, entity.failure_reason)
|
|
42
|
+
if part and part.strip()
|
|
43
|
+
)
|
|
44
|
+
raise TypeError(f"Unsupported embedding text entity: {type(entity).__name__}")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def embedding_input(
|
|
48
|
+
text: str, *, purpose: Literal["document", "query"] = "document"
|
|
49
|
+
) -> str:
|
|
50
|
+
"""Apply the asymmetric search prefix used before embedding calls.
|
|
51
|
+
|
|
52
|
+
``purpose`` must be ``"document"`` or ``"query"``; any other value raises so a
|
|
53
|
+
misspelled call site fails fast instead of silently writing or searching the
|
|
54
|
+
wrong vector space.
|
|
55
|
+
"""
|
|
56
|
+
if purpose == "document":
|
|
57
|
+
return SEARCH_DOCUMENT_PREFIX + text
|
|
58
|
+
if purpose == "query":
|
|
59
|
+
return SEARCH_QUERY_PREFIX + text
|
|
60
|
+
raise ValueError(
|
|
61
|
+
f"Unknown embedding purpose {purpose!r}; expected 'document' or 'query'"
|
|
62
|
+
)
|
package/plugin/vendor/reflexio/reflexio/server/services/extraction/pending_tool_call_dispatch.py
CHANGED
|
@@ -8,7 +8,7 @@ from dataclasses import dataclass, field
|
|
|
8
8
|
from datetime import UTC, datetime, timedelta
|
|
9
9
|
from typing import Annotated, Any
|
|
10
10
|
|
|
11
|
-
from pydantic import BaseModel, Field
|
|
11
|
+
from pydantic import BaseModel, Field, field_validator
|
|
12
12
|
|
|
13
13
|
from reflexio.models.config_schema import PendingToolCallConfig
|
|
14
14
|
from reflexio.server.llm.tools import (
|
|
@@ -38,6 +38,13 @@ class AskHumanArgs(BaseModel):
|
|
|
38
38
|
answer_format: str | None = None
|
|
39
39
|
tags: list[str] = Field(default_factory=list)
|
|
40
40
|
|
|
41
|
+
@field_validator("tags", mode="before")
|
|
42
|
+
@classmethod
|
|
43
|
+
def _coerce_tags(cls, value: Any) -> Any:
|
|
44
|
+
if isinstance(value, str):
|
|
45
|
+
return [tag.strip() for tag in value.split(",") if tag.strip()]
|
|
46
|
+
return value
|
|
47
|
+
|
|
41
48
|
|
|
42
49
|
class AttachPendingInfoRequestArgs(BaseModel):
|
|
43
50
|
"""Attach this run to a relevant pending Prior Knowledge request."""
|