knowledge-base-injection
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseKnowledge Base Injection
知识库注入
Part of Agent Skills™ by googleadsagent.ai™
属于 Agent Skills™ 的组成部分,由 googleadsagent.ai™ 提供
Description
描述
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. Generic language models lack the deep domain knowledge required for specialized tasks like Google Ads optimization, medical coding, or financial compliance. Rather than fine-tuning (expensive, slow, brittle) or bloating system prompts with everything the model might need (wasteful, dilutes attention), Knowledge Base Injection retrieves and injects only the specific patterns relevant to the current task.
This skill is built on the production knowledge base system powering Buddy™ at googleadsagent.ai™, specifically the module containing over 1,000 curated Google Ads optimization patterns. Each pattern includes a trigger condition (when to apply it), a recommendation (what to do), evidence (why it works), and a confidence score. When Buddy™ analyzes a campaign, the knowledge base engine scores all patterns against the current context using TF-IDF and injects the top-K most relevant patterns into the agent's context, transforming a general-purpose model into a domain expert.
gads-knowledge.jsThe injection system operates on a retrieval-augmented generation (RAG) paradigm, but with a critical distinction: rather than retrieving raw documents, it retrieves structured action patterns with built-in confidence scores and applicability conditions. This produces more actionable, more reliable agent outputs than document-level RAG.
知识库注入是一种技术:在最相关的时间点,利用 TF-IDF 模式匹配和语义评分,将领域专业知识动态注入 Agent 的上下文。通用语言模型缺乏完成专业任务所需的深层领域知识,例如 Google Ads 优化、医疗编码或财务合规。与其进行微调(成本高、速度慢且脆弱),或把模型可能需要的所有内容塞入系统提示(浪费资源并稀释注意力),知识库注入会检索并仅注入与当前任务相关的特定模式。
此 Skill 构建于支撑 googleadsagent.ai™ 上 Buddy™ 的生产级知识库系统之上,具体基于 模块,其中包含 1,000 多条精选的 Google Ads 优化模式。每个模式都包含触发条件(何时应用)、建议(具体做什么)、证据(为何有效)和置信度分数。当 Buddy™ 分析广告系列时,知识库引擎会使用 TF-IDF 将所有模式与当前上下文进行评分,并将最相关的前 K 个模式注入 Agent 上下文,从而将通用模型转变为领域专家。
gads-knowledge.js该注入系统采用检索增强生成(RAG)范式,但有一个关键区别:它检索的不是原始文档,而是内置置信度分数和适用条件的结构化行动模式。与文档级 RAG 相比,这能产生更具可操作性、更可靠的 Agent 输出。
Use When
何时使用
- The agent needs domain expertise that general-purpose models lack
- You have a curated knowledge base of patterns, rules, or best practices
- Fine-tuning is too expensive, too slow, or creates model version lock-in
- Different queries require different subsets of domain knowledge
- You want to update the agent's expertise without retraining or redeploying
- The agent must ground its recommendations in verified, authoritative sources
- Agent 需要通用模型所缺乏的领域专业知识
- 拥有由模式、规则或最佳实践组成的精选知识库
- 微调成本过高、速度过慢,或会造成模型版本锁定
- 不同查询需要不同子集的领域知识
- 希望在不重新训练或重新部署的情况下更新 Agent 的专业知识
- Agent 的建议必须以经过验证的权威来源为依据
How It Works
工作原理
mermaid
graph 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]When a task arrives, the query analyzer extracts key terms and concepts. The TF-IDF scorer computes relevance scores between the query and every pattern in the knowledge base. Patterns scoring above the threshold are ranked and the top-K are selected for injection. The selected patterns are assembled into a structured context block with clear formatting and injected into the agent's prompt. After execution, citation tracking links the agent's recommendations back to the specific patterns that informed them, providing auditability.
mermaid
graph 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]当任务到达时,查询分析器会提取关键术语和概念。TF-IDF 评分器会计算查询与知识库中每个模式之间的相关性分数。得分高于阈值的模式会被排序,并选出前 K 个用于注入。所选模式会组装成格式清晰的结构化上下文块,并注入 Agent 的提示中。执行完成后,引用追踪会将 Agent 的建议关联回为其提供依据的具体模式,从而实现可审计性。
Implementation
实现
Knowledge Pattern Structure:
typescript
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"],
},
];TF-IDF Scoring Engine:
python
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]Knowledge Injection into Agent Context:
python
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)Full Integration Example:
python
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)}知识模式结构:
typescript
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"],
},
];TF-IDF 评分引擎:
python
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]将知识注入 Agent 上下文:
python
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)完整集成示例:
python
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)}Best Practices
最佳实践
- Curate patterns with confidence scores — every knowledge pattern should have a confidence score based on evidence strength; the agent should weight high-confidence patterns more heavily.
- Keep patterns atomic — each pattern should address one specific situation; compound patterns reduce retrieval precision.
- Update the knowledge base continuously — domain knowledge evolves; schedule regular reviews to add new patterns, update confidence scores, and retire outdated ones.
- Limit injection to top-K relevant patterns — injecting too many patterns dilutes the agent's attention; 5-10 highly relevant patterns outperform 50 loosely relevant ones.
- Require citation tracking — instruct the agent to cite pattern IDs in its recommendations; this creates an audit trail and lets you measure which patterns drive the most value.
- Categorize patterns for efficient retrieval — pre-filtering by category (bidding, targeting, creative) before scoring reduces computation and improves precision.
- Benchmark against no-injection baselines — regularly compare agent performance with and without knowledge injection to quantify the value of the knowledge base.
- 使用置信度分数策划模式 — 每个知识模式都应有一个基于证据强度的置信度分数;Agent 应更重视高置信度模式。
- 保持模式原子化 — 每个模式应只处理一种具体场景;复合模式会降低检索精度。
- 持续更新知识库 — 领域知识会不断演变;应定期审查知识库,添加新模式、更新置信度分数并淘汰过时模式。
- 仅注入最相关的前 K 个模式 — 注入过多模式会稀释 Agent 的注意力;5 至 10 个高度相关的模式优于 50 个关联性较弱的模式。
- 要求引用追踪 — 指示 Agent 在建议中引用模式 ID;这既能创建审计轨迹,也能让你衡量哪些模式创造了最大价值。
- 按类别组织模式以实现高效检索 — 在评分前按类别(bidding、targeting、creative)预筛选,可减少计算量并提高精度。
- 与无注入基线进行基准测试 — 定期比较启用与停用知识注入时的 Agent 表现,以量化知识库的价值。
Platform Compatibility
平台兼容性
| 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 |
| 功能 | Claude Code | Cursor | Codex | Gemini CLI |
|---|---|---|---|---|
| 动态注入 | ✅ Hooks/MCP | ✅ Skills/MCP | ✅ 自定义 | ✅ 自定义 |
| TF-IDF 评分 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 |
| 模式检索 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 |
| 引用追踪 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 |
| 知识更新 | ✅ 文件重载 | ✅ Skill 重载 | ✅ 重启 | ✅ 重启 |
Related Skills
相关 Skill
- Token Optimization - Knowledge injection must respect context window budgets; top-K selection minimizes token waste
- Entity Memory Management - Entity context is assembled alongside knowledge patterns for comprehensive agent context
- Continuous Learning - Auto-generated skills feed back into the knowledge base as new injectable patterns
- Google Ads Audit - The 1,000-pattern knowledge base powers the audit's pattern-matching engine
- Token Optimization - 知识注入必须遵守上下文窗口预算;前 K 个选择可最大限度减少 token 浪费
- Entity Memory Management - 实体上下文与知识模式一同组装,以构建全面的 Agent 上下文
- Continuous Learning - 自动生成的 Skill 会以新的可注入模式反馈到知识库
- Google Ads Audit - 包含 1,000 个模式的知识库为审计的模式匹配引擎提供支持
Keywords
关键词
knowledge-base, tf-idf, pattern-matching, domain-expertise, retrieval-augmented-generation, knowledge-injection, confidence-scoring, citation-tracking, gads-knowledge, agent-skills
© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
knowledge-base, tf-idf, pattern-matching, domain-expertise, retrieval-augmented-generation, knowledge-injection, confidence-scoring, citation-tracking, gads-knowledge, agent-skills
© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License