UNPKG

@xynehq/jaf

Version:

Juspay Agent Framework - A purely functional agent framework with immutable state and composable tools

232 lines • 11.3 kB
/** * Example client usage of A2A protocol with JAF agents * Demonstrates all client capabilities in a pure functional way */ import { createA2AClient, getAgentCard, sendMessageToAgent, streamMessageToAgent, checkA2AHealth, getA2ACapabilities, connectToA2AAgent, } from '../client.js'; // Pure function to demonstrate basic client usage export const demonstrateBasicUsage = async (serverUrl = 'http://localhost:3000') => { console.log('šŸ”— Creating A2A client...'); const client = createA2AClient(serverUrl); console.log(`šŸ“± Client created with session ID: ${client.sessionId}`); try { // Test agent discovery console.log('\nšŸ” Discovering agents...'); const agentCard = await getAgentCard(client); console.log(`šŸ¤– Found agent: ${agentCard.name}`); console.log(`šŸ“ Description: ${agentCard.description}`); console.log(`šŸŽÆ Skills: ${agentCard.skills.map(s => s.name).join(', ')}`); // Test health check console.log('\nšŸ„ Checking server health...'); const health = await checkA2AHealth(client); console.log(`āœ… Status: ${health.status}`); console.log(`šŸ¤– Available agents: ${health.agents.join(', ')}`); // Test capabilities console.log('\n⚔ Getting server capabilities...'); const capabilities = await getA2ACapabilities(client); console.log(`šŸ“‹ Supported methods: ${capabilities.supportedMethods.join(', ')}`); console.log(`šŸ”§ Input modes: ${capabilities.inputModes.join(', ')}`); return { client, agentCard, health, capabilities }; } catch (error) { console.error('āŒ Error in basic usage:', error); throw error; } }; // Pure function to demonstrate weather agent interaction export const demonstrateWeatherAgent = async (serverUrl = 'http://localhost:3000') => { console.log('\nšŸŒ¤ļø Testing Weather Agent...'); const client = createA2AClient(serverUrl); try { // Simple weather query console.log('\nšŸ“ Getting weather for Tokyo...'); const tokyoWeather = await sendMessageToAgent(client, 'weather', 'What\'s the weather in Tokyo?'); console.log('šŸŒ”ļø Response:', tokyoWeather); // Weather with hourly forecast console.log('\nšŸ“Š Getting detailed weather for London...'); const londonWeather = await sendMessageToAgent(client, 'weather', 'Get weather for London with hourly forecast in Fahrenheit'); console.log('šŸ“ˆ Response:', londonWeather); // Travel planning console.log('\nāœˆļø Starting travel planning...'); const travelResponse = await sendMessageToAgent(client, 'weather', 'I want to plan a trip to Paris next week, can you help me with weather and planning?'); console.log('šŸ—ŗļø Response:', travelResponse); return { tokyoWeather, londonWeather, travelResponse }; } catch (error) { console.error('āŒ Error testing weather agent:', error); throw error; } }; // Pure function to demonstrate calculator agent interaction export const demonstrateCalculatorAgent = async (serverUrl = 'http://localhost:3000') => { console.log('\nšŸ”¢ Testing Calculator Agent...'); const client = createA2AClient(serverUrl); try { // Basic calculation console.log('\nāž• Basic calculation...'); const basicCalc = await sendMessageToAgent(client, 'calculator', 'Calculate 15 * 23 + 7'); console.log('šŸ”¢ Result:', basicCalc); // Calculation with steps console.log('\nšŸ“‹ Calculation with steps...'); const stepsCalc = await sendMessageToAgent(client, 'calculator', 'Calculate (45 + 15) * 2 / 3 and show me the steps'); console.log('šŸ“Š Result:', stepsCalc); // Equation solving console.log('\nšŸŽÆ Equation solving...'); const equation = await sendMessageToAgent(client, 'calculator', 'Solve the equation 2x + 5 = 15'); console.log('šŸ” Result:', equation); return { basicCalc, stepsCalc, equation }; } catch (error) { console.error('āŒ Error testing calculator agent:', error); throw error; } }; // Pure function to demonstrate streaming export const demonstrateStreaming = async (serverUrl = 'http://localhost:3000') => { console.log('\n🌊 Testing Streaming...'); const client = createA2AClient(serverUrl); try { console.log('šŸ“” Starting streaming request to weather agent...'); const events = []; for await (const event of streamMessageToAgent(client, 'weather', 'Plan a detailed trip to Barcelona with weather considerations')) { console.log(`šŸ“ŗ Stream event:`, event); events.push(event); // Stop after reasonable number of events for demo if (events.length >= 5) { break; } } console.log(`āœ… Received ${events.length} streaming events`); return events; } catch (error) { console.error('āŒ Error testing streaming:', error); throw error; } }; // Pure function to demonstrate multi-agent conversation export const demonstrateMultiAgentConversation = async (serverUrl = 'http://localhost:3000') => { console.log('\nšŸ”„ Testing Multi-Agent Conversation...'); const client = createA2AClient(serverUrl); try { // Start with greeting agent console.log('\nšŸ‘‹ Getting introduction...'); const introduction = await sendMessageToAgent(client, 'greeting', 'Hello! My name is Alex and I need help planning a trip.'); console.log('šŸ—£ļø Greeting:', introduction); // Switch to weather agent for weather info console.log('\nšŸŒ¤ļø Checking weather...'); const weatherInfo = await sendMessageToAgent(client, 'weather', 'What\'s the weather like in Amsterdam this week?'); console.log('šŸŒ”ļø Weather:', weatherInfo); // Use calculator for budget calculations console.log('\nšŸ’° Calculating budget...'); const budgetCalc = await sendMessageToAgent(client, 'calculator', 'If I have 1500 euros and daily expenses are 120 euros, how many days can I stay?'); console.log('šŸ’µ Budget:', budgetCalc); // Back to weather agent for travel planning console.log('\nšŸ“… Final travel planning...'); const travelPlan = await sendMessageToAgent(client, 'weather', 'Based on Amsterdam weather, help me plan a 7-day trip with budget considerations'); console.log('šŸ—“ļø Travel Plan:', travelPlan); return { introduction, weatherInfo, budgetCalc, travelPlan }; } catch (error) { console.error('āŒ Error in multi-agent conversation:', error); throw error; } }; // Pure function to demonstrate the convenience API export const demonstrateConvenienceAPI = async (serverUrl = 'http://localhost:3000') => { console.log('\nšŸš€ Testing Convenience API...'); try { // Connect to agent with convenience wrapper const weatherAgent = await connectToA2AAgent(`${serverUrl}/a2a/agents/weather`); console.log('šŸ¤– Connected to weather agent'); console.log(`šŸ“ Agent: ${weatherAgent.agentCard.name}`); // Use simplified API console.log('\nā“ Asking simple question...'); const response = await weatherAgent.ask('What\'s the weather in Madrid?'); console.log('šŸ’¬ Response:', response); // Check agent health console.log('\nšŸ„ Checking agent health...'); const health = await weatherAgent.health(); console.log('āœ… Health:', health); // Get capabilities console.log('\n⚔ Getting capabilities...'); const capabilities = await weatherAgent.capabilities(); console.log('šŸ”§ Capabilities:', capabilities); return { weatherAgent, response, health, capabilities }; } catch (error) { console.error('āŒ Error testing convenience API:', error); throw error; } }; // Pure function to run all demonstrations export const runAllDemonstrations = async (serverUrl = 'http://localhost:3000') => { console.log('šŸŽ¬ Starting A2A Client Demonstrations'); console.log('=====================================\n'); try { // Test server availability first const basic = await demonstrateBasicUsage(serverUrl); // Run all demonstrations const weather = await demonstrateWeatherAgent(serverUrl); const calculator = await demonstrateCalculatorAgent(serverUrl); const streaming = await demonstrateStreaming(serverUrl); const multiAgent = await demonstrateMultiAgentConversation(serverUrl); const convenience = await demonstrateConvenienceAPI(serverUrl); console.log('\nšŸŽ‰ All demonstrations completed successfully!'); return { basic, weather, calculator, streaming, multiAgent, convenience }; } catch (error) { console.error('\nšŸ’„ Demonstration failed:', error); console.log('\nšŸ’” Make sure the A2A server is running on', serverUrl); console.log(' You can start it with: npm run a2a:example'); throw error; } }; // Pure function for interactive demonstration export const runInteractiveDemo = async (serverUrl = 'http://localhost:3000') => { const client = createA2AClient(serverUrl); console.log('šŸŽ® Interactive A2A Demo'); console.log('Type your messages and see A2A protocol in action!'); console.log('Commands: /weather <msg>, /calc <msg>, /greeting <msg>, /quit\n'); // This would typically use readline in a real implementation // For demo purposes, we'll simulate some interactions const sampleInteractions = [ { agent: 'greeting', message: 'Hello! I\'m new here.' }, { agent: 'weather', message: 'What\'s the weather in San Francisco?' }, { agent: 'calculator', message: 'Calculate 42 * 1.5 + 18' }, { agent: 'weather', message: 'Plan a trip to Tokyo' } ]; for (const interaction of sampleInteractions) { console.log(`\nšŸ‘¤ User to ${interaction.agent}: ${interaction.message}`); try { const response = await sendMessageToAgent(client, interaction.agent, interaction.message); console.log(`šŸ¤– ${interaction.agent} agent: ${response.substring(0, 200)}${response.length > 200 ? '...' : ''}`); } catch (error) { console.log(`āŒ Error: ${error}`); } // Simulate thinking time await new Promise(resolve => setTimeout(resolve, 1000)); } console.log('\nāœ… Interactive demo completed!'); }; // Run demonstrations if this file is executed directly if (typeof require !== 'undefined' && require.main === module) { const serverUrl = process.argv[2] || 'http://localhost:3000'; runAllDemonstrations(serverUrl) .then(() => { console.log('\nšŸ All demonstrations completed successfully!'); process.exit(0); }) .catch((error) => { console.error('\nšŸ’„ Demonstrations failed:', error); process.exit(1); }); } //# sourceMappingURL=client-example.js.map