/** * Complete Workflow Example - All Features Combined * * This comprehensive example demonstrates using multiple features together: * - Knowledge base (RAG) * - Memory (conversation context) * - Tools (local functions) * - Structured outputs (Zod) * - RAI guardrails (safety) * - Streaming */ import { z } from 'zod'; import { v4 as uuidv4 } from 'uuid'; import { Studio } from '../src'; // Define response schema for structured outputs const AnalysisSchema = z.object({ summary: z.string(), keyPoints: z.array(z.string()), sentiment: z.enum(['positive', 'negative', 'neutral']), confidence: z.number().min(0).max(1) }); type Analysis = z.infer; // Local tools function searchDatabase(query: string): string { // Simulate database search return `Found 5 results for "${query}": [result1, result2, result3, result4, result5]`; } function calculateMetrics(data: string): string { // Simulate metric calculation return `Metrics calculated: 42 items processed, 98.5% success rate`; } async function main() { const studio = new Studio({ apiKey: process.env.LYZR_API_KEY }); try { console.log('🚀 Building complete enterprise workflow\n'); // Step 1: Create Knowledge Base console.log('Step 1: Setting up Knowledge Base'); const kb = await studio.createKnowledgeBase({ name: 'company-knowledge', vectorStore: 'qdrant', description: 'Company documents and FAQs' }); console.log(`✓ Knowledge base created\n`); // Add content await kb.addText( 'Our company processes 1M transactions daily with 99.99% uptime SLA.', 'company-facts' ); // Step 2: Create Context console.log('Step 2: Setting up Global Context'); const context = await studio.createContext( 'business-rules', 'Always prioritize customer satisfaction. Follow GDPR compliance. Report issues within 2 hours.' ); console.log(`✓ Context created\n`); // Step 3: Create RAI Policy console.log('Step 3: Setting up Safety Policy'); const policy = await studio.createRAIPolicy({ name: 'Enterprise Safety', description: 'Production-grade safety policy', toxicityCheck: { enabled: true, threshold: 0.3 }, piiDetection: { EMAIL: 'redact', PHONE_NUMBER: 'redact' } }); console.log(`✓ Safety policy created\n`); // Step 4: Create Agent with All Features console.log('Step 4: Creating Advanced Agent'); const agent = await studio.createAgent({ name: 'Enterprise Assistant', provider: 'gpt-4o', role: 'Enterprise business assistant', goal: 'Provide data-driven insights with safety', instructions: ` You are an enterprise assistant that: 1. Uses the knowledge base for company information 2. Follows business rules and compliance 3. Calls available tools when needed 4. Provides structured analysis 5. Maintains conversation context `, temperature: 0.7, memory: 50, // Remember last 50 messages responseModel: AnalysisSchema, // Structured outputs raiPolicy: policy // Safety guardrails }); console.log(`✓ Agent created\n`); // Step 5: Add Tools console.log('Step 5: Registering Tools'); await agent.addTool(searchDatabase); await agent.addTool(calculateMetrics); console.log(`✓ ${agent.listTools().length} tools registered\n`); // Step 6: Add Context console.log('Step 6: Adding Context'); await agent.addContext(context); console.log(`✓ Context added\n`); // Step 7: Run Multi-turn Conversation console.log('Step 7: Running Multi-turn Conversation\n'); const sessionId = uuidv4(); const prompts = [ 'Hi, I need help analyzing our transaction data', 'Can you search the database for high-value transactions?', 'What metrics should we track?' ]; for (const prompt of prompts) { console.log(`User: ${prompt}`); const response = await agent.run(prompt, { sessionId, knowledgeBases: [kb] }); // Response is typed as Analysis due to responseModel const analysis = response as unknown as Analysis; if (typeof analysis === 'object' && analysis !== null && 'summary' in analysis) { console.log(`Assistant: ${(analysis as Analysis).summary}`); console.log(`Sentiment: ${(analysis as Analysis).sentiment}`); } else { console.log(`Assistant: ${(response as any).response}`); } console.log(); } // Step 8: Streaming Example console.log('Step 8: Streaming Response\n'); console.log('User: Tell me about our operational excellence'); console.log('Assistant (streaming): '); let charCount = 0; for await (const chunk of await agent.run( 'Give a detailed report about our operational performance', { sessionId, stream: true } )) { process.stdout.write(chunk.content); charCount += chunk.content.length; } console.log(`\n(${charCount} characters)\n`); // Step 9: Summary and Cleanup console.log('Step 9: Cleanup\n'); await agent.delete(); await kb.delete(); await context.delete(); await policy.delete(); console.log('✓ All resources cleaned up\n'); console.log('✨ Complete workflow example finished successfully!'); } catch (error) { console.error('Error:', error); process.exit(1); } } main();