Use Cases & Real-World Patterns
This document showcases real-world deployments and battle-tested patterns that demonstrate GrayMatter's power across different industries and agent architectures.
Use Case 1: Customer Support Agent with Contextual Memory
Problem: Support agents handle similar customer issues repeatedly. Context is lost between sessions. Customers re-explain problems.
Solution: Use GrayMatter to store issue patterns, solutions, and customer preferences.
Memory Schema
MemoryEntry:
type: preference
tags: [support, pattern, stripe]
title: "Handle Stripe charge failure gracefully"
text: |
Customer reported failed charge on {{date}}
Issue: Declined card due to insufficient funds
Solution: Offer alternative payment method or pause subscription
Key: Check balance before charging; provide 3-day grace period
metadata:
domain: billing
solutionRate: 0.94 # 94% of similar issues resolved
averageResolutionMinutes: 8
MemoryEntry:
type: PREFERENCE
tags: [customer, stripe, vip]
title: "ACME Corp: special billing rules"
text: |
Customer: ACME Corp (enterprise account)
Rule 1: Always allow 14-day payment terms (vs. standard 3 days)
Rule 2: Waive failed charge fees
Rule 3: Escalate to account manager if any issue
metadata:
accountId: cust_acme
riskLevel: low
createdBy: sales@valkyr.ai
Workflow Integration
workflow:
name: "Customer Support Triage"
tasks:
- id: "retrieve_context"
module: "memory_read"
config:
query: "{{customer.issue_summary}}"
tags: ["support", "pattern"]
limit: 10
outputs:
- relevant_patterns
- id: "retrieve_customer_prefs"
module: "memory_read"
config:
query: "customer:{{customer.id}}"
tags: ["customer", "preference"]
outputs:
- customer_preferences
- id: "draft_response"
module: "llm"
inputs:
- customer_issue
- relevant_patterns
- customer_preferences
prompt: |
You are a helpful support agent.
Customer Issue:
{{customer_issue}}
Similar issues we've resolved:
{{relevant_patterns.map(p => p.text).join("\n---\n")}}
Customer Preferences:
{{customer_preferences.map(p => p.text).join("\n")}}
Draft a helpful response that:
1. Acknowledges their specific issue
2. References proven solution patterns
3. Respects customer preferences
4. Offers next steps
outputs:
- response
- id: "store_resolution"
module: "memory_write"
inputs:
- response
- success
config:
type: "decision"
title: "Resolved {{customer.issue_category}} for {{customer.name}}"
text: "{{response}}"
tags:
- "support"
- "resolved"
- "customer:{{customer.id}}"
- "category:{{customer.issue_category}}"
metadata:
succeeded: "{{success}}"
customerSatisfactionScore: "{{survey.nps}}"
resolutionTime: "{{timer.elapsedMinutes}}"
Expected Outcomes
- First response quality: Improves by 30-40% (patterns = proven solutions)
- Resolution time: Drops from ~20 min to ~8 min (context readily available)
- Customer satisfaction: NPS improves by 15-20 points
- Agent consistency: All agents follow same patterns and customer preferences
- Monthly usage estimate: Plan around memory reads and learning writes per agent; see Pricing for current credit rates.
Use Case 2: AI Business Analyst Auto-Generating Pitch Decks
Problem: Business analysts spend hours crafting pitch decks. Must research company, competitor landscape, market vertical. Knowledge gets scattered across documents.
Solution: Store market intelligence, company profiles, winning pitch patterns, and competitive positioning in GrayMatter.
Memory Schema
MemoryEntry:
type: context
tags: [market, saas, erp]
title: "SAP market share 2026"
text: |
SAP holds 28% of enterprise ERP market
Growth rate: 2% YoY (mature market)
Main competitors: Oracle (18%), Microsoft (14%), Infor (8%)
Emerging: NetSuite, Workday in mid-market
Trend: Shift to cloud-native (SAP S/4HANA vs. legacy)
metadata:
source: gartner-2026-report
confidence: 0.98
date: "2026-03-15"
MemoryEntry:
type: decision
tags: [pitch, saas, pattern, winning]
title: "Winning pitch structure for bottom-up SaaS"
text: |
Deck sections (in order):
1. Problem: Paint a vivid picture of pain (use customer quotes)
2. Market Opportunity: TAM/SAM/SOM with credible sources
3. Solution: How your product uniquely solves it
4. Go-to-Market: Initial customers, viral loops, metrics
5. Team: Why this team will win
6. Competition: Why you're different (avoid sounding defensive)
7. Financial Projections: Conservative 3-year forecast
8. Ask: Exactly how much capital and for what milestones
Key principles:
- Lead with customer problem, not your tech
- Use specific metrics, not generalities
- Avoid slides mentioning features you haven't launched
metadata:
source: y-combinator-guidance
successRate: 0.87
usedInDeals: 23
MemoryEntry:
type: PREFERENCE
tags: [company, acme, profile]
title: "ACME Corp competitive positioning"
text: |
Company: ACME Corp
Founded: 2024
Market: Supply chain visibility for mid-market manufacturing
Strengths:
- 10x faster integration vs. SAP (plug-and-play IoT)
- Real-time visibility dashboard (unique)
- $2M ARR already (amazing traction)
Weaknesses:
- Small team (4 engineers, 1 sales)
- No enterprise sales experience
- Limited geographic footprint (US only)
Positioning angle VS. SAP:
"SAP takes 18 months to implement. ACME takes 3 weeks."
Positioning angle VS. Coupa:
"Coupa is for procurement. ACME is for logistics execution."
Top 3 competitor wins:
- Moved from Descartes to ACME (saved $400k/year)
- Moved from Zeus to ACME (faster deployment)
metadata:
company: acme
lastUpdated: "2026-04-01"
datasource: customer-interviews
Agent Workflow
import { Agent } from "@valoride/agent";
import { MemoryService } from "@valkyr-labs/api-client";
export class PitchDeckBuilder extends Agent {
private memory: MemoryService;
async generatePitch(company: string, investor: string) {
// 1. Fetch company profile
const profile = await this.memory.queryEntries({
query: `company:${company}`,
tags: ["company", "profile"],
limit: 1,
});
// 2. Fetch market data
const markets = await this.memory.queryEntries({
query: profile.items[0].metadata.market,
tags: ["market", "fact"],
limit: 5,
});
// 3. Fetch winning pitch patterns
const pitchPatterns = await this.memory.queryEntries({
query: `pitch pattern`,
tags: ["pitch", "winning"],
limit: 3,
});
// 4. Fetch investor thesis
const investorThesis = await this.memory.queryEntries({
query: `investor:${investor}`,
tags: ["investor", "thesis"],
limit: 1,
});
// 5. Build prompt with all context
const prompt = `
You are a world-class pitch deck builder.
Company Profile:
${profile.items[0].text}
Market Context:
${markets.items.map((m) => m.text).join("\n---\n")}
Winning Pitch Patterns:
${pitchPatterns.items[0].text}
Investor Thesis:
${investorThesis.items[0]?.text || "General VC, looking for 10x returns in 5 years"}
Generate a 10-slide pitch deck outline in JSON format.
Each slide should have: title, key_points (array), speaker_notes
`;
const deck = await this.llm.generate(prompt);
// 6. Store generated deck as artifact
await this.memory.createEntry({
type: "artifact",
title: `Pitch deck for ${company} → ${investor}`,
text: JSON.stringify(deck, null, 2),
tags: ["artifact", `company:${company}`, `investor:${investor}`, "pitch"],
metadata: {
generatedAt: new Date().toISOString(),
version: 1,
},
});
return deck;
}
}
Expected Outcomes
- Time to deck: Drops from ~4 hours to ~30 min
- Deck quality: Improves because patterns are battle-tested
- Consistency: All pitches follow same winning structure
- Iteration speed: Agents can regenerate decks with different angles in 2 min
- Learning: Each pitch becomes a new artifact stored for future reference
- Usage estimate: A pitch usually combines a few memory reads with at least one learning write; see Pricing for current credit rates.
Use Case 3: Autonomous Agent Continuously Learning & Adapting
Problem: Agents repeat past mistakes. No mechanism to learn from failures or adapt behavior.
Solution: Agent stores execution logs, pattern discoveries, and behavioral adjustments in GrayMatter. Reads learnings before each task.
Self-Improvement Loop
export class SelfLearningAgent extends Agent {
async executeTask(task: Task): Promise<TaskResult> {
// 1. Fetch past executions of similar tasks
const pastRuns = await this.memory.queryEntries({
query: task.goal,
tags: [`task-pattern:${task.type}`],
type: "decision",
limit: 10,
});
// 2. Identify successful patterns
const successfulPatterns = pastRuns.items.filter(
(p) => p.metadata.success === true,
);
// 3. Identify failed patterns
const failedPatterns = pastRuns.items.filter(
(p) => p.metadata.success === false,
);
// 4. Execute task with learned patterns
const instruction = `
Execute this task: ${task.goal}
Past successful approaches:
${successfulPatterns.map((p) => p.text).join("\n---\n")}
Pitfalls to avoid:
${failedPatterns.map((p) => p.text).join("\n---\n")}
Execute the task and explain your reasoning.
`;
const result = await this.llm.execute(instruction);
// 5. After execution, capture learnings
if (result.success) {
await this.memory.createEntry({
type: "decision",
title: `Successfully executed: ${task.type}`,
text: `
Goal: ${task.goal}
Approach: ${result.approach}
Key Decisions: ${result.keyDecisions.join("; ")}
Result: ${result.outcome}
Time: ${result.executionTimeMs}ms
`,
tags: [`task-pattern:${task.type}`, "success"],
metadata: {
success: true,
taskType: task.type,
efficiencyGain: result.executionTimeMs - task.expectedTimeMs,
confidence: result.confidence,
},
});
// If this was significantly better than past attempts, mark as preferred pattern
const avgPastTime =
successfulPatterns
.map((p) => p.metadata.executionTime || 0)
.reduce((a, b) => a + b, 0) / Math.max(successfulPatterns.length, 1);
if (result.executionTimeMs < avgPastTime * 0.8) {
await this.memory.createEntry({
type: "PREFERENCE",
title: `Preferred pattern for ${task.type}`,
text: `Use this approach: ${result.approach}\nReasoning: ${result.reasoning}`,
tags: [`task-pattern:${task.type}`, "preferred"],
metadata: {
discoveredAt: new Date().toISOString(),
improvementPercent: (
(1 - result.executionTimeMs / avgPastTime) *
100
).toFixed(0),
},
});
}
} else {
// Capture failure for future avoidance
await this.memory.createEntry({
type: "decision",
title: `Failed attempt: ${task.type}`,
text: `
Goal: ${task.goal}
Attempted approach: ${result.approach}
Failure reason: ${result.error}
What to do instead: [AGENT RECOMMENDATION]
`,
tags: [`task-pattern:${task.type}`, "failure"],
metadata: {
success: false,
taskType: task.type,
errorType: result.error,
confidence: 0.5, // Lower confidence due to failure
},
});
}
return result;
}
}
Expected Outcomes
Over time, agents show continuous improvement:
| Metric | Week 1 | Week 4 | Week 12 |
|---|---|---|---|
| Task success rate | 65% | 78% | 88% |
| Avg execution time | 45s | 32s | 18s |
| Credit burn trend | Baseline | Learning phase | Optimized |
| Agent confidence | 0.62 | 0.74 | 0.85 |
Use Case 4: Multi-Agent Coordination via Shared Memory
Problem: Multiple agents solve different parts of a problem but don't share context. Results are suboptimal.
Solution: Agents share a common memory namespace where they leave notes, discoveries, and coordination points.
Agent Coordination Pattern
// Agent 1: Market Researcher
export class MarketResearcherAgent extends Agent {
async researchMarket(industry: string) {
const findings = await this.callLLM(`Research ${industry} market...`);
// Write findings for other agents
await this.memory.createEntry({
type: "context",
title: `Market research: ${industry}`,
text: findings.report,
tags: ["research", `industry:${industry}`, "shared"],
metadata: {
completedAt: new Date().toISOString(),
researchDepth: "comprehensive",
confidence: findings.confidence,
},
});
}
}
// Agent 2: Competitive Analyst
export class CompetitiveAnalystAgent extends Agent {
async analyzeCompetition(industry: string) {
// Read market research from Agent 1
const marketContext = await this.memory.queryEntries({
query: `industry:${industry}`,
tags: ["research", "shared"],
limit: 1,
});
const competitiveAnalysis = await this.callLLM(`
Given this market context:
${marketContext.items[0].text}
Analyze competitors in this space...
`);
// Write competitive analysis for other agents
await this.memory.createEntry({
type: "decision",
title: `Competitive landscape: ${industry}`,
text: competitiveAnalysis.report,
tags: ["competitive", `industry:${industry}`, "shared"],
metadata: {
builtOn: marketContext.items[0].id, // Reference chain
completedAt: new Date().toISOString(),
},
});
}
}
// Agent 3: Go-to-Market Strategist
export class GoToMarketAgent extends Agent {
async developStrategy(industry: string) {
// Read both research and competitive analysis
const context = await this.memory.queryEntries({
query: `industry:${industry}`,
tags: ["shared"],
limit: 10,
});
const gtmStrategy = await this.callLLM(`
Given all this context:
${context.items.map((c) => c.text).join("\n---\n")}
Develop a go-to-market strategy...
`);
await this.memory.createEntry({
type: "artifact",
title: `GTM Strategy: ${industry}`,
text: gtmStrategy.plan,
tags: ["gtm", `industry:${industry}`, "shared"],
metadata: {
builtOn: context.items.map((c) => c.id), // Dependency chain
strategy: "comprehensive",
},
});
}
}
// Orchestrator: Coordinate agents in sequence
async function orchestrateAnalysis(industry: string) {
const researcher = new MarketResearcherAgent();
const analyst = new CompetitiveAnalystAgent();
const gtmAgent = new GoToMarketAgent();
await researcher.researchMarket(industry); // Writes to shared memory
await analyst.analyzeCompetition(industry); // Reads + writes shared memory
await gtmAgent.developStrategy(industry); // Reads + writes shared memory
// Final strategy is in memory, ready for presentation
const finalStrategy = await this.memory.queryEntries({
query: `industry:${industry}`,
type: "artifact",
limit: 1,
});
return finalStrategy.items[0];
}
Expected Outcomes
- Coherence: Agents don't contradict each other
- Depth: Each agent builds on previous findings without re-researching
- Speed: 3 agents complete in ~5 min (vs. 15 min if independent)
- Quality: Integrated analysis beats sequential human work
- Traceability: Full dependency chain visible in memory (who read what, when)
Use Case 5: Compliance & Audit Trail for Regulated Industries
Problem: Financial/healthcare agents must prove decisions are auditable. Regulators demand provenance and reasoning trails.
Solution: Use GrayMatter with audit logging, signed payloads, and retention policies.
Compliance Memory Pattern
MemoryEntry:
type: preference
tags: [compliance, hipaa, healthcare]
title: "HIPAA-compliant patient data handling"
text: |
1. All patient names: log as hashed ID only
2. All medical records: encrypt at rest with AES-256
3. All access: log with timestamp, principal, and purpose
4. All deletions: audit trail retained for 7 years
metadata:
source: hipaa-regulation
effectiveDate: "2026-04-01"
enforced: true
MemoryEntry:
type: context
tags: [audit, loan-decision, 2026-04-01]
title: "Loan decision for customer_id=xyz (hashed)"
text: |
Decision: APPROVED
Amount: $50,000
Interest Rate: 4.8%
Reasoning:
- Credit score: 740 (good)
- Income: $120k (sufficient debt-to-income)
- Employment: 7 years stable (low risk)
- Decision rule: Score > 700 AND (income > 3×loan) = APPROVE
Decision made by: system-auto-approval-v3
Override: none
Customer notified: yes @2026-04-01 10:15:33 UTC
metadata:
decisionType: AUTOMATED
confidenceScore: 0.96
regulatoryCertification: true
createSignature: "hmac-sha256:..."
auditRetentionYears: 7
Audit Query Pattern
# Compliance officer queries: Show me all loan approvals on 2026-04-01
GET /v1/memory/entries?tags=audit,loan-decision,2026-04-01&type=context&limit=1000
# Response includes:
# - Full decision reasoning
# - Who made the decision (system or human)
# - All override instances
# - Signature for non-repudiation
# Regulator can export scoped evidence for review:
GET /v1/memory/entries/export?tags=audit,loan-decision,2026-04-01&limit=1000
# Shows:
# - Decision entries and reasoning
# - Principal-scoped metadata
# - Source tags and timestamps
Comparison: Before & After GrayMatter
| Aspect | Without GrayMatter | With GrayMatter |
|---|---|---|
| Context sharing | Copy-paste between agents | Single queryable memory |
| Learning curve | Each agent starts from scratch | Agents inherit past patterns |
| Consistency | Policies enforced in code | Policies stored as memories |
| Debugging | "Why did the agent do X?" (guesswork) | Full audit trail of what memories were used |
| Compliance | Scattered logs, hard to prove | Immutable record, signed, timestamped |
| Cost visibility | Opaque token usage | Explicit credit ledger per operation |
| Scaling | Adding agents = redundant knowledge | New agents immediately inherit memory |
| Knowledge retention | Lost between restarts | Durable unless explicitly deleted |