-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathagent-with-fusion.ts
More file actions
233 lines (193 loc) · 5.79 KB
/
agent-with-fusion.ts
File metadata and controls
233 lines (193 loc) · 5.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/**
* OpenAI Agent SDK + Prompt Fusion Integration Example
*
* Demonstrates how to layer prompts using the OpenAI Agents SDK
* instructions parameter combined with Prompt Fusion for dynamic
* instruction composition.
*
* Based on official OpenAI Agent SDK documentation.
*/
import { Agent } from '@openai/agents'; // Hypothetical SDK
import PromptFusionEngine from '../../core/promptFusionEngine.js';
const fusionEngine = new PromptFusionEngine();
// LAYER 1: Base Instructions (Tool definitions & safety)
const baseInstructions = `You are a professional AI assistant with specialized capabilities.
CORE COMPETENCIES:
- Research and analysis
- Data processing
- Information synthesis
OPERATIONAL GUIDELINES:
- Validate all inputs before processing
- Cite sources when using external knowledge
- Acknowledge uncertainty when appropriate
- Maintain user privacy and data security`;
// LAYER 2: Brain Instructions (Workspace/Project configuration)
const brainInstructions = `PROJECT CONTEXT: Customer Analytics Platform
ENVIRONMENT: Production
ACCESS LEVEL: Analyst
PROJECT REQUIREMENTS:
- Focus on customer retention metrics
- Provide data-driven recommendations
- Use structured JSON for quantitative data
- Include confidence levels in predictions
DATA CONSTRAINTS:
- Access limited to anonymized customer data
- Maximum query size: 10,000 records
- Retention period: Last 24 months only`;
// LAYER 3: Persona Instructions (Role-specific behavior)
const personaInstructions = {
analyst: `ROLE: Data Analyst
SPECIALIZATION:
- Statistical analysis and hypothesis testing
- Pattern recognition in customer behavior
- Predictive modeling for churn prevention
METHODOLOGY:
1. Define clear metrics
2. Gather relevant data
3. Apply statistical methods
4. Validate findings
5. Present actionable insights
COMMUNICATION STYLE:
- Technical but accessible
- Quantify everything
- Use visualizations when helpful
- Provide specific recommendations`,
researcher: `ROLE: Research Specialist
SPECIALIZATION:
- Deep literature review
- Experimental design
- Source validation
METHODOLOGY:
1. Comprehensive information gathering
2. Critical evaluation of sources
3. Synthesis of findings
4. Academic-style documentation
COMMUNICATION STYLE:
- Formal academic tone
- Complete citations
- Detailed explanations
- Transparent about limitations`
};
/**
* Create a fused instruction set for OpenAI Agent
*/
function createFusedInstructions(
base: string,
brain: string,
persona: string = '',
personaActive: boolean = false
): string {
// Determine weights
const weights = personaActive && persona
? { base: 0.2, brain: 0.3, persona: 0.5 }
: { base: 0.4, brain: 0.6, persona: 0.0 };
// Fuse with semantic weighting
const fused = fusionEngine.semanticWeightedFusion(
base,
brain,
persona,
weights
);
return fused;
}
/**
* Create an OpenAI agent with fused instructions
*/
function createFusionAgent(
personaType: 'analyst' | 'researcher' | null = null
) {
const personaContent = personaType ? personaInstructions[personaType] : '';
const fusedInstructions = createFusedInstructions(
baseInstructions,
brainInstructions,
personaContent,
personaType !== null
);
const agent = new Agent({
name: personaType ? `${personaType}_agent` : 'default_agent',
model: "gpt-4o",
instructions: fusedInstructions,
tools: [
// Define your tools here
]
});
return agent;
}
/**
* Dynamic persona switching
*/
class AdaptiveAgent {
private baseInstructions: string;
private brainInstructions: string;
private currentAgent: any;
private currentPersona: string | null = null;
constructor(base: string, brain: string) {
this.baseInstructions = base;
this.brainInstructions = brain;
this.currentAgent = this.createAgent(null);
}
private createAgent(personaType: 'analyst' | 'researcher' | null) {
return createFusionAgent(personaType);
}
switchPersona(personaType: 'analyst' | 'researcher' | null) {
if (this.currentPersona !== personaType) {
console.log(`Switching persona from ${this.currentPersona} to ${personaType}`);
this.currentAgent = this.createAgent(personaType);
this.currentPersona = personaType;
}
}
async run(userMessage: string) {
return await this.currentAgent.run(userMessage);
}
}
/**
* Example usage
*/
async function main() {
// Create adaptive agent
const agent = new AdaptiveAgent(baseInstructions, brainInstructions);
// Start without persona (brain-heavy)
let response = await agent.run("What metrics should we track?");
console.log("Default response:", response);
// Switch to analyst persona (persona-heavy)
agent.switchPersona('analyst');
response = await agent.run("Analyze our customer retention rate");
console.log("Analyst response:", response);
// Switch to researcher persona
agent.switchPersona('researcher');
response = await agent.run("What does literature say about retention strategies?");
console.log("Researcher response:", response);
}
/**
* Template-based approach for multiple configurations
*/
interface AgentConfig {
role: string;
domain: string;
constraints: string[];
guidelines: string[];
}
function createConfiguredAgent(config: AgentConfig): any {
const brainPrompt = `ROLE: ${config.role}
DOMAIN: ${config.domain}
CONSTRAINTS:
${config.constraints.map(c => `- ${c}`).join('\n')}
GUIDELINES:
${config.guidelines.map(g => `- ${g}`).join('\n')}`;
const fusedInstructions = createFusedInstructions(
baseInstructions,
brainPrompt,
'', // No persona
false
);
return new Agent({
name: `${config.role}_agent`,
model: "gpt-4o",
instructions: fusedInstructions
});
}
// Run if executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
main();
}
export { createFusionAgent, AdaptiveAgent, createConfiguredAgent };