-
Notifications
You must be signed in to change notification settings - Fork 11
feat(subtasks): segment trajectories into subtasks before tip generation #198
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
visahak
merged 19 commits into
AgentToolkit:main
from
jayaramkr:trajectory-segmentation
Apr 28, 2026
Merged
Changes from 4 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
ff58475
feat(tips): segment trajectories into subtasks before tip generation
9bfe6cc
Merge branch 'main' into trajectory-segmentation
jayaramkr 64b9c13
fix(tips): address CodeRabbit review issues on trajectory segmentation
eee4ea6
Merge branch 'main' into trajectory-segmentation
jayaramkr 80d1379
Merge branch 'main' into trajectory-segmentation
jayaramkr 972c113
fix(tips): skip subtasks with empty step ranges instead of calling LLM
7cda0f8
fix(tips): downgrade skip log to debug and fall back when all subtask…
d0a885b
style(tips): apply ruff formatting
c72ee0c
test(e2e): add segmentation e2e test with appworld venmo trajectory f…
8678bc4
fix(tips): fall through to full-trajectory when fewer than 2 valid su…
cb3a7bf
Merge branch 'main' into trajectory-segmentation
jayaramkr b3b9efb
chore: update secrets baseline for appworld trajectory fixture (fake …
a5ad051
chore: restore secrets baseline with fixture false positives properly…
41f90d0
chore: scrub fake tokens from trajectory fixture to pass detect-secrets
94af5f7
Merge branch 'main' into trajectory-segmentation
jayaramkr bfd046d
fix(tests): rename e2e segmentation test to avoid basename collision …
2eddd11
Merge remote-tracking branch 'upstream/main' into trajectory-segmenta…
9d290fe
fix(guidelines): apply clean_llm_response to constrained branch and s…
b568e0c
docs(segmentation): clarify start_step/end_step are indices into filt…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| Analyze this AI agent trajectory and segment it into logical subtasks. | ||
|
|
||
| # Trajectory | ||
| **Total Steps:** {{num_steps}} | ||
|
|
||
| {{trajectory_summary}} | ||
|
|
||
| # Your Task | ||
| Identify the distinct logical phases of work the agent performed. For each phase, produce a generalized description that would apply to *any* agent performing a similar operation — strip out specific values, user names, IDs, and task-specific details. | ||
|
|
||
| **Good description:** "Authenticate with a web service using stored credentials" | ||
| **Bad description:** "Login to Venmo using tr_solo@gmail.com" | ||
|
|
||
| **Guidelines:** | ||
| - Group tightly related steps together (e.g., all authentication steps form one subtask) | ||
| - Separate distinct logical phases (discovery, authentication, data retrieval, computation, output) | ||
| - `start_step` and `end_step` are the step numbers shown in the trajectory above (inclusive) | ||
| - Prefer contiguous, non-overlapping ranges where the trajectory allows it | ||
| - A single step can be its own subtask if it represents a clearly distinct phase | ||
| - `purpose` should describe what this subtask achieves, not how it does it | ||
|
|
||
| {% if not constrained_decoding_supported %} | ||
| **Output Format (JSON):** | ||
| ```json | ||
| { | ||
| "subtasks": [ | ||
| { | ||
| "generalized_description": "Authenticate with a web service using stored credentials", | ||
| "start_step": 1, | ||
| "end_step": 4, | ||
| "purpose": "Obtain an access token to make authorized API calls" | ||
| }, | ||
| { | ||
| "generalized_description": "Retrieve and filter a list of records", | ||
| "start_step": 5, | ||
| "end_step": 9, | ||
| "purpose": "Fetch the target dataset and apply the required filters" | ||
| } | ||
| ] | ||
| } | ||
| ``` | ||
|
|
||
| Return ONLY the JSON object, no other text. | ||
| {% endif %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import json | ||
| import logging | ||
| from json import JSONDecodeError | ||
| from pathlib import Path | ||
|
|
||
| import litellm | ||
| from jinja2 import Template | ||
| from litellm import completion, get_supported_openai_params, supports_response_schema | ||
| from pydantic import ValidationError | ||
|
|
||
| from altk_evolve.config.llm import llm_settings | ||
| from altk_evolve.schema.tips import SegmentationResponse, SubtaskSegment | ||
| from altk_evolve.utils.utils import clean_llm_response | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _SEGMENT_TEMPLATE = Template((Path(__file__).parent / "prompts/segment_trajectory.jinja2").read_text()) | ||
|
|
||
|
|
||
| def segment_trajectory(messages: list[dict]) -> list[SubtaskSegment]: | ||
| """Segment a trajectory into logical subtasks with generalized descriptions. | ||
|
|
||
| Returns an empty list on failure — callers fall back to full-trajectory tip generation. | ||
| """ | ||
| # Import here to avoid circular import (tips.py imports this module) | ||
| from altk_evolve.llm.tips.tips import parse_openai_agents_trajectory | ||
|
|
||
| trajectory_data = parse_openai_agents_trajectory(messages) | ||
|
|
||
| supported_params = get_supported_openai_params( | ||
| model=llm_settings.tips_model, | ||
| custom_llm_provider=llm_settings.custom_llm_provider, | ||
| ) | ||
| supports_response_format = supported_params and "response_format" in supported_params | ||
| response_schema_enabled = supports_response_schema( | ||
| model=llm_settings.tips_model, | ||
| custom_llm_provider=llm_settings.custom_llm_provider, | ||
| ) | ||
| constrained_decoding_supported = bool(supports_response_format and response_schema_enabled) | ||
|
|
||
| prompt = _SEGMENT_TEMPLATE.render( | ||
| trajectory_summary=trajectory_data["trajectory_summary"], | ||
| num_steps=trajectory_data["num_steps"], | ||
| constrained_decoding_supported=constrained_decoding_supported, | ||
| ) | ||
|
|
||
| litellm.enable_json_schema_validation = constrained_decoding_supported | ||
|
|
||
| last_error: Exception | None = None | ||
| for attempt in range(3): | ||
| try: | ||
| if constrained_decoding_supported: | ||
| clean_response = ( | ||
| completion( | ||
| model=llm_settings.tips_model, | ||
| messages=[{"role": "user", "content": prompt}], | ||
| response_format=SegmentationResponse, | ||
| custom_llm_provider=llm_settings.custom_llm_provider, | ||
| ) | ||
| .choices[0] | ||
| .message.content | ||
| ) | ||
| else: | ||
| raw = ( | ||
| completion( | ||
| model=llm_settings.tips_model, | ||
| messages=[{"role": "user", "content": prompt}], | ||
| custom_llm_provider=llm_settings.custom_llm_provider, | ||
| ) | ||
| .choices[0] | ||
| .message.content | ||
| ) | ||
| clean_response = clean_llm_response(raw) | ||
|
|
||
| if not clean_response: | ||
| logger.debug(f"Segmentation attempt {attempt + 1}: empty response") | ||
| continue | ||
|
|
||
| subtasks = SegmentationResponse.model_validate(json.loads(clean_response)).subtasks | ||
| return subtasks | ||
|
|
||
| except (JSONDecodeError, ValidationError) as e: | ||
| logger.debug(f"Segmentation attempt {attempt + 1} failed: {e}") | ||
| last_error = e | ||
| continue | ||
|
|
||
| logger.warning(f"Failed to segment trajectory after 3 attempts: {last_error}") | ||
| return [] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.