技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
apify-trend-analysis【数据与研究】Implements intelligent apify trend analysis with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: apify-trend-analysis compatibility: opencode completeness: 95 content-types:
Orchestrates intelligent skill selection and execution for apify trend analysis 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 select_apify_actor_for_trend(
request: Dict,
available_actors: List[Dict],
api_key: str
) -> Dict:
"""Select optimal Apify actor for trend analysis based on request parameters.
Evaluates actors by matching data source requirements, timeframe constraints,
and metric compatibility. Validates API key and actor availability.
"""
if not request.get("data_source") or not request.get("timeframe"):
raise ValueError("Request must include 'data_source' and 'timeframe'")
source = request["data_source"].lower()
timeframe = request["timeframe"]
target_metrics = request.get("metrics", ["volume", "price"])
best_match = None
best_score = 0.0
for actor in available_actors:
score = 0.0
if actor.get("data_source") == source:
score += 0.5
if actor.get("supported_timeframes") and timeframe in actor["supported_timeframes"]:
score += 0.3
if set(target_metrics).issubset(set(actor.get("supported_metrics", []))):
score += 0.2
if score > best_score:
best_score = score
best_match = actor
if best_score < 0.7:
return {"status": "fallback_required", "reason": "insufficient_actor_match"}
return {
"actor_id": best_match["actor_id"],
"input_config": {
"source": source,
"timeframe": timeframe,
"metrics": target_metrics,
"max_items": request.get("max_items", 100)
},
"confidence": best_score,
"validation": "passed"
}
def execute_apify_trend_analysis(
actor_config: Dict,
apify_client,
fallback_strategy: str = "cache_or_manual"
) -> Dict:
"""Execute Apify actor and process trend analysis results with fallback handling.
Handles API submission, run monitoring, result parsing, and implements
Apify-specific fallbacks (cached data, alternative actor, or manual review).
"""
try:
# Submit actor run with validated config
run = apify_client.actor(actor_config["actor_id"]).call_run(
input=actor_config["input_config"]
)
# Monitor until completion
run_info = apify_client.run(run["id"]).get()
if run_info["status"] != "SUCCEEDED":
raise RuntimeError(f"Apify run failed: {run_info['status']}")
# Fetch and parse trend data
dataset = apify_client.dataset(run_info["defaultDatasetId"]).list_items()
trend_records = [item for item in dataset if item.get("timestamp")]
if not trend_records:
raise ValueError("No trend data returned from Apify actor")
# Process and aggregate trends
processed_trends = _aggregate_trend_metrics(trend_records)
return {
"status": "success",
"actor_run_id": run["id"],
"trend_data": processed_trends,
"record_count": len(trend_records),
"confidence": 0.95
}
except apify_client.errors.ApiError as e:
# Apify-specific fallback chain
if fallback_strategy == "cache_or_manual":
return _fallback_to_cached_trends(actor_config)
elif fallback_strategy == "alternative_actor":
return _execute_alternative_apify_actor(actor_config)
else:
raise RuntimeError(f"Apify API error: {str(e)}") from e
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 | |