-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutput-rendering.ts
More file actions
325 lines (265 loc) · 12.4 KB
/
Copy pathoutput-rendering.ts
File metadata and controls
325 lines (265 loc) · 12.4 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/**
* Output Rendering Example
*
* Demonstrates the comprehensive rendering helpers available in Harmony Protocol,
* including text, Markdown, HTML output, channel-specific rendering, and streaming updates.
*/
import {
Message,
Conversation,
Role,
Channel,
createSystemContent,
HarmonyRenderer,
StreamingRenderer,
renderToText,
renderToMarkdown,
renderToHTML,
renderFinalOnly,
renderSummary,
renderChannel,
ReasoningEffort
} from '../src/index.js';
async function main(): Promise<void> {
console.log('🎨 Harmony Protocol - Output Rendering Example');
console.log('===============================================');
// Step 1: Create a sample conversation with multiple channels
console.log('\n📝 Step 1: Creating sample conversation');
const conversation = Conversation.fromMessages([
Message.system(
createSystemContent()
.withIdentity('Advanced AI Assistant')
.withRequiredChannels(['analysis', 'commentary', 'final'])
.withReasoningEffort(ReasoningEffort.HIGH)
.build()
),
Message.user('Can you explain quantum computing and its potential impact on cybersecurity?'),
Message.assistant('I need to break this down systematically. Quantum computing leverages quantum mechanical phenomena, which poses both opportunities and threats to current security systems.')
.withChannel(Channel.ANALYSIS),
Message.assistant('This is a highly relevant topic given recent advances by companies like IBM, Google, and IonQ. The timeline for practical quantum computers is approaching faster than many expected.')
.withChannel(Channel.COMMENTARY),
Message.assistant('Quantum computing uses quantum bits (qubits) that can exist in superposition, allowing parallel processing of multiple states. For cybersecurity, this creates both risks and opportunities:\n\n**Threats:**\n- RSA and elliptic curve cryptography vulnerable to Shor\'s algorithm\n- Current encryption may become obsolete\n- Timeline: 10-20 years for cryptographically relevant systems\n\n**Opportunities:**\n- Quantum key distribution for unbreakable communication\n- Post-quantum cryptography development\n- Enhanced random number generation')
.withChannel(Channel.FINAL),
Message.user('What should organizations do to prepare?'),
Message.assistant('Organizations need both immediate and long-term strategies. The NIST post-quantum cryptography standards provide a roadmap, but implementation requires careful planning.')
.withChannel(Channel.ANALYSIS),
Message.assistant('This is urgent - organizations can\'t wait until quantum computers are mainstream. The transition to quantum-safe cryptography will take years.')
.withChannel(Channel.COMMENTARY),
Message.assistant('Here\'s a practical preparation roadmap:\n\n**Immediate (0-6 months):**\n1. Conduct cryptographic inventory audit\n2. Identify systems using RSA/ECC\n3. Establish quantum readiness team\n4. Monitor NIST standards\n\n**Medium-term (6-24 months):**\n1. Pilot post-quantum algorithms\n2. Update security policies\n3. Vendor discussions on quantum roadmaps\n4. Staff training programs\n\n**Long-term (2-10 years):**\n1. Full migration to quantum-safe cryptography\n2. Hybrid classical-quantum security\n3. Regular quantum threat assessments')
.withChannel(Channel.FINAL)
]);
console.log(`✓ Created conversation with ${conversation.length()} messages`);
// Step 2: Demonstrate basic rendering functions
console.log('\n🎯 Step 2: Basic rendering functions');
console.log('\n--- Plain Text Output ---');
const textOutput = renderToText(conversation, {
showChannels: true,
showRoles: true,
maxContentLength: 200
});
console.log(textOutput);
console.log('\n--- Summary ---');
const summary = renderSummary(conversation);
console.log(summary);
console.log('\n--- Final Channel Only ---');
const finalOnly = renderFinalOnly(conversation);
console.log(finalOnly.text);
// Step 3: Advanced renderer with custom options
console.log('\n🔧 Step 3: Advanced renderer with custom options');
const renderer = new HarmonyRenderer({
showChannels: true,
showRoles: true,
includeTimestamps: true,
channelLabels: {
[Channel.ANALYSIS]: '🤔 Thinking',
[Channel.COMMENTARY]: '💭 Context',
[Channel.FINAL]: '💬 Answer'
},
roleLabels: {
[Role.SYSTEM]: '⚙️ System',
[Role.USER]: '👤 User',
[Role.ASSISTANT]: '🤖 Assistant'
},
maxContentLength: 150
});
const fullRender = renderer.renderConversation(conversation);
console.log('\n--- Custom Formatted Output ---');
console.log(fullRender.text);
// Step 4: Channel-specific rendering
console.log('\n📊 Step 4: Channel-specific rendering');
const channelOutputs = renderer.renderByChannel(conversation);
for (const [channel, output] of Object.entries(channelOutputs)) {
console.log(`\n--- ${channel.toUpperCase()} Channel (${output.messageCount} messages) ---`);
console.log(output.combinedContent);
}
// Step 5: Markdown output for documentation
console.log('\n📄 Step 5: Markdown output');
const markdownRenderer = new HarmonyRenderer({
showChannels: true,
showRoles: false, // Cleaner for documentation
channelLabels: {
[Channel.ANALYSIS]: 'Analysis',
[Channel.COMMENTARY]: 'Commentary',
[Channel.FINAL]: 'Final Response'
}
});
const markdown = markdownRenderer.renderConversation(conversation).markdown;
console.log('\n--- Markdown Output (first 500 chars) ---');
console.log(markdown.substring(0, 500) + '...');
// Step 6: HTML output for web interfaces
console.log('\n🌐 Step 6: HTML output');
const html = renderer.renderConversation(conversation).html;
console.log('\n--- HTML Output Structure ---');
// Show just the structure, not full HTML
const htmlLines = html.split('\n');
htmlLines.slice(0, 10).forEach((line, i) => {
console.log(`${i + 1}: ${line}`);
});
console.log(`... and ${htmlLines.length - 10} more lines`);
// Step 7: Structured output for programmatic use
console.log('\n🏗️ Step 7: Structured output');
const structured = fullRender.structured;
console.log('\n--- Conversation Statistics ---');
console.log(`Total messages: ${structured.totalMessages}`);
console.log(`Total channels: ${structured.totalChannels}`);
console.log('Messages by role:');
Object.entries(structured.roles).forEach(([role, messages]) => {
console.log(` ${role}: ${messages.length} messages`);
});
console.log('Messages by channel:');
Object.entries(structured.channels).forEach(([channel, messages]) => {
console.log(` ${channel}: ${messages.length} messages`);
});
// Step 8: Streaming renderer demonstration
console.log('\n🌊 Step 8: Streaming renderer demonstration');
const streamingRenderer = new StreamingRenderer({
showChannels: true,
showRoles: false
});
// Simulate incremental conversation building
const conversations = [
Conversation.fromMessages(conversation.messages.slice(0, 2)), // System + first user
Conversation.fromMessages(conversation.messages.slice(0, 4)), // + analysis + commentary
Conversation.fromMessages(conversation.messages.slice(0, 5)), // + final response
conversation // Full conversation
];
for (let i = 0; i < conversations.length; i++) {
const result = streamingRenderer.renderIncremental(conversations[i]);
console.log(`\n--- Streaming Update ${i + 1} ---`);
console.log(`Has changes: ${result.hasChanges}`);
if (result.hasChanges) {
console.log(`New content (${result.newContent.length} messages):`);
result.newContent.forEach(msg => {
console.log(` ${msg.channel ? `[${msg.channel}] ` : ''}${msg.content.substring(0, 100)}...`);
});
}
}
// Step 9: Conversation comparison and diffs
console.log('\n🔍 Step 9: Conversation comparison');
const originalConversation = Conversation.fromMessages(conversation.messages.slice(0, 5));
const extendedConversation = conversation;
const diff = renderer.renderDiff(originalConversation, extendedConversation);
console.log('\n--- Conversation Diff ---');
console.log(`Added messages: ${diff.added.length}`);
console.log(`Modified messages: ${diff.modified.length}`);
console.log(`Unchanged messages: ${diff.unchanged.length}`);
diff.added.forEach(msg => {
console.log(` + [${msg.role}${msg.channel ? '/' + msg.channel : ''}]: ${msg.content.substring(0, 80)}...`);
});
// Step 10: Custom rendering for specific use cases
console.log('\n🎯 Step 10: Use case specific rendering');
// For chat UI (final responses only)
console.log('\n--- Chat UI Format ---');
const chatRenderer = new HarmonyRenderer({
showChannels: false,
showRoles: true,
roleLabels: {
[Role.USER]: 'You',
[Role.ASSISTANT]: 'AI'
}
});
const finalMessages = conversation.messages.filter(msg =>
msg.role === Role.USER || (msg.role === Role.ASSISTANT && msg.channel === Channel.FINAL)
);
const chatConversation = new Conversation(finalMessages);
const chatOutput = chatRenderer.renderConversation(chatConversation);
console.log(chatOutput.text);
// For debug/development (all channels)
console.log('\n--- Debug Format (all channels) ---');
const debugRenderer = new HarmonyRenderer({
showChannels: true,
showRoles: true,
includeTimestamps: true,
channelLabels: {
[Channel.ANALYSIS]: 'DEBUG:ANALYSIS',
[Channel.COMMENTARY]: 'DEBUG:COMMENTARY',
[Channel.FINAL]: 'DEBUG:FINAL'
}
});
const debugOutput = debugRenderer.renderConversation(conversation);
console.log(debugOutput.text.substring(0, 400) + '...');
// Step 11: Export formats
console.log('\n📤 Step 11: Export demonstrations');
console.log('\n--- JSON Export ---');
const jsonExport = {
conversation: conversation.toJSON(),
rendered: {
text: fullRender.text,
summary: summary,
statistics: structured
}
};
console.log(`JSON export size: ${JSON.stringify(jsonExport).length} characters`);
console.log('\n--- CSV-style Export ---');
const csvData = structured.messages.map(msg =>
`"${msg.role}","${msg.channel || 'none'}","${msg.content.replace(/"/g, '""')}",${msg.originalLength}`
);
console.log('Role,Channel,Content,Length');
csvData.slice(0, 3).forEach(row => console.log(row));
console.log(`... ${csvData.length - 3} more rows`);
// Step 12: Performance and statistics
console.log('\n📈 Step 12: Performance statistics');
const conversationSummary = renderer.renderSummary(conversation);
console.log('\n--- Detailed Statistics ---');
console.log(conversationSummary.overview);
console.log(conversationSummary.channelSummary);
console.log(conversationSummary.roleSummary);
console.log('\n--- Rendering Performance ---');
const startTime = Date.now();
for (let i = 0; i < 100; i++) {
renderer.renderConversation(conversation);
}
const renderTime = Date.now() - startTime;
console.log(`100 renders completed in ${renderTime}ms (${renderTime / 100}ms average)`);
console.log('\n🎉 Output rendering example completed successfully!');
console.log('\n💡 Key rendering capabilities demonstrated:');
console.log(' ✓ Plain text, Markdown, and HTML output formats');
console.log(' ✓ Channel-specific and role-specific filtering');
console.log(' ✓ Customizable labels and formatting options');
console.log(' ✓ Streaming and incremental rendering');
console.log(' ✓ Conversation diffs and comparisons');
console.log(' ✓ Structured data for programmatic use');
console.log(' ✓ Export formats (JSON, CSV)');
console.log(' ✓ Performance optimization for real-time use');
console.log('\n📋 Common use cases:');
console.log(' • Chat interfaces (final channel only)');
console.log(' • Debug views (all channels with metadata)');
console.log(' • Documentation generation (Markdown export)');
console.log(' • Web dashboards (HTML + structured data)');
console.log(' • Data analysis (CSV export + statistics)');
console.log(' • Real-time streaming UIs (incremental rendering)');
}
// Helper function to demonstrate custom rendering
function createCustomChatRenderer() {
return new HarmonyRenderer({
showChannels: false,
showRoles: true,
roleLabels: {
[Role.USER]: '👤',
[Role.ASSISTANT]: '🤖'
},
maxContentLength: 280 // Twitter-style length limit
});
}
// Run the example
main().catch(console.error);