Loading...
Loading...
Knowledge Base Injection is the technique of dynamically injecting domain expertise into an agent's context at the moment it is most relevant, using TF-IDF pattern matching and semantic scoring.
npx skill4agent add itallstartedwithaidea/agent-skills knowledge-base-injectiongads-knowledge.jsgraph TD
A[Agent Task/Query] --> B[Query Analyzer]
B --> C[TF-IDF Scorer]
C --> D[Knowledge Base<br/>1,000+ Patterns]
D --> E[Ranked Results]
E --> F{Score > Threshold?}
F -->|Yes| G[Top-K Selection]
F -->|No| H[Fallback: Broader Search]
H --> G
G --> I[Context Assembly]
I --> J[Pattern Injection<br/>into Agent Context]
J --> K[Agent Execution]
K --> L[Citation Tracking]
L --> M[Response with Sources]interface KnowledgePattern {
id: string;
category: "bidding" | "targeting" | "creative" | "budget" | "structure" | "general";
trigger: string;
recommendation: string;
evidence: string;
confidence: number;
terms: string[];
tf_idf_vector?: number[];
}
const SAMPLE_PATTERNS: KnowledgePattern[] = [
{
id: "bid-001",
category: "bidding",
trigger: "Campaign using manual CPC with more than 30 conversions/month",
recommendation: "Switch to Target CPA or Maximize Conversions bidding strategy",
evidence: "Campaigns with 30+ monthly conversions have sufficient data for Smart Bidding algorithms. Google's internal data shows 15-20% CPA improvement on average after switching.",
confidence: 0.92,
terms: ["manual", "cpc", "conversions", "bidding", "strategy", "target", "cpa"],
},
{
id: "budget-003",
category: "budget",
trigger: "Campaign limited by budget for more than 7 consecutive days",
recommendation: "Increase daily budget by 20-30% or reduce bids/targeting to fit within budget",
evidence: "Budget-limited campaigns miss high-value impressions during peak hours. Impression share lost to budget directly correlates with missed conversions.",
confidence: 0.88,
terms: ["budget", "limited", "daily", "impressions", "share", "lost"],
},
];import math
from collections import Counter
class TFIDFEngine:
def __init__(self, patterns: list[dict]):
self.patterns = patterns
self.idf = self.compute_idf()
def compute_idf(self) -> dict[str, float]:
n = len(self.patterns)
doc_freq = Counter()
for pattern in self.patterns:
unique_terms = set(pattern["terms"])
for term in unique_terms:
doc_freq[term] += 1
return {term: math.log(n / (1 + freq)) for term, freq in doc_freq.items()}
def score(self, query_terms: list[str], pattern: dict) -> float:
query_tf = Counter(query_terms)
pattern_terms = set(pattern["terms"])
score = 0.0
for term in query_terms:
if term in pattern_terms:
tf = query_tf[term] / len(query_terms)
idf = self.idf.get(term, 0)
score += tf * idf
return score * pattern.get("confidence", 1.0)
def search(self, query: str, top_k: int = 10, threshold: float = 0.1) -> list[dict]:
query_terms = self.tokenize(query)
scored = []
for pattern in self.patterns:
s = self.score(query_terms, pattern)
if s >= threshold:
scored.append({**pattern, "relevance_score": s})
scored.sort(key=lambda x: x["relevance_score"], reverse=True)
return scored[:top_k]
def tokenize(self, text: str) -> list[str]:
return [w.lower().strip(".,!?;:") for w in text.split() if len(w) > 2]def inject_knowledge(query: str, engine: TFIDFEngine, max_patterns: int = 8, max_tokens: int = 3000) -> str:
relevant = engine.search(query, top_k=max_patterns)
if not relevant:
return ""
sections = ["<domain_knowledge>"]
token_count = 0
for pattern in relevant:
entry = f"""[{pattern['id']}] (confidence: {pattern['confidence']:.0%}, relevance: {pattern['relevance_score']:.2f})
Trigger: {pattern['trigger']}
Recommendation: {pattern['recommendation']}
Evidence: {pattern['evidence']}"""
entry_tokens = len(entry.split()) * 1.3 # rough estimate
if token_count + entry_tokens > max_tokens:
break
sections.append(entry)
token_count += entry_tokens
sections.append("</domain_knowledge>")
sections.append("Use the patterns above to ground your analysis. Cite pattern IDs when making recommendations.")
return "\n\n".join(sections)async def analyze_with_knowledge(campaign_data: dict, user_query: str):
engine = TFIDFEngine(load_knowledge_base("gads-knowledge.js"))
context_query = f"{user_query} {campaign_data.get('strategy', '')} {campaign_data.get('status', '')}"
knowledge_block = inject_knowledge(context_query, engine)
messages = [
{"role": "system", "content": f"""You are Buddy™, a Google Ads expert agent by googleadsagent.ai™.
{knowledge_block}
Analyze the campaign data below and provide actionable recommendations.
Cite knowledge pattern IDs (e.g., [bid-001]) when your recommendations are based on domain patterns."""},
{"role": "user", "content": f"Campaign data:\n{json.dumps(campaign_data, indent=2)}\n\nQuery: {user_query}"},
]
response = await model.generate(messages)
citations = extract_citations(response, engine.patterns)
return {"analysis": response, "citations": citations, "patterns_used": len(citations)}| Feature | Claude Code | Cursor | Codex | Gemini CLI |
|---|---|---|---|---|
| Dynamic injection | ✅ Hooks/MCP | ✅ Skills/MCP | ✅ Custom | ✅ Custom |
| TF-IDF scoring | ✅ Full | ✅ Full | ✅ Full | ✅ Full |
| Pattern retrieval | ✅ Full | ✅ Full | ✅ Full | ✅ Full |
| Citation tracking | ✅ Full | ✅ Full | ✅ Full | ✅ Full |
| Knowledge updates | ✅ File reload | ✅ Skill reload | ✅ Restart | ✅ Restart |