Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ High-density product roadmap, engineering milestones, and open-source integratio
- *Deep Integration & Functional Extension*: Automated W3C Trace Context propagation across all background tasks, subagent delegations, and external CLI subprocesses; in-process metric stream aggregation via OpenTelemetry Metrics SDK; baggage propagation for multi-persona review sessions.
- *Code Optimization & Performance Acceleration*: Replace ad-hoc timing and stopwatch counters with standardized, low-overhead in-memory span processors; eliminate unhandled span export exceptions during offline operations via bounded ring-buffered exporters.
- *Refactoring Potential & Legacy Elimination*: Refactor `src/devops_cli/telemetry/` into an unobtrusive decorator and context manager pattern; remove redundant manual span creation boilerplate; eliminate orphaned span traces.
- [ ] **Pydantic AI Structured Workflows, Prompt Caching & Client-Side Token Governance Research (P0 - Critical, Issue #320)**:
- [x] **Pydantic AI Structured Workflows, Prompt Caching & Client-Side Token Governance Research (P0 - Critical, Issue #320)**:
- *Context & Rationale*: AI inference routing and agent execution rely on bespoke HTTP callers, manual function call parsers, and custom retry loops that are prone to schema divergence and latency spikes.
- *Deep Integration & Functional Extension*: Native PydanticAI Agent workflows with dependency injection and typed tool definitions; prompt caching optimizations for Anthropic/OpenAI; client-side token-bucket rate governance; dynamic fallback cascades across LiteLLM, Portkey, LightLLM, and Ollama.
- *Code Optimization & Performance Acceleration*: Reduce prompt token billing and processing latency by up to 80% through prompt caching; eliminate JSON schema parsing failures via Pydantic v2 runtime validation; optimize streaming time-to-first-token.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Task 320: Pydantic AI Structured Workflows, Prompt Caching & Client-Side Token Governance Research

**Issue**: [#320](https://github.com/dan-petty/devops-cli/issues/320)
**PR**: None (Draft)
**Status**: Backlog
**PR**: Tracking PR targeting `release/v0.2.22`
**Status**: Completed
**Milestone**: `v0.2.22`
**Priority**: `priority/p0-critical`
**Scope**: `type/feature`, `scope/ai`, `priority/p0-critical`
Expand All @@ -14,10 +14,29 @@
AI inference routing and agent execution rely on bespoke HTTP callers, manual function call parsers, and custom retry loops that are prone to schema divergence and latency spikes.

#### Key Deliverables:
- Context & Rationale*: AI inference routing and agent execution rely on bespoke HTTP callers, manual function call parsers, and custom retry loops that are prone to schema divergence and latency spikes.
- Deep Integration & Functional Extension*: Native PydanticAI Agent workflows with dependency injection and typed tool definitions; prompt caching optimizations for Anthropic/OpenAI; client-side token-bucket rate governance; dynamic fallback cascades across LiteLLM, Portkey, LightLLM, and Ollama.
- Code Optimization & Performance Acceleration*: Reduce prompt token billing and processing latency by up to 80% through prompt caching; eliminate JSON schema parsing failures via Pydantic v2 runtime validation; optimize streaming time-to-first-token.
- Refactoring Potential & Legacy Elimination*: Refactor `src/devops_cli/ai/agent.py`, `controller.py`, and `gateway.py` to eliminate custom function calling parsers and fragile manual retry loops; adopt standardized PydanticAI streaming agents with typed tool registries.
- Unit and integration test coverage with structural tuple equality assertions.
- Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$.
- 100% passing across Gated CI validation suite (`uv run devops ci`).
- [x] **Context & Rationale**: Addressed bespoke HTTP callers and manual retry loops in AI inference and agent workflows.
- [x] **Deep Integration & Functional Extension**:
- Native PydanticAI Agent workflows with dependency injection and typed tool definitions via `DevOpsAgentContext` and `execute_structured_workflow` / `execute_structured_workflow_sync` in `src/devops_cli/ai/pydantic_ai_bridge.py`.
- Prompt caching optimizations for Anthropic / OpenAI via `inject_prompt_cache_points` and `create_cached_user_prompt` using `pydantic_ai.CachePoint`.
- Client-side token-bucket rate governance via `TokenBucketGovernance` and `TokenBudgetConfig` in `src/devops_cli/ai/governance.py` with automatic calculation of throttling delays and consumption tracking from `RunUsage`.
- Dynamic fallback cascades across LiteLLM, Portkey, LightLLM, and Ollama via `build_fallback_cascade_model` constructing `pydantic_ai.models.fallback.FallbackModel`, integrated into `GatewayRouter.build_pydantic_cascade_model`.
- [x] **Code Optimization & Performance Acceleration**:
- Prompt caching reduces prompt token processing latency and billing overhead.
- Token-bucket rate governor mitigates rate limit failures and smooths bursty LLM traffic.
- Dynamic fallback cascades guarantee uninterrupted execution across degraded or failing upstream inference endpoints.
- [x] **Refactoring Potential & Legacy Elimination**:
- Defined `CONST_AI_PROMPT_CACHE_TTL_5M`, `CONST_AI_PROMPT_CACHE_TTL_1H`, `CONST_AI_PROMPT_CACHE_TTLS`, `CONST_AI_CASCADE_PROVIDERS`, `CONST_AI_DEFAULT_CACHE_MARKER_KIND`, `DEFAULT_AI_TOKEN_BUCKET_CAPACITY`, `DEFAULT_AI_TOKEN_BUCKET_REFILL_RATE`, `DEFAULT_AI_PROMPT_CACHE_TTL`, and `DEFAULT_AI_USAGE_REQUEST_LIMIT` in `src/devops_cli/config/constants.py` and `src/devops_cli/config/defaults.py`.
- Exported `TokenBudgetConfig`, `TokenBucketGovernance`, `inject_prompt_cache_points`, `create_cached_user_prompt`, `build_fallback_cascade_model`, `execute_structured_workflow`, `execute_structured_workflow_sync` in `src/devops_cli/ai/__init__.py`.
- [x] **Testing & Verification**:
- Authored 10 unit tests with structural tuple equality assertions in `tests/test_pydantic_ai_workflows.py`.
- Verified prompt cache injection, token bucket consumption, budget configuration to `UsageLimits`, fallback cascade execution, structured workflow execution (sync and async), and gateway cascade builder.
- Maintained cyclomatic complexity $M \le 10$ and nesting depth $\le 5$.
- 100% passing across Gated CI validation suite (`uv run devops ci`).

---

## 2. Verification Summary

- **Unit Tests**: 10/10 passed in `tests/test_pydantic_ai_workflows.py`; all 53 AI tests passed in test suite.
- **Architectural Invariants**: Complexity check passed ($M \le 10$, nesting depth $\le 5$).
- **Gated CI Quality Gates**: All 10 gates passed locally via `uv run devops ci`.
22 changes: 22 additions & 0 deletions src/devops_cli/ai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,28 @@ def __getattr__(name: str) -> Any:
import devops_cli.ai.durable

return getattr(devops_cli.ai.durable, name)
if name in {
"TokenBudgetConfig",
"TokenBucketGovernance",
}:
import devops_cli.ai.governance

return getattr(devops_cli.ai.governance, name)
if name in {
"DevOpsAgentContext",
"build_fallback_cascade_model",
"create_cached_user_prompt",
"create_pydantic_ai_agent",
"execute_structured_workflow",
"execute_structured_workflow_sync",
"get_persona_pydantic_agent",
"inject_prompt_cache_points",
"is_pydantic_ai_available",
"resolve_pydantic_ai_model",
}:
import devops_cli.ai.pydantic_ai_bridge

return getattr(devops_cli.ai.pydantic_ai_bridge, name)
if name in {
"AgentRunError",
"ApprovalRequired",
Expand Down
16 changes: 16 additions & 0 deletions src/devops_cli/ai/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,22 @@ def probe_backend(
"models": models,
}

def build_pydantic_cascade_model(
self,
virtual_model: str = "devops-chat",
settings: Any = None,
model_concurrency: Any = None,
) -> Any:
"""Construct a PydanticAI FallbackModel chaining the primary route to its failover target."""
from devops_cli.ai.pydantic_ai_bridge import build_fallback_cascade_model

fallback_target = MODEL_FAILOVER_PAIRS.get(virtual_model, "devops-chat")
return build_fallback_cascade_model(
[virtual_model, fallback_target, "ollama"],
settings=settings,
model_concurrency=model_concurrency,
)


def _resolve_backend_url(config: AIConfig, clean_type: str, backend_url: str | None) -> str:
"""Resolve backend target URL from override or AIConfig defaults."""
Expand Down
153 changes: 153 additions & 0 deletions src/devops_cli/ai/governance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""Client-side token bucket rate governance and token budgeting for PydanticAI."""

from __future__ import annotations

import logging
import threading
import time
from decimal import Decimal
from typing import Any

from pydantic import BaseModel, ConfigDict, Field
from pydantic_ai.usage import RunUsage, UsageLimits

from devops_cli.config.defaults import (
DEFAULT_AI_TOKEN_BUCKET_CAPACITY,
DEFAULT_AI_TOKEN_BUCKET_REFILL_RATE,
DEFAULT_AI_USAGE_REQUEST_LIMIT,
)

logger = logging.getLogger(__name__)


class TokenBudgetConfig(BaseModel):
"""Declarative token and request budgeting configuration for AI agent workflows."""

model_config = ConfigDict(extra="forbid")

input_tokens_limit: int | None = None
output_tokens_limit: int | None = None
total_tokens_limit: int | None = None
per_request_input_tokens_limit: int | None = None
request_limit: int | None = Field(default=DEFAULT_AI_USAGE_REQUEST_LIMIT)
cost_limit: float | None = None
count_tokens_before_request: bool = False

def to_usage_limits(self) -> UsageLimits:
"""Convert configuration into native PydanticAI UsageLimits instance."""
cost_decimal = Decimal(str(self.cost_limit)) if self.cost_limit is not None else None
return UsageLimits(
input_tokens_limit=self.input_tokens_limit,
output_tokens_limit=self.output_tokens_limit,
total_tokens_limit=self.total_tokens_limit,
per_request_input_tokens_limit=self.per_request_input_tokens_limit,
request_limit=self.request_limit,
cost_limit=cost_decimal,
count_tokens_before_request=self.count_tokens_before_request,
)


class TokenBucketGovernance:
"""Thread-safe client-side token bucket rate governor and consumption tracker."""

def __init__(
self,
capacity: int = DEFAULT_AI_TOKEN_BUCKET_CAPACITY,
refill_rate: float = DEFAULT_AI_TOKEN_BUCKET_REFILL_RATE,
) -> None:
self.capacity: float = float(max(1, capacity))
self.refill_rate: float = float(max(0.1, refill_rate))
self.tokens: float = self.capacity
self.last_refill_timestamp: float = time.monotonic()
self.consumed_input_tokens: int = 0
self.consumed_output_tokens: int = 0
self.consumed_total_tokens: int = 0
self.total_requests: int = 0
self._lock = threading.Lock()

def _refill_unlocked(self, now: float) -> None:
"""Internal helper to replenish tokens based on elapsed monotonic time."""
elapsed = max(0.0, now - self.last_refill_timestamp)
self.tokens = min(self.capacity, self.tokens + (elapsed * self.refill_rate))
self.last_refill_timestamp = now

def available_tokens(self) -> float:
"""Return currently available tokens after monotonic replenishment."""
with self._lock:
self._refill_unlocked(time.monotonic())
return max(0.0, self.tokens)

def acquire_token_permit(self, estimated_tokens: int = 1) -> float:
"""Acquire token permits and calculate pacing delay in seconds if throttled."""
cost = float(max(1, estimated_tokens))
with self._lock:
now = time.monotonic()
self._refill_unlocked(now)
if self.tokens >= cost:
self.tokens -= cost
return 0.0

deficit = cost - self.tokens
self.tokens -= cost
delay = deficit / self.refill_rate
logger.debug(
"Token bucket throttled: deficit=%.1f, pacing_delay=%.3fs",
deficit,
delay,
)
return delay

def record_token_usage(
self,
input_tokens: int = 0,
output_tokens: int = 0,
request_count: int = 1,
) -> None:
"""Record consumed tokens and update internal telemetry counters."""
total = max(0, input_tokens) + max(0, output_tokens)
with self._lock:
self.consumed_input_tokens += max(0, input_tokens)
self.consumed_output_tokens += max(0, output_tokens)
self.consumed_total_tokens += total
self.total_requests += max(0, request_count)

def record_run_usage(self, usage: RunUsage) -> None:
"""Record usage directly from a completed PydanticAI RunUsage event."""
in_tok = getattr(usage, "input_tokens", 0) or 0
out_tok = getattr(usage, "output_tokens", 0) or 0
reqs = getattr(usage, "requests", 1) or 1
self.record_token_usage(
input_tokens=in_tok,
output_tokens=out_tok,
request_count=reqs,
)

def get_governance_telemetry(self) -> dict[str, Any]:
"""Produce structured governance telemetry dictionary."""
with self._lock:
self._refill_unlocked(time.monotonic())
return {
"capacity": self.capacity,
"refill_rate": self.refill_rate,
"available_tokens": max(0.0, round(self.tokens, 1)),
"consumed_input_tokens": self.consumed_input_tokens,
"consumed_output_tokens": self.consumed_output_tokens,
"consumed_total_tokens": self.consumed_total_tokens,
"total_requests": self.total_requests,
}

def reset(self) -> None:
"""Reset token bucket to full capacity and reset counters."""
with self._lock:
self.tokens = self.capacity
self.last_refill_timestamp = time.monotonic()
self.consumed_input_tokens = 0
self.consumed_output_tokens = 0
self.consumed_total_tokens = 0
self.total_requests = 0


__all__ = [
"TokenBucketGovernance",
"TokenBudgetConfig",
]
Loading
Loading