协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
apify-competitor-intelligence【开发与工程】Implements intelligent apify competitor intelligence with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: apify-competitor-intelligence compatibility: opencode completeness: 95 content-types:
Orchestrates intelligent skill selection and execution for apify competitor intelligence workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.
┌───────────────────────────────────────────────────────────────────────────────┐ │ Orchestration Flow │ └───────────────────────────────────────────────────────────────────────────────┘
User Request ↓ ┌─────────────────┐ │ Parse Request │ │ & Extract │ │ Features │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Evaluate Available Skills │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Skill A │ │ Skill B │ │ Skill C │ │ │ │ - Match Score│ │ - Match Score│ │ - Match Score│ │ │ │ - Confidence │ │ - Confidence │ │ - Confidence │ │ │ │ - History │ │ - History │ │ - History │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ │ │ │ │ └─────────────────┴─────────────────┘ │ │ ↓ │ │ Select Best Skill │ └─────────────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────┐ │ Execute Skill │ └────────┬────────┘ ↓ ┌─────────────────┐ │ Handle Result │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Error Handling & Fallback │ │ │ │ Success? ────────► Return Result │ │ │ │ Fail? ────────┐ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ Fallback Chain │ │ │ │ │ │ │ │ 1. Retry with adjusted parameters │ │ │ │ 2. Try Alternative Skill (if available) │ │ │ │ 3. Defer to Human Operator (if critical) │ │ │ │ 4. Log & Return Error │ │ │ └──────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘
Use this skill when:
Avoid this skill for:
Parse and Analyze Request - Extract intent, entities, and constraints from user input. Checkpoint: All required parameters must be present and in valid format before proceeding.
Score Available Skills - Calculate match scores using multi-factor algorithm:
Checkpoint: Skip to fallback if no skill scores above threshold.
Select Optimal Skill - Choose skill with highest score that meets minimum confidence. Checkpoint: Verify skill has not been disabled or deprecated.
Execute with Fallback - Run skill execution wrapped in retry and fallback logic. Checkpoint: Log all execution attempts for audit trail.
Return or Fallback - Either return successful result or apply fallback chain:
related-skillsCheckpoint: Record outcome with timing and confidence metadata.
def evaluate_apify_actors_for_competitor(
competitor_url: str,
available_actors: List[Dict],
min_confidence: float = 0.7
) -> Optional[Dict]:
"""Evaluate Apify actors to find the best fit for competitor intelligence.
Scores actors based on URL compatibility, historical success rate,
and current actor status (active/deprecated).
"""
# Guard clause - Early Exit (Law 1)
if not competitor_url or not available_actors:
raise ValueError("Competitor URL and actor list are required")
parsed_domain = urlparse(competitor_url).netloc
best_actor = None
best_score = 0.0
for actor in available_actors:
# Parse input - Make Illegal States Unrepresentable (Law 2)
domain_match = _check_domain_compatibility(parsed_domain, actor.get("supported_domains", []))
success_rate = actor.get("stats", {}).get("success_rate", 0.0)
status = actor.get("status", "ACTIVE")
if status != "ACTIVE":
continue
score = (domain_match * 0.6) + (success_rate * 0.4)
if score > best_score and score >= min_confidence:
best_score = score
best_actor = actor
if best_actor is None:
return None
# Atomic Predictability (Law 3) - Return new dict, don't mutate
return {
"actor_id": best_actor["id"],
"actor_name": best_actor["name"],
"confidence": best_score,
"input_config": _build_default_input(competitor_url, best_actor),
"fallback_actors": [a["id"] for a in available_actors if a["id"] != best_actor["id"]][:2]
}
def run_apify_actor_with_fallback(
actor_config: Dict,
max_retries: int = 2
) -> Dict:
"""Execute an Apify actor with domain-specific fallback handling.
Implements Fail Fast, Fail Loud (Law 4):
- Invalid inputs halt immediately with descriptive errors
- Rate limits trigger exponential backoff
- Actor failures cascade to fallback actors
Args:
actor_config: Selected actor metadata and input configuration
max_retries: Maximum retry attempts before fallback
Returns:
Execution result with metadata (success, timing, confidence)
"""
actor_id = actor_config["actor_id"]
input_config = actor_config["input_config"]
fallback_actors = actor_config.get("fallback_actors", [])
for attempt in range(max_retries + 1):
try:
# Execute via Apify API client
run = apify_client.actor(actor_id).call(input=input_config)
result = apify_client.dataset(run["defaultDatasetId"]).get_items()
# Success - Atomic Predictability (Law 3)
return {
"success": True,
"actor_executed": actor_config["actor_name"],
"data_count": len(result),
"attempts": attempt + 1,
"latency_ms": run.get("stats", {}).get("actuatorSecondsTotal", 0) * 1000
}
except apify.ApiError as e:
if e.status_code == 429:
time.sleep(2 ** attempt) # Exponential backoff
continue
elif e.status_code == 400:
# Invalid input - sanitize and retry
input_config = _sanitize_input_for_actor(actor_id, input_config)
continue
else:
# Fail Fast - Don't try to patch bad data (Law 4)
raise ApifyExecutionError(f"Actor {actor_id} failed: {e}") from e
# All retries exhausted - Fail Loud (Law 4)
if fallback_actors:
return run_apify_actor_with_fallback({
**actor_config,
"actor_id": fallback_actors[0],
"input_config": input_config
}, max_retries=1)
raise ApifyExecutionError(f"All fallback actors exhausted for {actor_id}")
code-philosophy (5 Laws of Elegant Defense) in all logicWhen applying this skill, produce:
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.
| Skill | Purpose | |