<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicola Santi on Medium]]></title>
        <description><![CDATA[Stories by Nicola Santi on Medium]]></description>
        <link>https://medium.com/@nicolasanti_43152?source=rss-a64fa76f94b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mtz943XPHfN68hbIqv0pYw.jpeg</url>
            <title>Stories by Nicola Santi on Medium</title>
            <link>https://medium.com/@nicolasanti_43152?source=rss-a64fa76f94b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:58:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicolasanti_43152/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Certi che il nuovo servizio web sia più veloce?]]></title>
            <link>https://medium.com/@nicolasanti_43152/certi-che-il-nuovo-servizio-web-sia-pi%C3%B9-veloce-cdc98e47a436?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdc98e47a436</guid>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[confidence-interval]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[permutation-test]]></category>
            <category><![CDATA[t-test]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 14:30:38 GMT</pubDate>
            <atom:updated>2026-02-21T14:30:38.831Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Perché confrontare i tempi medi di risposta dei test di carico non è una così buona idea.</em></p><p><a href="https://medium.com/@nicolasanti_43152/are-you-sure-the-new-web-service-is-faster-155aeb941d55">english version</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJ4uQwics7HZud629S5XTg.png" /></figure><p>“La nuova versione risponde in media 6 millisecondi più velocemente. Deploy in produzione!”</p><p>Quante volte abbiamo preso decisioni simili basandoci semplicemente sul confronto delle medie nei test di carico? Il problema è che questo approccio nasconde due insidie fondamentali: il <strong>ruolo del caso</strong> e l’<strong>effetto del campionamento</strong>.</p><p>Immaginate di lanciare una moneta 20 volte e ottenere 13 teste. La moneta è truccata? O avete semplicemente avuto fortuna? Lo stesso vale per i test di performance: se la vostra nuova versione del servizio mostra tempi di risposta più bassi, quanto di questo miglioramento è reale e quanto è solo variabilità casuale?</p><p>Il caso non è l’unico problema. Il <strong>modo</strong> in cui raccogliete i dati influenza pesantemente i risultati. Effettuare 1000 chiamate consecutive al servizio in 10 secondi non produce osservazioni indipendenti: lo stato condiviso del sistema (cache, pool di connessioni, garbage collection) crea correlazioni artificiali. Una chiamata lenta tende a essere seguita da altre chiamate lente, non perché il servizio sia intrinsecamente più lento, ma per effetti di congestione temporanea.</p><p>Questi problemi non sono solo tecnicismi accademici. Portano a decisioni sbagliate: promuovere in produzione “miglioramenti” inesistenti o, peggio, scartare ottimizzazioni reali perché i test non le hanno evidenziate con sufficiente chiarezza.</p><p>In questo articolo esploreremo come applicare test statistici appropriati partendo dal classico t-test fino ad approcci più robusti come il test di Welch e il permutation test. Vedremo anche strategie pratiche per migliorare il campionamento e ridurre le correlazioni spurie nei dati.</p><p><strong>Tutti gli esempi di codice e i dati utilizzati sono disponibili nel repository GitHub:</strong> <a href="https://github.com/nicolinux72/statistical-tests.git">github.com/nicolinux72/statistical-tests.git</a></p><h3>I test statistici (molto molto brevemente)</h3><p>Un test statistico serve a verificare un’ipotesi (detta ipotesi nulla) contro l’evidenza raccolta. Ad esempio, se lanciassimo una moneta, l’ipotesi nulla potrebbe essere ritenerla bilanciata (50% testa, 50% croce). Il test ci dice quanto sia probabile ottenere i risultati osservati se questa ipotesi fosse vera, ovvero si propone di smentire l’ipotesi nulla quando questa probabilità sia molto bassa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3seENsFr7g-Eq5UG2c7iaQ.png" /></figure><p>In una moneta equilibrata, 20 lanci seguono una distribuzione binomiale, Bin(20;0,5), rappresentata nel grafico. Il valore più probabile è 10 teste (17,6%), mentre esiti estremi come 0 o 20 teste hanno probabilità quasi nulla (0,0001%).</p><p>Il ragionamento è questo: avendo realmente ottenuto 13 teste su 20 lanci, calcoliamo la probabilità teorica di ottenere quelle 13 o più teste assumendo vera l’ipotesi nulla. Nel nostro caso è 13,16%, quindi non particolarmente improbabile.</p><p>Per decidere quando rifiutare l’ipotesi nulla, si fissa una <strong>soglia di significatività</strong> α (tipicamente 5%). Se la probabilità p dell’evidenza osservata è minore di α, si rifiuta l’ipotesi nulla. Nel nostro esempio, fissato α=5%, rifiuteremmo l’ipotesi di moneta bilanciata solo con 15 o più teste (probabilità 2,07%).</p><h3>T-test</h3><p>Tornando al nostro servizio web, dobbiamo realizzare un test la cui ipotesi nulla sia che la risposta media della versione in produzione sia più lenta della nuova e scoprire se riusciamo a confutare questa ipotesi.</p><p>Per procedere come nel parametro precedente, ci occorre sapere la distribuzione della statistica utilizzata dal test, in questo caso la differenza tra le medie delle due versioni del servizio. Sotto alcune ipotesi che discuteremo tra poco, la distribuzione che ci occorre è la famosa t di Student (formalmente il rapporto tra una normale e la radice di una chi-quadrato entrambe normalizzate).</p><pre>from scipy.stats import ttest_ind<br> <br> # df_old e df_new sono DataFrame pandas con colonna &#39;response_time&#39;<br> t_stat, p_value = ttest_ind(df_old[&#39;response_time&#39;], df_new[&#39;response_time&#39;])<br> print(f&quot;p-value: {p_value:.4f} - {&#39;Differenza significativa&#39; if p_value &lt; 0.05 else &#39;Nessuna differenza&#39;}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-USCX_kbuXrKZYLwM7dgw.png" /></figure><p>Il grafico di sinistra mostra le distribuzioni dei tempi di risposta delle due versioni, mentre quello di destra visualizza la distribuzione t di Student e confronta la statistica t osservata, indicata dalla linea rossa tratteggiata, con le linee arancioni tratteggiate che delimitano le <strong>regioni di rifiuto</strong> per α=0.05. In questo caso, la statistica osservata non cade nelle zone ombreggiate in rosso quindi non abbiamo elementi per rifiutare l’ipotesi nulla: il nuovo servizio non è significativamente più veloce.</p><p>Approfondimento: La statistica t si calcola come:</p><p>t = (μ₁ — μ₂) / SE = (146,68–140,62) / 3,81 ≈ 1.64</p><p>dove μ₁ e μ₂ sono le medie dei due campioni (rispettivamente 146,68ms e 140,62ms) e SE (Standard Error) è l’errore standard della differenza, che quantifica l’incertezza nella stima della differenza tra le medie tenendo conto della variabilità dei dati e della dimensione dei campioni. Nel nostro esempio SE=3.81ms, e otteniamo quindi t≈1,64.</p><h3>Condizioni di necessarie di un t-test</h3><p>Torniamo alle ipotesi che ci consentono di usare il t test: * <strong>Indipendenza</strong> i campioni devono essere indipendenti tra loro così come devono essere indipendenti tra loro le osservazioni <em>dentro</em> i singoli campioni. * <strong>Normalità</strong> le distribuzioni di probabilità devono essere normali, la famosa distribuzione di Gauss a forma di campana. * <strong>Omoschedasticità</strong> le due popolazioni devono avere la stessa varianza.</p><p>Scendiamo nel dettaglio.</p><h3>Indipendenza</h3><p>I tempi di risposta di un servizio web raramente sono osservazioni indipendenti: lo stato del sistema (pod, cache, rete, …) è condiviso tra chiamate successive, creando correlazione. Inoltre, effettuare N chiamate consecutive in un breve intervallo, dunque la modalità più comune di campionamento, introduce autocorrelazione artificiale: a una chiamata lenta è più probabile che ne segua un’altra altrettanto lenta.</p><p>Per arginare le dipendenze legate allo stato del sistema si dovrebbero effettuare le richieste in condizioni comparabili per quanto riguarda carico del sistema, startup dei pod o cache e failover. Anche isolare i pod o le VM coinvolte nel campionamento o, non potendo, bilanciare le richieste su diversi back-end in modo assolutamente casuale.</p><p>Riguardo alle correlazioni indotte della modalità di campionamento, invece di utilizzare l’intera sequenza di chiamate effettuata in un intervallo continuo di tempo, si potrebbe utilizza una richiesta ogni k oppure selezionarle in modo casuale (subsampling). Alternativamente o in aggiunta, si effettuano diverse chiamate in finestre temporali diversi, si calcolano valori aggregati in queste finestre considerandole come unità campionarie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owhUMvgGhG4r6brWppYy6g.png" /></figure><h3>Normalità</h3><p>I tempi di risposta dei servizi web raramente seguono una distribuzione normale: tipicamente hanno code più pesanti a destra a causa di outlier con tempi molto lunghi. Fortunatamente il teorema del limite centrale ci viene in aiuto.</p><p>Il teorema garantisce che le medie campionarie tendono a distribuirsi normalmente indipendentemente dalla distribuzione originale dei dati, purché il campione sia sufficientemente grande. In pratica, anche se i singoli tempi di risposta non sono normali, basta che ogni campione contenga almeno 30 osservazioni perché la loro media si distribuisca approssimativamente in modo normale. Questo rende valido l’uso del t-test anche partendo da distribuzioni non normali.</p><p>Se si vuole verificare la normalità delle medie campionarie si può usare un Q-Q plot o il test di Shapiro-Wilk, ma con campioni di dimensione adeguata il teorema del limite centrale è generalmente sufficiente a giustificare l’uso del t-test.</p><h3>Omoschedasticità</h3><p>L’omoschedasticità, ovvero l’uguaglianza delle varianze tra i due campioni, è spesso problematica nei confronti tra servizi web. Versioni diverse di un servizio possono avere varianze differenti, violando questa ipotesi del t-test standard. Per risolvere il problema si ricorre al test di Welch, una variante del t-test che non assume varianze uguali e che descriveremo nel prossimo paragrafo.</p><h3>Test di Welch</h3><p>Il test di Welch è una variante del t-test di Student che rilassa l’ipotesi di omoschedasticità, permettendo ai due campioni di avere varianze diverse. Questo lo rende particolarmente adatto per confrontare servizi web, dove le varianze dei tempi di risposta possono differire significativamente tra versioni o configurazioni diverse.</p><p>A differenza del t-test standard, il test di Welch calcola i gradi di libertà usando l’approssimazione di Welch-Satterthwaite, che tiene conto delle varianze e dimensioni dei campioni. Il test richiede comunque che i campioni siano indipendenti e che le medie campionarie siano approssimativamente normali, condizione garantita dal teorema del limite centrale con campioni sufficientemente grandi (n ≥ 30).</p><p>In Python, il test di Welch si implementa facilmente usando scipy specificando il parametro equal_var=False:</p><pre># df_old e df_new sono DataFrame pandas con colonna &#39;response_time&#39;<br> t_stat, p_value = ttest_ind(df_old[&#39;response_time&#39;], df_new[&#39;response_time&#39;], equal_var=False)<br> print(f&quot;p-value: {p_value:.4f} - {&#39;Nuova versione significativamente più veloce&#39; if p_value &lt; 0.05 else &#39;Nessuna differenza significativa&#39;}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpEIs0OOKo0FST99KZ7fNw.png" /></figure><p>Questo approccio è generalmente preferibile al t-test standard nei contesti reali, poiché è più robusto e non penalizza significativamente la potenza del test quando le varianze sono effettivamente uguali.</p><h3>Permutation test</h3><p>Come abbiamo visto, ottenere campioni perfettamente indipendenti non è semplice nei sistemi distribuiti, e in alcuni casi anche l’ipotesi di normalità può essere problematica nonostante il teorema del limite centrale. Il permutation test offre un’alternativa interessante perché richiede un’ipotesi più debole: la scambiabilità invece dell’indipendenza.</p><p>La scambiabilità significa che l’ordine delle osservazioni non contiene informazione rilevante: se l’ipotesi nulla fosse vera (nessuna differenza tra i due servizi), permutare casualmente le etichette “vecchio” e “nuovo” tra le osservazioni non dovrebbe cambiare la distribuzione dei dati. Il test funziona calcolando la statistica di interesse (ad esempio la differenza delle medie) sui dati originali, poi ripetendo il calcolo su molte permutazioni casuali delle etichette. Il p-value è la frazione di permutazioni che producono una statistica più estrema di quella osservata.</p><p>Per ottenere la scambiabilità nei servizi web, invece di campionare singole richieste, si campionano a blocchi: ad esempio si raccolgono i tempi di risposta in finestre temporali di 5 minuti e si considera la media di ogni finestra come unità campionaria. In questo modo le correlazioni interne a ciascun blocco non violano l’ipotesi di scambiabilità tra blocchi.</p><pre># Medie calcolate su finestre temporali (blocchi)<br> old_blocks = df_old.groupby(&#39;window_id&#39;)[&#39;response_time&#39;].mean().values<br> new_blocks = df_new.groupby(&#39;window_id&#39;)[&#39;response_time&#39;].mean().values<br> <br> def statistic(x, y):<br> return np.mean(x) - np.mean(y)<br> <br> result = permutation_test((old_blocks, new_blocks), statistic, <br> permutation_type=&#39;independent&#39;, n_resamples=10000)<br> print(f&quot;p-value: {result.pvalue:.4f} - {&#39;Differenza significativa&#39; if result.pvalue &lt; 0.05 else &#39;Nessuna differenza&#39;}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DphrP6uUgRfX0pS4ffW37w.png" /></figure><p>Il permutation test è particolarmente robusto perché non fa assunzioni sulla forma della distribuzione e funziona bene anche con campioni piccoli, rendendolo una scelta affidabile quando le condizioni per il t-test sono dubbie.</p><h3>Bonus: Bootstrap</h3><p>La tecnica del bootstrap può tornare utile per stimare proprietà statistiche dei tempi di risposta di un singolo servizio, come la media o la varianza, e quantificare l’incertezza di queste stime. A differenza dei test precedenti, il bootstrap non serve per confrontare due servizi ma per capire quanto possiamo fidarci delle nostre misure su un singolo sistema.</p><p>Il bootstrap funziona ricampionando con reinserimento dal campione originale: se abbiamo raccolto n osservazioni, generiamo migliaia di nuovi campioni estraendo casualmente n valori dal campione originale (con possibilità di ripetizioni). Per ognuno di questi campioni “bootstrap” calcoliamo la statistica di interesse, ottenendo così una distribuzione empirica di quella statistica. Questa distribuzione ci permette di calcolare l’intervallo di confidenza, ovvero un range di valori entro cui ci aspettiamo si trovi il vero valore della popolazione con una certa probabilità (tipicamente 95%).</p><pre># Tempi di risposta osservati (in millisecondi)<br> response_times = df[&#39;response_time&#39;].values<br> n_bootstrap = 10000<br> <br> # Genera campioni bootstrap e calcola le medie<br> bootstrap_means = []<br> for _ in range(n_bootstrap):<br> sample = np.random.choice(response_times, size=len(response_times), replace=True)<br> bootstrap_means.append(np.mean(sample))<br> <br> bootstrap_means = np.array(bootstrap_means)<br> <br> # Calcola intervallo di confidenza al 95%<br> ci_lower = np.percentile(bootstrap_means, 2.5)<br> ci_upper = np.percentile(bootstrap_means, 97.5)<br> observed_mean = np.mean(response_times)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnbfg90wUnT0yMdh92RDJQ.png" /></figure><p>Il grafico mostra come si distribuiscono le medie calcolate sui campioni bootstrap. L’intervallo di confidenza al 95% ci dice che, se ripetessimo il campionamento infinite volte, nel 95% dei casi la vera media della popolazione cadrebbe in quell’intervallo. Questo ci dà una misura quantitativa dell’incertezza nelle nostre stime, informazione preziosa quando si devono prendere decisioni basate sui dati di performance.</p><h3>Conclusioni</h3><p>In molte aziende, i risultati dei test di carico vengono utilizzati direttamente per confrontare le performance tra versioni diverse di un servizio, basandosi semplicemente sulla differenza delle medie osservate. Questo approccio presenta però limiti significativi: non solo ignora il ruolo del caso nei risultati, ma spesso si basa su campionamenti che violano le ipotesi di indipendenza necessarie per un’analisi statistica corretta.</p><p>Abbiamo mostrato come applicare un approccio più rigoroso utilizzando test statistici appropriati. Il test di Welch rappresenta una scelta solida quando si possono ottenere campioni ragionevolmente indipendenti attraverso strategie di campionamento accorte, mentre il permutation test offre maggiore robustezza quando l’indipendenza è difficile da garantire. Entrambi gli approcci permettono di quantificare la probabilità che una differenza osservata sia dovuta al caso piuttosto che a una reale differenza di performance.</p><p>Gli esempi di codice forniti possono essere adattati facilmente ai propri contesti specifici, permettendo di trasformare i dati grezzi dei test di carico in evidenze statisticamente fondate. In definitiva, dedicare attenzione alla progettazione del campionamento e all’analisi statistica dei risultati non è solo un esercizio accademico: è ciò che distingue una decisione basata su impressioni da una decisione basata sui dati.</p><blockquote><strong>Nota dell’autore:</strong> ho scritto questo articolo con l’assistenza di LLM, in particolare Claude, ChatGpt e Gemini CLI. Come tutti, adotto il vibe code da un pezzo ma non mi ero ancora spinto fino alla redazione di un articolo divulgativo. È stato divertente :-)</blockquote><h3>Bibliografia</h3><h3>Testi classici</h3><p><strong>Fisher, R. A.</strong> (1935). <em>The Design of Experiments</em>. Oliver and Boyd, Edinburgh. L’opera fondamentale che ha introdotto i concetti di randomizzazione e test di significatività, ponendo le basi della moderna statistica inferenziale.</p><p><strong>Student</strong> (Gosset, W. S.) (1908). “The probable error of a mean”. <em>Biometrika</em>, 6(1), 1–25. L’articolo originale che introduce la distribuzione t, ancora oggi essenziale per l’analisi statistica con campioni di dimensione limitata.</p><p><strong>Tukey, J. W.</strong> (1977). <em>Exploratory Data Analysis</em>. Addison-Wesley. Opera seminale che ha rivoluzionato l’approccio all’analisi dei dati, enfatizzando l’importanza della visualizzazione e dell’esplorazione prima dell’inferenza formale.</p><p><strong>Welch, B. L.</strong> (1947). “The generalization of ‘Student’s’ problem when several different population variances are involved”. <em>Biometrika</em>, 34(1–2), 28–35. L’articolo che introduce il test di Welch e l’approssimazione di Welch-Satterthwaite per i gradi di libertà.</p><p><strong>Efron, B.</strong> (1979). “Bootstrap methods: Another look at the jackknife”. <em>The Annals of Statistics</em>, 7(1), 1–26. L’articolo fondamentale sul bootstrap, tecnica che ha trasformato l’analisi statistica permettendo di stimare distribuzioni campionarie senza assunzioni parametriche.</p><h3>Testi moderni</h3><p><strong>Good, P. I.</strong> (2005). <em>Permutation, Parametric and Bootstrap Tests of Hypotheses</em> (3rd ed.). Springer. Trattazione completa e accessibile dei test di permutazione e del bootstrap, con particolare attenzione alle applicazioni pratiche.</p><p><strong>Davison, A. C., &amp; Hinkley, D. V.</strong> (1997). <em>Bootstrap Methods and Their Application</em>. Cambridge University Press. Riferimento autorevole per l’applicazione del bootstrap in contesti reali, con esempi e case study approfonditi.</p><p><strong>Wasserstein, R. L., &amp; Lazar, N. A.</strong> (2016). “The ASA statement on p-values: Context, process, and purpose”. <em>The American Statistician</em>, 70(2), 129–133. Importante statement dell’American Statistical Association sull’uso corretto e i limiti dei p-value, fondamentale per interpretare correttamente i test statistici.</p><p><strong>VanderPlas, J.</strong> (2016). <em>Python Data Science Handbook</em>. O’Reilly Media. Guida pratica all’analisi dei dati in Python, con copertura di scipy.stats e tecniche di resampling. Disponibile gratuitamente su <a href="https://jakevdp.github.io/PythonDataScienceHandbook/">https://jakevdp.github.io/PythonDataScienceHandbook/</a></p><h3>Risorse web</h3><p><strong>SciPy Documentation — Statistical functions</strong> (scipy.stats)<br> <a href="https://docs.scipy.org/doc/scipy/reference/stats.html">https://docs.scipy.org/doc/scipy/reference/stats.html</a><br> Documentazione ufficiale completa delle funzioni statistiche di SciPy, inclusi ttest_ind, permutation_test e bootstrap.</p><p><strong>Towards Data Science</strong> — “Understanding the t-test”<br> <a href="https://towardsdatascience.com/">https://towardsdatascience.com/</a><br> Piattaforma con numerosi articoli divulgativi sui test statistici e le loro applicazioni pratiche in data science.</p><p><strong>Real Python</strong> — “Statistics in Python”<br> <a href="https://realpython.com/python-statistics/">https://realpython.com/python-statistics/</a><br> Tutorial pratici sull’applicazione della statistica in Python, con esempi di codice riproducibili.</p><p><strong>CrossValidated</strong> (StackExchange)<br> <a href="https://stats.stackexchange.com/">https://stats.stackexchange.com/</a><br> Comunità attiva di statistici dove trovare discussioni approfondite su test statistici, assunzioni e interpretazione dei risultati.</p><p><strong>Performance Testing Guidance</strong> — Microsoft Azure<br> <a href="https://learn.microsoft.com/en-us/azure/architecture/">https://learn.microsoft.com/en-us/azure/architecture/</a><br> Linee guida di Microsoft sulla progettazione e interpretazione di test di performance per applicazioni cloud.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdc98e47a436" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are You Sure the New Web Service Is Faster?]]></title>
            <link>https://medium.com/@nicolasanti_43152/are-you-sure-the-new-web-service-is-faster-155aeb941d55?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/155aeb941d55</guid>
            <category><![CDATA[permutation-test]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[t-test]]></category>
            <category><![CDATA[welch-t-test]]></category>
            <category><![CDATA[bootstrap]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 08:59:43 GMT</pubDate>
            <atom:updated>2026-01-23T08:59:43.393Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why comparing average response times in load tests is not such a good idea.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJ4uQwics7HZud629S5XTg.png" /></figure><p>“The new version responds on average 6 milliseconds faster. Deploy to production!”</p><p>How many times have we made similar decisions based simply on comparing averages in load tests? The problem is that this approach hides two fundamental pitfalls: the <strong>role of chance</strong> and the <strong>effect of sampling</strong>.</p><p>Imagine flipping a coin 20 times and getting 13 heads. Is the coin biased? Or were you just lucky? The same applies to performance tests: if your new service version shows lower response times, how much of this improvement is real and how much is just random variability?</p><p>Chance is not the only problem. The <strong>way</strong> you collect data heavily influences the results. Making 1000 consecutive calls to the service in 10 seconds does not produce independent observations: the shared system state (cache, connection pools, garbage collection) creates artificial correlations. A slow call tends to be followed by other slow calls, not because the service is inherently slower, but due to temporary congestion effects.</p><p>These problems are not just academic technicalities. They lead to wrong decisions: promoting non-existent “improvements” to production or, worse, discarding real optimizations because the tests did not highlight them with sufficient clarity.</p><p>In this article we will explore how to apply appropriate statistical tests, starting from the classic t-test to more robust approaches like Welch’s test and the permutation test. We will also see practical strategies to improve sampling and reduce spurious correlations in the data.</p><p><strong>All code examples and data used are available in the GitHub repository:</strong> <a href="https://github.com/nicolinux72/statistical-tests.git">github.com/nicolinux72/statistical-tests.git</a></p><h3>Statistical Tests (Very Briefly)</h3><p>A statistical test serves to verify a hypothesis (called the null hypothesis) against collected evidence. For example, if we were to flip a coin, the null hypothesis could be to consider it balanced (50% heads, 50% tails). The test tells us how likely it is to obtain the observed results if this hypothesis were true, that is, it aims to reject the null hypothesis when this probability is very low.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3seENsFr7g-Eq5UG2c7iaQ.png" /></figure><p>For a balanced coin, 20 flips follow a binomial distribution, Bin(20;0.5), represented in the graph. The most likely value is 10 heads (17.6%), while extreme outcomes like 0 or 20 heads have almost zero probability (0.0001%).</p><p>The reasoning is this: having actually obtained 13 heads out of 20 flips, we calculate the theoretical probability of obtaining those 13 or more heads assuming the null hypothesis is true. In our case it is 13.16%, so not particularly unlikely.</p><p>To decide when to reject the null hypothesis, we set a <strong>significance level</strong> α (typically 5%). If the probability p of the observed evidence is less than α, we reject the null hypothesis. In our example, with α=5%, we would reject the hypothesis of a balanced coin only with 15 or more heads (probability 2.07%).</p><h3>T-test</h3><p>Returning to our web service, we need to perform a test whose null hypothesis is that the average response of the production version is slower than the new one, and discover if we can refute this hypothesis.</p><p>To proceed as in the previous parameter, we need to know the distribution of the statistic used by the test, in this case the difference between the means of the two service versions. Under some hypotheses we will discuss shortly, the distribution we need is the famous Student’s t (formally the ratio between a normal distribution and the square root of a chi-square distribution, both normalized).</p><pre><br># df_old and df_new are pandas DataFrames with &#39;response_time&#39; column<br>t_stat, p_value = ttest_ind(df_old[&#39;response_time&#39;], df_new[&#39;response_time&#39;])<br>print(f&quot;p-value: {p_value:.4f} - {&#39;Significant difference&#39; if p_value &lt; 0.05 else &#39;No difference&#39;}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-USCX_kbuXrKZYLwM7dgw.png" /></figure><p>The left graph shows the distributions of response times for the two versions, while the right one visualizes the Student’s t distribution and compares the observed t-statistic, indicated by the red dashed line, with the orange dashed lines that delimit the <strong>rejection regions</strong> for α=0.05. In this case, the observed statistic does not fall in the red shaded areas, so we have no grounds to reject the null hypothesis: the new service is not significantly faster.</p><p>Deep dive: The t-statistic is calculated as:</p><p>t = (μ₁ — μ₂) / SE = (146.68–140.62) / 3.81 ≈ 1.64</p><p>where μ₁ and μ₂ are the means of the two samples (146.68ms and 140.62ms respectively) and SE (Standard Error) is the standard error of the difference, which quantifies the uncertainty in estimating the difference between the means, taking into account the variability of the data and the sample size. In our example SE=3.81ms, and we therefore obtain t≈1.64.</p><h3>Necessary Conditions for a T-test</h3><p>Let’s return to the assumptions that allow us to use the t-test: * <strong>Independence</strong> the samples must be independent of each other, just as the observations <em>within</em> individual samples must be independent of each other. * <strong>Normality</strong> the probability distributions must be normal, the famous bell-shaped Gaussian distribution. * <strong>Homoscedasticity</strong> the two populations must have the same variance.</p><p>Let’s go into detail.</p><h3>Independence</h3><p>The response times of a web service are rarely independent observations: the system state (pods, cache, network, …) is shared between successive calls, creating correlation. Moreover, making N consecutive calls in a short interval, therefore the most common sampling method, introduces artificial autocorrelation: a slow call is more likely to be followed by another equally slow one.</p><p>To limit dependencies related to system state, requests should be made under comparable conditions regarding system load, pod startup, cache, and failover. Also isolate the pods or VMs involved in sampling or, if not possible, balance requests across different backends in a completely random manner.</p><p>Regarding correlations induced by the sampling method, instead of using the entire sequence of calls made in a continuous time interval, you could use one request every k or select them randomly (subsampling). Alternatively or in addition, make several calls in different time windows, calculate aggregated values in these windows, considering them as sampling units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owhUMvgGhG4r6brWppYy6g.png" /></figure><h3>Normality</h3><p>Web service response times rarely follow a normal distribution: they typically have heavier right tails due to outliers with very long times. Fortunately, the central limit theorem comes to our aid.</p><p>The theorem guarantees that sample means tend to be normally distributed regardless of the original distribution of the data, provided the sample is sufficiently large. In practice, even if individual response times are not normal, as long as each sample contains at least 30 observations, their mean will be approximately normally distributed. This makes the use of the t-test valid even starting from non-normal distributions.</p><p>If you want to verify the normality of sample means, you can use a Q-Q plot or the Shapiro-Wilk test, but with samples of adequate size, the central limit theorem is generally sufficient to justify the use of the t-test.</p><h3>Homoscedasticity</h3><p>Homoscedasticity, that is, the equality of variances between the two samples, is often problematic in comparisons between web services. Different versions of a service can have different variances, violating this assumption of the standard t-test. To solve the problem, we resort to Welch’s test, a variant of the t-test that does not assume equal variances and which we will describe in the next paragraph.</p><h3>Welch’s Test</h3><p>Welch’s test is a variant of Student’s t-test that relaxes the homoscedasticity assumption, allowing the two samples to have different variances. This makes it particularly suitable for comparing web services, where the variances of response times can differ significantly between different versions or configurations.</p><p>Unlike the standard t-test, Welch’s test calculates the degrees of freedom using the Welch-Satterthwaite approximation, which takes into account the variances and sizes of the samples. The test still requires that the samples be independent and that the sample means be approximately normal, a condition guaranteed by the central limit theorem with sufficiently large samples (n ≥ 30).</p><p>In Python, Welch’s test is easily implemented using scipy by specifying the equal_var=False parameter:</p><pre># df_old and df_new are pandas DataFrames with &#39;response_time&#39; column<br>t_stat, p_value = ttest_ind(df_old[&#39;response_time&#39;], df_new[&#39;response_time&#39;], equal_var=False)<br>print(f&quot;p-value: {p_value:.4f} - {&#39;New version significantly faster&#39; if p_value &lt; 0.05 else &#39;No significant difference&#39;}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpEIs0OOKo0FST99KZ7fNw.png" /></figure><p>This approach is generally preferable to the standard t-test in real contexts, as it is more robust and does not significantly penalize the power of the test when the variances are actually equal.</p><h3>Permutation Test</h3><p>As we have seen, obtaining perfectly independent samples is not simple in distributed systems, and in some cases even the normality assumption can be problematic despite the central limit theorem. The permutation test offers an interesting alternative because it requires a weaker assumption: exchangeability instead of independence.</p><p>Exchangeability means that the order of observations does not contain relevant information: if the null hypothesis were true (no difference between the two services), randomly permuting the “old” and “new” labels between observations should not change the distribution of the data. The test works by calculating the statistic of interest (for example, the difference of means) on the original data, then repeating the calculation on many random permutations of the labels. The p-value is the fraction of permutations that produce a statistic more extreme than the one observed.</p><p>To obtain exchangeability in web services, instead of sampling individual requests, we sample in blocks: for example, we collect response times in 5-minute time windows and consider the average of each window as a sampling unit. This way, the internal correlations within each block do not violate the exchangeability assumption between blocks.</p><pre># Means calculated over time windows (blocks)<br>old_blocks = df_old.groupby(&#39;window_id&#39;)[&#39;response_time&#39;].mean().values<br>new_blocks = df_new.groupby(&#39;window_id&#39;)[&#39;response_time&#39;].mean().values<br><br>def statistic(x, y):<br>return np.mean(x) - np.mean(y)<br><br>result = permutation_test((old_blocks, new_blocks), statistic, <br>permutation_type=&#39;independent&#39;, n_resamples=10000)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DphrP6uUgRfX0pS4ffW37w.png" /></figure><p>The permutation test is particularly robust because it makes no assumptions about the shape of the distribution and works well even with small samples, making it a reliable choice when the conditions for the t-test are questionable.</p><h3>Bonus: Bootstrap</h3><p>The bootstrap technique can be useful for estimating statistical properties of the response times of a single service, such as the mean or variance, and quantifying the uncertainty of these estimates. Unlike the previous tests, bootstrap is not used to compare two services but to understand how much we can trust our measurements on a single system.</p><p>Bootstrap works by resampling with replacement from the original sample: if we have collected n observations, we generate thousands of new samples by randomly drawing n values from the original sample (with the possibility of repetitions). For each of these “bootstrap” samples we calculate the statistic of interest, thus obtaining an empirical distribution of that statistic. This distribution allows us to calculate the confidence interval, that is, a range of values within which we expect the true population value to fall with a certain probability (typically 95%).</p><pre># Observed response times (in milliseconds)<br> response_times = df[&#39;response_time&#39;].values<br> n_bootstrap = 10000<br> <br> # Generate bootstrap samples and calculate means<br> bootstrap_means = []<br> for _ in range(n_bootstrap):<br> sample = np.random.choice(response_times, size=len(response_times), replace=True)<br> bootstrap_means.append(np.mean(sample))<br> <br> bootstrap_means = np.array(bootstrap_means)<br> <br> # Calculate 95% confidence interval<br> ci_lower = np.percentile(bootstrap_means, 2.5)<br> ci_upper = np.percentile(bootstrap_means, 97.5)<br> observed_mean = np.mean(response_times)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gnbfg90wUnT0yMdh92RDJQ.png" /></figure><p>The graph shows how the means calculated on bootstrap samples are distributed. The 95% confidence interval tells us that if we repeated the sampling infinitely many times, in 95% of cases the true population mean would fall within that interval. This gives us a quantitative measure of the uncertainty in our estimates, valuable information when making data-driven decisions.</p><h3>Conclusions</h3><p>In many companies, load test results are used directly to compare performance between different versions of a service, based simply on the difference in observed means. However, this approach has significant limitations: not only does it ignore the role of chance in the results, but it is often based on sampling that violates the independence assumptions necessary for correct statistical analysis.</p><p>We have shown how to apply a more rigorous approach using appropriate statistical tests. Welch’s test represents a solid choice when reasonably independent samples can be obtained through careful sampling strategies, while the permutation test offers greater robustness when independence is difficult to guarantee. Both approaches allow quantifying the probability that an observed difference is due to chance rather than a real performance difference.</p><p>The provided code examples can be easily adapted to your specific contexts, allowing you to transform raw load test data into statistically sound evidence. Ultimately, paying attention to sampling design and statistical analysis of results is not just an academic exercise: it is what distinguishes a decision based on impressions from a data-driven decision.</p><p><strong>Author’s note:</strong> I wrote this article with the assistance of LLMs, particularly Claude, ChatGPT and Gemini CLI. Like everyone else, I’ve been doing vibe coding for a while but had not yet ventured as far as writing a popular science article. It was fun :-)</p><h3>Bibliography</h3><h4>Classic Texts</h4><p><strong>Fisher, R. A.</strong> (1935). <em>The Design of Experiments</em>. Oliver and Boyd, Edinburgh. The foundational work that introduced the concepts of randomization and significance testing, laying the foundations of modern inferential statistics.</p><p><strong>Student</strong> (Gosset, W. S.) (1908). “The probable error of a mean”. <em>Biometrika</em>, 6(1), 1–25. The original article that introduces the t-distribution, still essential today for statistical analysis with limited sample sizes.</p><p><strong>Tukey, J. W.</strong> (1977). <em>Exploratory Data Analysis</em>. Addison-Wesley. Seminal work that revolutionized the approach to data analysis, emphasizing the importance of visualization and exploration before formal inference.</p><p><strong>Welch, B. L.</strong> (1947). “The generalization of ‘Student’s’ problem when several different population variances are involved”. <em>Biometrika</em>, 34(1–2), 28–35. The article that introduces Welch’s test and the Welch-Satterthwaite approximation for degrees of freedom.</p><p><strong>Efron, B.</strong> (1979). “Bootstrap methods: Another look at the jackknife”. <em>The Annals of Statistics</em>, 7(1), 1–26. The foundational article on bootstrap, a technique that has transformed statistical analysis by allowing the estimation of sampling distributions without parametric assumptions.</p><h4>Modern Texts</h4><p><strong>Good, P. I.</strong> (2005). <em>Permutation, Parametric and Bootstrap Tests of Hypotheses</em> (3rd ed.). Springer. Comprehensive and accessible treatment of permutation tests and bootstrap, with particular attention to practical applications.</p><p><strong>Davison, A. C., &amp; Hinkley, D. V.</strong> (1997). <em>Bootstrap Methods and Their Application</em>. Cambridge University Press. Authoritative reference for the application of bootstrap in real contexts, with in-depth examples and case studies.</p><p><strong>Wasserstein, R. L., &amp; Lazar, N. A.</strong> (2016). “The ASA statement on p-values: Context, process, and purpose”. <em>The American Statistician</em>, 70(2), 129–133. Important statement by the American Statistical Association on the correct use and limitations of p-values, fundamental for correctly interpreting statistical tests.</p><p><strong>VanderPlas, J.</strong> (2016). <em>Python Data Science Handbook</em>. O’Reilly Media. Practical guide to data analysis in Python, with coverage of scipy.stats and resampling techniques. Available for free at <a href="https://jakevdp.github.io/PythonDataScienceHandbook/">https://jakevdp.github.io/PythonDataScienceHandbook/</a></p><h4>Web Resources</h4><p><strong>SciPy Documentation — Statistical functions</strong> (scipy.stats)<br> <a href="https://docs.scipy.org/doc/scipy/reference/stats.html">https://docs.scipy.org/doc/scipy/reference/stats.html</a><br> Complete official documentation of SciPy statistical functions, including ttest_ind, permutation_test and bootstrap.</p><p><strong>Towards Data Science</strong> — “Understanding the t-test”<br> <a href="https://towardsdatascience.com/">https://towardsdatascience.com/</a><br> Platform with numerous popular articles on statistical tests and their practical applications in data science.</p><p><strong>Real Python</strong> — “Statistics in Python”<br> <a href="https://realpython.com/python-statistics/">https://realpython.com/python-statistics/</a><br> Practical tutorials on applying statistics in Python, with reproducible code examples.</p><p><strong>CrossValidated</strong> (StackExchange)<br> <a href="https://stats.stackexchange.com/">https://stats.stackexchange.com/</a><br> Active community of statisticians where you can find in-depth discussions on statistical tests, assumptions, and interpretation of results.</p><p><strong>Performance Testing Guidance</strong> — Microsoft Azure<br> <a href="https://learn.microsoft.com/en-us/azure/architecture/">https://learn.microsoft.com/en-us/azure/architecture/</a><br> Microsoft guidelines on designing and interpreting performance tests for cloud applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=155aeb941d55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[La favola di due standard: A2A e MCP possono davvero coesistere?❤️vs]]></title>
            <link>https://medium.com/@nicolasanti_43152/la-favola-di-due-standard-a2a-e-mcp-possono-davvero-coesistere-%EF%B8%8Fvs-0caa06088bf7?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0caa06088bf7</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[a2a-protocol]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 08:56:26 GMT</pubDate>
            <atom:updated>2025-09-14T08:56:26.045Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Verifichiamo con mano la sovrapponibilità dei due standard scrivendo un paio di agenti Python ADK e Java Spring AI.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70OderDN-SYif4phewtsuA.jpeg" /><figcaption><a href="https://www.majambiente.it/2017/10/06/un-escursione-sicura-riconoscere-e-leggere-la-segnaletica-dei-sentieri/">Foto originale</a> editata cone Google Gemini 2.5 Flash (aka Nano Banana)</figcaption></figure><p>Pochi mesi fa, Google ha presentato Agent to Agent (A2A), un nuovo protocollo aperto di comunicazione tra agenti, tra l’altro <a href="https://developers.googleblog.com/en/google-cloud-donates-a2a-to-linux-foundation/">donato</a> generosamente alla Linux Software Foundation. Già durante la presentazione è stata enfatizzata la differenza di finalità rispetto al Model Context Protocol (MCP) di Anthropic, rilasciato ormai da tempo e accolto entusiasticamente dalla comunità degli sviluppatori. La complementarità tra due protocolli, reiterata in molte forme e modi, è sintetizzata nella documentazione ufficiale di A2A nella pagina intitolata eloquentemente: <a href="https://a2a-protocol.org/latest/topics/a2a-and-mcp/">A2A ❤️ MCP</a>.</p><p>Nonostante questi sforzi, il timore di sovrapposizione tra i due standard è stato segnalato da più parti, anche con toni piuttosto espliciti come, ad esempio, le dichiarazioni del CEO di Dagger, ex fondatore e CEO di Docker:</p><blockquote>Anthropic pushes MCP. Google rushes A2A. Welcome to the AI Standard Wars. “But they are complementary! Each standard has a purpose” Oh my sweet summer child. This is war.</blockquote><blockquote><a href="https://x.com/solomonstre/status/1909971067113742732">Solomon Hykes</a></blockquote><p>Recentemente, Open AI ha abbracciato MCP e non è passata inosservata la sua assenza, e quella di Anthropic, alla presentazione ufficiale di A2A (riportata da <a href="https://www.koyeb.com/blog/a2a-and-mcp-start-of-the-ai-agent-protocol-wars#are-a2a-and-mcp-addressing-different-use-cases">Alisdair Broshar</a>).</p><p>In questo articolo metteremo a confronto due protocolli, <strong>A2A</strong> e <strong>MCP</strong>, attraverso la realizzazione di un esempio pratico. Eviteremo una trattazione esaustiva a favore di un approfondimento mirato ai punti comuni e a quelli divergenti, con l’obiettivo di offrire al lettore gli elementi per scegliere in autonomia su quale standard scommettere nell’immediato futuro.</p><p>L’articolo si inserisce nella <a href="https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-parte-ii-03532dc4639f">serie</a> dedicata alle aziende che già possiedano una codebase ricca di servizi e applicazioni, ad esempio scritti in Java, e desiderino renderli accessibili all’AI.</p><p>Un ulteriore chiave di lettura è intendere questo articolo come un tutorial per realizzare un MCP server in Java con Spring AI e un agente in Python con l’Agent Development Kit (ADK) di Google.</p><h3>La teoria</h3><p>La narrazione ufficiale di Google è ben rappresentata dallo schema seguente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*xgLTfQr9KP4jsYyz.png" /><figcaption><a href="https://a2a-protocol.org/latest/#why-a2a-matters">https://a2a-protocol.org/latest/#why-a2a-matters</a></figcaption></figure><p>Molto brevemente: gli agenti sono applicazioni intelligenti e comunicano tra loro, diciamo orizzontalmente, tramite il protocollo A2A, pensato appositamente per questo scopo.</p><p>Al contrario, quando gli agenti necessitino di accedere a risorse (quali tabelle database, servizi web, file system, ecc.) devono usare, verticalmente, il protocollo MCP.</p><p>Sulla carta, dunque, tutto appare chiaro: i due protocolli possono convivere perseguendo obiettivi e finalità distinte. Riassumendo:</p><ul><li>gli agenti sono applicazioni intelligenti, i server MCP non lo sono;</li><li>la comunicazione tra agenti utilizza A2A ed è prevalentemente remota, quella tra agente e risorse è mediata da MCP server residente, il più delle volte, in locale;</li></ul><p>I due protocolli sono davvero così indipendenti? Non potrebbero essere usati in modi diversi da quelli dichiarati? Verifichiamo.</p><h3>Utenti maleducati: il nostro esempio</h3><p>Approfondiremo la conoscenza dei due standard realizzando una piccola applicazione composta da due agenti (Python con ADK) e un server MCP (Java con Spring AI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*6zmsfxfaMMnagEgYltvi_Q.png" /></figure><p>L’agente principale, main agent, come primo passo consulta l’agente remoto tramite il protocollo A2A. Poi contatta un MCP server locale ed infine risponde al cliente.</p><p>Il sistema sarà progettato per gestire clienti maleducati (sì, esistono 😀): l’agente remoto misura il grado di ostilità in una scala da 1 a 10 consentendo all’agente principale di rispondere appropriatamente, ad esempio chiedendo di abbassare i toni. Fatto ciò, l’agente principale contatta il server MCP per sapere dove si trovi la spedizione del cliente: anche se maleducato merita una risposta.</p><p>Di seguito un esempio di conversazione: a destra la richiesta dell’utente, a sinistra le chiamate all’agente remoto (icona dell’automa bianco con JSON come risposta) e al server MCP (il <em>tool </em>denominato<em> getTrackingEventsForShipment</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5W22V9UGtAIhU1O99CpPQ.png" /></figure><p>Nei prossimi paragrafi realizzeremo i tre componenti pensati come tutorial per le librerie Spring AI e ADK in modo da poter verificare con mano il funzionamento dei due protocolli.</p><h3>MCP Server</h3><p>Il patrimonio di applicazioni e servizi web disponibile in azienda può essere reso accessibile ai modelli di AI in modo relativamente agevole attraverso il protocollo MCP e le molte librerie che lo implementano. Riprendendo il discorso iniziato qualche mese fa in una <a href="https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-parte-ii-03532dc4639f">serie</a> di miei articoli relativi a Spring AI, possiamo avanzare di un passo verso l’ammaliante mondo dell’AI modificando le nostre classi a livello di servizio, annotate dunque con @Service, affinché i metodi rilevanti siano esposti tramite MCP.</p><p>Se la nostra applicazione Spring è progettata bene, con competenze chiare, non sovrapposte sui diversi livelli e se rispetta il principio di inversione delle dipendenze, la modifica richiesta al codice non sarà nulla più che l’aggiunta di un paio di annotazioni fornite dalla libreria Spring AI:</p><pre>@Service<br>public class TrackingService {<br><br>    @Tool(description = &quot;Get the tracking events for a specific shipment identified by the shipment number&quot;)<br>    public List&lt;TrackingEvent&gt; getTrackingEventsForShipment(<br>        @ToolParam(description = &quot;14 digit shipment number&quot;) <br>              String shipmentNumber ) {<br><br>        return TrackingEvent.generateMockEvents();<br>    }<br><br>}</pre><p>Sembra facile e, in effetti, lo è a patto di ricordare che i modelli di AI necessitano di nomenclature chiare per i metodi, i loro parametri e le classi coinvolte nella chiamata. Se il codice legacy usasse delle abbreviazioni, termini equivoci o DTO troppo estesi, innestati o complicati i modelli di AI non sapranno costruire correttamente le chiamate o capire quando effettuarle.</p><p>Nell’esempio, abbiamo usato le annotazione <em>@Tool</em> e <em>@ToolParam</em> per descrivere ai modelli lo scopo e la modalità di impiego di un servizio per fare il track and trace di spedizioni già presente in azienda: il nome stesso del metodo è stato rifattorizzato per risultare più chiaro all’AI.</p><p>Come chiarito altrove, OpenAI ha inaugurato il termine <em>tool </em>per riferirsi essenzialmente a chiamate remote a funzioni; questo tipo di interazione è una delle tre previste dal protocollo MCP, come verificheremo tra poco. Per esporre i metodi della nostra applicazione legacy attraverso <em>tool</em> MCP, non bastano le annotazioni già aggiunte ma è richiesta la seguente semplice configurazione.</p><pre>@Bean<br>public ToolCallbackProvider weatherTools(TrackingService trackingService) {<br>    return MethodToolCallbackProvider.builder()<br>                                     .toolObjects(trackingService)<br>                                     .build();<br>}</pre><p>Compiliamo e lanciamo il nostro server ricordandoci di lasciare aperto il terminale per non chiudere l’applicazione. L’API key per utilizzare gratuitamente il modello Gemini può essere generata collegandosi al Google Ai Studio.</p><pre>GEMINI_API_KEY=your-gemini-api-key ./gradlew bootRun</pre><p>Testiamo l’applicazione con MCP Inspector, un utile e completo strumento per sviluppatori indicato in bibliografia, rimandando alle pagine ufficiali per la semplice installazione. Nella spalla di sinistra dell’interfaccia web, indichiamo come protocollo SSE (Server-Sent Events) e come indirizzo <a href="http://localhost:8080/sse">http://localhost:8080/sse</a>, poi premiamo il bottone [connect].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhu-xPfgJz9MQNBVCJsa9g.png" /></figure><p>Se tutto è andato per il vero giusto, possiamo iniziare l’esplorazione del protocollo MCP sfruttando l’interfaccia web dell’inspector. Troviamo la prima chiamata al nostro MCP server nel pannello in basso al centro, denominato history. La riporto qui:</p><pre># Client Request<br>{<br>  &quot;method&quot;: &quot;initialize&quot;<br>}<br><br># MCP Server Response<br>{<br>  &quot;capabilities&quot;: {<br>    &quot;logging&quot;: {},<br>    &quot;completions&quot;: {},<br>    &quot;prompts&quot;: {<br>      &quot;listChanged&quot;: true<br>    },<br>    &quot;resources&quot;: {<br>      &quot;subscribe&quot;: false,<br>      &quot;listChanged&quot;: true<br>    },<br>    &quot;tools&quot;: {<br>      &quot;listChanged&quot;: true<br>    }<br>  },<br>  &quot;serverInfo&quot;: {<br>    &quot;name&quot;: &quot;mcp-server&quot;,<br>    &quot;version&quot;: &quot;0.0.1&quot;<br>  }<br>}</pre><p>Questa prima chiamata consente al client di conoscere le <em>capabilities</em> offerte dal server MCP tra quelle previste dal protocollo. Vediamo le principali:</p><ul><li><strong>tools:</strong> il server espone strumenti eseguibili con parametri specifici, quindi funzioni, che il client può invocare per eseguire azioni mirate. <em>Esempio:</em> il nostro metodo per il track and trace di una spedizione.</li><li><strong>prompts:</strong> il server può fornire una lista di prompt predefiniti o modelli di prompt che il client può usare per semplificare l’interazione. <em>Esempio:</em> un client che mostra all’utente un elenco di comandi pronti, come “Traduci in inglese” o “Riassumi questo testo”.</li><li><strong>resources:</strong> il server mette a disposizione risorse come file, dataset o connessioni a servizi esterni, che il client può consultare o scaricare. <em>Esempio:</em> il server offre un manuale PDF o un archivio di dati a cui l’utente può accedere tramite l’interfaccia del client.</li><li><strong>elicitations:</strong> consente al server di chiedere in modo strutturato al client informazioni mancanti o conferme prima di procedere con un’operazione. <em>Esempio:</em> l’utente chiede di tradurre un testo ma non specifica la lingua di destinazione; il server invia una richiesta di chiarimento “In quale lingua vuoi tradurre?” prima di eseguire il tool.</li><li><strong>logging:</strong> consente a server e client di scambiarsi messaggi di log strutturati attraverso MCP, fuori banda, utili per debug e monitoraggio. <em>Esempio:</em> un IDE che riceve in tempo reale dal server messaggi come “Avviata elaborazione documento” o “Connessione al database riuscita”.</li></ul><p>Se la capability è elencata in risposta al metodo <em>initialize </em>allora il server MCP la implementa. Nella risposta del nostro server, avrete certamente notato anche i campi <em>listChanged </em>e <em>subscribe:</em> il primo è usato per segnalare al client che la lista di oggetti relativa ad una certa capability è stata modificata rispetto alla ultima richiesta. Invece, <em>subscribe=true </em>indica la possibilità di ricevere aggiornamenti nel caso di modifica di una risposta.</p><p>In definitiva, il metodo <em>initialize </em>consente di ottenere una sorta di biglietto da visita del server MCP in cui elencarne le capacità, vedremo come anche il protocollo A2A offra una funzionalità del tutto analoga con le agent card.</p><p>Per quanto riguarda la nostra applicazione di esempio, dobbiamo modificare le configurazioni (ad esempio nel file <em>application.properties</em>) perché millanta delle <em>capabilities</em> non implementate:</p><pre>spring.ai.mcp.server.capabilities.tool=true<br>spring.ai.mcp.server.capabilities.resource=false<br>spring.ai.mcp.server.capabilities.prompt=false<br>spring.ai.mcp.server.capabilities.completion=false<br><br>spring.ai.mcp.server.prompt-change-notification=true<br>spring.ai.mcp.server.tool-change-notification=false<br>spring.ai.mcp.server.resource-change-notification=true</pre><p>Rilanciando e riconnettendo l’inspector, otteniamo una risposta più realistica al metodo <em>initialize</em>.</p><pre>{<br>  &quot;capabilities&quot;: {<br>    &quot;logging&quot;: {},<br>    &quot;tools&quot;: {<br>      &quot;listChanged&quot;: false<br>    }<br>  },<br>  &quot;serverInfo&quot;: {<br>    &quot;name&quot;: &quot;mcp-server&quot;,<br>    &quot;version&quot;: &quot;0.0.1&quot;<br>  }<br>}</pre><p>Per ottenere l’elenco dei <em>tool</em> offerti, scegliamo nel menu in alto dell’inspector la voce omonima e invochiamo il metodo <em>tools/list</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovQAb_ufGqjpwmTJzumOEw.png" /></figure><p>Possiamo così verificare che il nostro server MCP riporti correttamente il metodo Java <em>getTrackingEventsForShipment </em>con la descrizione precisa dei parametri richiesti, il loro nome e il loro tipo. Vedremo che A2A non presenta un dettaglio simile.</p><pre>{<br>  &quot;tools&quot;: [<br>    {<br>      &quot;name&quot;: &quot;getTrackingEventsForShipment&quot;,<br>      &quot;description&quot;: &quot;Get the tracking events for a specific shipment identified by the shipment number&quot;,<br>      &quot;inputSchema&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>          &quot;shipmentNumber&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;description&quot;: &quot;14 digit shipment number&quot;<br>          }<br>        },<br>        &quot;required&quot;: [<br>          &quot;shipmentNumber&quot;<br>        ],<br>        &quot;additionalProperties&quot;: false<br>      }<br>    }<br>  ]<br>}</pre><p>Infine, il metodo MCP <em>tools/call</em> consente l’invocazione remota del nostro metodo passando i parametri richiesti:</p><pre># Client Request<br>{<br>  &quot;method&quot;: &quot;tools/call&quot;,<br>  &quot;params&quot;: {<br>    &quot;name&quot;: &quot;getTrackingEventsForShipment&quot;,<br>    &quot;arguments&quot;: {<br>      &quot;shipmentNumber&quot;: &quot;12345678901234&quot;<br>    },<br>    &quot;_meta&quot;: {<br>      &quot;progressToken&quot;: 0<br>    }<br>  }<br>}<br><br># MCP Server Response<br>{<br>  &quot;content&quot;: [<br>    {<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;text&quot;: &quot;[{\&quot;timestamp\&quot;:[2025,8,22,8,59,46,298953315],\&quot;depot\&quot;:\&quot;Bologna\&quot;,\&quot;event\&quot;:\&quot;IN_DEPOT\&quot;},{\&quot;timestamp\&quot;:[2025,8,22,10,59,46,298953315],\&quot;depot\&quot;:\&quot;Bologna\&quot;,\&quot;event\&quot;:\&quot;SHIPPED\&quot;},{\&quot;timestamp\&quot;:[2025,8,23,2,59,46,298953315],\&quot;depot\&quot;:\&quot;Lione\&quot;,\&quot;event\&quot;:\&quot;IN_DEPOT\&quot;},{\&quot;timestamp\&quot;:[2025,8,23,14,59,46,298953315],\&quot;depot\&quot;:\&quot;Parigi\&quot;,\&quot;event\&quot;:\&quot;IN_DEPOT\&quot;},{\&quot;timestamp\&quot;:[2025,8,23,20,59,46,298953315],\&quot;depot\&quot;:\&quot;Parigi\&quot;,\&quot;event\&quot;:\&quot;DELIVERY\&quot;},{\&quot;timestamp\&quot;:[2025,8,24,0,59,46,298953315],\&quot;depot\&quot;:\&quot;Parigi\&quot;,\&quot;event\&quot;:\&quot;DELIVERED\&quot;}]&quot;<br>    }<br>  ],<br>  &quot;isError&quot;: false<br>}</pre><p>Concludendo, anche da questo breve tour, il protocollo MCP appare a tutti gli effetti progettato per disciplinare la comunicazione tra un agente intelligente ed un server senza AI in grado di servire risorse (file, directory, database, ecc.) ma anche <em>tool</em> (funzioni). Il proliferare di server MCP, si veda ad esempio <a href="https://www.pulsemcp.com/servers">pulseMCP</a> o <a href="https://mcpmarket.com/server">MCPMarket</a>, testimonia l’adesione entusiasta di sviluppatori e aziende a questo comodo protocollo.</p><h3>A2A enabled remote agent</h3><p>Veniamo adesso al nostro agente remoto: come detto, deve valutare l’ostilità della richiesta del cliente su una scala da 1 (amichevole) a 10 (furioso). Questa volta, utilizzeremo la nuova libreria di Google denominata semplicemente Agent Development Kit (ADK). Il codice si riduce a poche righe:</p><pre>class Response(BaseModel):<br>    costumer_request: str = Field(description=&quot;the original customer request&quot;)<br>    hostility_degree: int = Field(description=&quot;the hostility tone of user request on a scale from 1 (friendly) to 10 (furious)&quot;)<br><br>root_agent = Agent(<br>    name=&quot;sentiment_agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;A specialized agent for sentiment analysis that evaluates the hostility &quot;<br>                &quot;tone of user request on a scale from 1 (friendly) to 10 (furious).&quot;,<br>    instruction=&quot;&quot;&quot;<br>        You are a sentiment analysis agent.         <br>    &quot;&quot;&quot;,<br>    output_schema=Response,<br>)</pre><p>I parametri del costruttore dovrebbero risultare chiari: stiamo istanziando un agente denominato <em>sentiment_agent </em>(gli spazi non sono ammessi) che utilizza l’ottimo modello <em>gemini-2.0-flash</em> chiamandolo da remoto, dunque come SaaS. Lo user prompt è specificato nel campo <em>instruction</em> a cui viene accodato la richiesta vera e propria del cliente vero. Sarebbe possibile aggiungere anche il system prompt nel campo <em>system_instruction.</em></p><p>Infine, il campo <em>output_schema </em>forza il modello a restituire in risposta la rappresentazione JSON della classe Response, dichiarata poco sopra e commentata opportunamente.</p><blockquote>Sul campo <em>description</em> c’è un po’ di confusione: molti articoli online suggeriscono che serva solo per fini documentali e non sia passata al modello utilizzato (es. <em>gemini-2.0-flash</em>). Se quest’ultima osservazione è senz’altro vera, la prima è dubbia in quanto, come vedremo, la descrizione viene spesso esposta dal protocollo A2A per descrivere le abilità offerta ad un agente remoto, quindi ad un altro modello di AI esterno. Suggerisco dunque di compilare scrupolosamente il campo <em>description </em>in termini comprensibili per un *LM.</blockquote><p>Esistono diversi modi per esporre il servizio tramite A2A, per le finalità di questo articolo, più orientato al confronto tra protocolli che all’esplorazione di ADK, sceglieremo la via più veloce, ovvero quella che ci genera autonomamente l’agent card. Si riduce tutto alla seguente riga:</p><pre>a2a_app = to_a2a(root_agent, port=8001)</pre><p>Poi, dalla cartella remote-agent, lanciamo l’agente:</p><pre>echo &quot;GOOGLE_API_KEY=your_api_key_here&quot; &gt;&gt; remote_agent/.env<br>poetry install<br>poetry run uvicorn remote_agent.agent:a2a_app --host localhost --port 8001</pre><p>Come nel caso del server MCP, verifichiamo l’adesione al protocollo A2A grazie all’applicazione open source <em>a2a-inspector,</em> da installare e lanciare seguendo le istruzioni ufficiali. Apriamo il browser su <em>localhost:5001</em> e inseriamo l’indirizzo del nostro agente <em>localhost/8001 </em>nella text box in alto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*g1SToy3LafX05ue6HxhUFw.png" /></figure><p>L’equivalente A2A del metodo MCP <em>initialize </em>consiste nel recuperare l’agent card, una sorta di biglietto da visita dell’agente che ne descrive le funzionalità in termini, essenzialmente ma non solo, di <em>skills</em>. Vediamolo nel dettaglio:</p><pre>{<br>  &quot;capabilities&quot;: {},<br>  &quot;defaultInputModes&quot;: [<br>    &quot;text/plain&quot;<br>  ],<br>  &quot;defaultOutputModes&quot;: [<br>    &quot;text/plain&quot;<br>  ],<br>  &quot;description&quot;: &quot;A specialized agent for sentiment analysis that evaluates the hostility tone of user request on a scale from 1 (friendly) to 10 (furious).&quot;,<br>  &quot;name&quot;: &quot;sentiment_agent&quot;,<br>  &quot;preferredTransport&quot;: &quot;JSONRPC&quot;,<br>  &quot;protocolVersion&quot;: &quot;0.3.0&quot;,<br>  &quot;skills&quot;: [<br>    {<br>      &quot;description&quot;: &quot;A specialized agent for sentiment analysis that evaluates the hostility tone of user request on a scale from 1 (friendly) to 10 (furious). \n        I am a sentiment analysis agent. \n        Read the provided customer request and return *only* a JSON object\n        like the following:\n        {   \n            \&quot;costumer_request\&quot;: \&quot;the original customer request\&quot;,\n            \&quot;hostility_degree\&quot;: n\n        }\n        Where n is an integer between 1 (friendly) and 10 (furious).\n    &quot;,<br>      &quot;id&quot;: &quot;sentiment_agent&quot;,<br>      &quot;name&quot;: &quot;model&quot;,<br>      &quot;tags&quot;: [<br>        &quot;llm&quot;<br>      ]<br>    }<br>  ],<br>  &quot;supportsAuthenticatedExtendedCard&quot;: false,<br>  &quot;url&quot;: &quot;http://localhost:8001&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;<br>}</pre><p>Con il termine <em>skills </em>si intendono le abilità offerte dall’agente, nel nostro esempio abbiamo solo <em>sentiment_agent (</em>la descrizione è quella indicata nel codice). Ogni <em>skill </em>è fruita tramite una chiamata remota a funzione, e qui il discorso si fa interessante: al contrario di MCP, i parametri in ingresso (o uscita) sono <em>standardizzati</em> nel solo tipo Messagge che contiene una collezione di Part.</p><pre>/**<br> * Represents a single message in the conversation between a user and an agent.<br> */<br>export interface Message {<br>  * An array of content parts that form the message body. A message can be<br>   * composed of multiple parts of different types (e.g., text and files).<br>   */<br>  parts: Part[];<br>...</pre><p>Queste parti, poi, possono essere di soli tre tipi predefiniti: Text, File e Data (quest’ultimo contiene un oggetto JSON). Lo stesso messaggio può quindi contenere parti di tipo diverso, ad esempio un’immagine e del testo.</p><p>A2A, dunque, non prevede per le <em>skill </em>l’elencazione libera dei parametri con nomi e tipi ma una mera indicazione del content MIME relativo alle parti passate, ad esempio <em>text/plain</em> o <em>image/jpeg. </em>I campi <em>defaultInputModes</em> e <em>defaultOutputModes, </em>nel nostro esempio, specificano il content MIME di default del nostro agente.</p><p>Un’altra differenza rilevante rispetto a MCP è l’assenza di <em>resources</em>, <em>prompt</em> e le altre <em>capabilities</em> quindi A2A sembra offrire una minore flessibilità (tipi predefiniti e essenza dei nomi dei parametri) confermando di essere progettato per il solo specifico compito di disciplinare la comunicazione tra agenti.</p><blockquote>Eppure, notiamo come sia tecnicamente possibile usare A2A per effettuare qualsiasi tipo di chiamata remota: ad esempio, elencando i parametri nella descrizione dello <em>skill</em> ed aspettarsi che il client li passai dentro una Part di tipo Data. Oppure, come estensione al protocollo, nel campo <em>metadata </em>presente a diverso livello.</blockquote><p>Ora proviamo ad effettuare una chiamata usando l’input text box in fondo all’a2a inspector: passiamo la richiesta di un cliente per verificarne il grado di ostilità e poi apriamo la console per leggere il payload della chiamata.</p><pre>{<br>  &quot;id&quot;: &quot;msg-1756282486850-c81izwfzc&quot;,<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;method&quot;: &quot;message/send&quot;,<br>  &quot;params&quot;: {<br>    &quot;configuration&quot;: {<br>      &quot;acceptedOutputModes&quot;: [<br>        &quot;text/plain&quot;,<br>        &quot;video/mp4&quot;<br>      ]<br>    },<br>    &quot;message&quot;: {<br>      &quot;kind&quot;: &quot;message&quot;,<br>      &quot;messageId&quot;: &quot;msg-1756282486850-c81izwfzc&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;where the hecks is my shipment, damn it&quot;<br>        }<br>      ],<br>      &quot;role&quot;: &quot;user&quot;<br>    }<br>  }<br>}</pre><p>Il metodo invocato si chiama <em>message/send, </em>il nostro client si rende disponibile ad accettare messaggi di testo e video, come indicato nel campo <em>acceptedOutputModes</em>. Concentriamo ora la nostra attenzione sul contenuto vero e proprio della richiesta per vedere all’opera il campo <em>message, </em>di tipo Message contenente le parti (<em>parts</em>) di cui abbiamo parlato. In questo caso una sola di tipo text contenente il messaggio dell’utente.</p><p>Ecco la risposta del nostro agente:</p><pre><br>{<br>  &quot;artifacts&quot;: [<br>    {<br>      &quot;artifactId&quot;: &quot;a23d5784-127c-480c-b716-3158316ac026&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;{\n\&quot;costumer_request\&quot;: \&quot;where the hecks is my shipment, damn it\&quot;,\n\&quot;hostility_degree\&quot;: 9\n}&quot;<br>        }<br>      ]<br>    }<br>  ],<br>  &quot;contextId&quot;: &quot;71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>  &quot;history&quot;: [<br>    --omissis--<br>    {<br>      &quot;contextId&quot;: &quot;71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>      &quot;kind&quot;: &quot;message&quot;,<br>      &quot;messageId&quot;: &quot;msg-1756282486850-c81izwfzc&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;where the hecks is my shipment, damn it&quot;<br>        }<br>      ],<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;taskId&quot;: &quot;35ca2e79-3a2b-4a38-bedb-fd01f6249659&quot;<br>    },<br>    {<br>      &quot;kind&quot;: &quot;message&quot;,<br>      &quot;messageId&quot;: &quot;cb2d7999-2321-4455-a20d-ba6914b1d287&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;{\n\&quot;costumer_request\&quot;: \&quot;where the hecks is my shipment, damn it\&quot;,\n\&quot;hostility_degree\&quot;: 9\n}&quot;<br>        }<br>      ],<br>      &quot;role&quot;: &quot;agent&quot;<br>    }<br>  ],<br>  &quot;id&quot;: &quot;35ca2e79-3a2b-4a38-bedb-fd01f6249659&quot;,<br>  &quot;kind&quot;: &quot;task&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;adk_app_name&quot;: &quot;sentiment_agent&quot;,<br>    &quot;adk_user_id&quot;: &quot;A2A_USER_71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>    &quot;adk_session_id&quot;: &quot;71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>    &quot;adk_invocation_id&quot;: &quot;e-4d87d690-1c50-4c8b-a606-62610e5cd965&quot;,<br>    &quot;adk_author&quot;: &quot;sentiment_agent&quot;,<br>    --omissis-- <br>    &quot;totalTokenCount&quot;: 167<br>    }<br>  },<br>  &quot;status&quot;: {<br>    &quot;state&quot;: &quot;completed&quot;,<br>    &quot;timestamp&quot;: &quot;2025-08-27T08:14:48.653439+00:00&quot;<br>  },<br>  &quot;validation_errors&quot;: []<br>}</pre><p>Un po’ prolisso: iniziamo dal campo <em>artifacts </em>dove troviamo la risposta definitiva dell’agente, quindi il JSON con la misura di ostilità. Da notare come sia stato passato in una Part di tipo <em>text</em>, come richiesto dal client.</p><p>Il campo <em>history </em>elenca, in ordine, richieste e risposte mentre <em>status </em>ci conferma che la conversazione è completata.</p><h3>Main agent</h3><p>Main agent ha il compito di orchestrare le chiamate ad agenti remoti e server MCP. È spesso indicato col nome di <em>host agent. </em>Nel nostro caso, come detto, dovrà rispondere ad ogni richiesta dell’utente consultando prima l’agente remoto tramite A2A e poi ricercare la spedizione ricorrendo al server MCP locale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*ngXTEnsqnXLxFwsMec1oBg.png" /></figure><p>ADK consente di implementarlo agevolmente usando una sequenza di agenti, o meglio un agente sequenziale, che richiami i due agenti (remoto e locale) in sequenza:</p><pre>root_agent = SequentialAgent(<br>    name=&quot;pipeline_agent&quot;,<br>    sub_agents=[sentiment_agent, tracking_agent],<br>)</pre><p>Il primo dei due agenti, <em>sentiment_agent</em>, è quello remoto, definito molto semplicemente così:</p><pre>sentiment_agent = RemoteA2aAgent(<br>    name=&quot;sentiment_agent&quot;,<br>    description=&quot;Agent to detect customer sentiment.&quot;,<br>    agent_card=&quot;http://localhost:8001/.well-known/agent-card.json&quot;,<br>)</pre><p>Importante è l’indicazione delle URL dove recuperare l’agent card, usando la convenzione del well-known path. Il secondo agente è locale, definito così:</p><pre>tracking_agent = Agent(<br>    name=&quot;helpdesk_agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=(&quot;Helpdesk agent of Mercurio express courier companyservice&quot;),<br>    instruction=<br>        &quot;&quot;&quot;You are a polite agent for Mercurio, an European shipping company.<br>        Always respond in a professional and helpful manner, making sure you <br>        have satisfied the customer&#39;s requests.<br>        <br>        Before processing any customer&#39;s request check the customer&#39;s sentiment <br>        in case of negative sentiment, you should spend some words to  <br>        calm the customer before searching for the shipment.<br>        <br>        To track shipments, you need to obtain the 14-digit shipment number.<br>        Use the shipment number to track the shipment status using the right tool.<br>        Do not report the name of the depot if the parcel has been delivered.<br>        &quot;&quot;&quot;<br>    ,<br>    tools=[mcp_toolset],<br>)</pre><p>L’unica novità è costituita dai parametri <em>tools</em> dove troviamo le indicazioni per contattare il nostro MCP server, che sono queste:</p><pre>mcp_toolset = MCPToolset(<br>    connection_params=SseConnectionParams(<br>        url=&quot;http://localhost:8080/sse&quot;<br>    )<br>)</pre><p>L’unico dato rilevante è la URL a cui risponde il server e l’utilizzo di streaming transport (Server-Sent Events).</p><p>Lo sviluppo finisce qui. Lanciamo, compiliamo e testiamo il tutto:</p><pre>echo &quot;GOOGLE_API_KEY=your_api_key_here&quot; &gt;&gt; main_agent/.env<br>poetry install<br>poetry run adk web</pre><p>Questa volta abbiamo usato il comando <em>adk web</em>, che apre l’interfaccia web per l’agente mostrata all’inizio di questo articolo.</p><blockquote>Ricapitolando, il comando adk offre tre modalità per avviare un servizio: <strong>run</strong>, ovvero da console, <strong>api_server</strong> quindi come server e <strong>web</strong>, che offre un’interfaccia utente piuttosto comoda per lo sviluppo.</blockquote><h3>A2A vs MCP or A2A + MCP</h3><p>Tirando le somme, i due protocolli sono veramente complementari? Sulla carta sì. A2A prevede solo chiamate pensate per agenti (con parametri predefiniti) e nessun protocollo locale al contrario di MCP che disciplina chiamate a risorse, prompt, e funzioni con qualsiasi firma. Prevede inoltre la comunicazione locale basata su standard output.</p><p>Ciononostante, e a dispetto delle intenzioni progettuali sincere o meno, entrambi i protocolli consentono di chiamare funzioni remote, in modo più o meno ortodosso. La distinzione tra agenti e <em>tools,</em> poi, non appare così netta nella realtà: se un server MCP, anche il nostro esempio, utilizzasse un modello di AI per implementare i suoi <em>tools, </em>diventerebbe un agente? E se girasse in remoto come già previsto dal protocollo, sarebbe quindi un agente remoto? Dovrebbe allora passare al protocollo A2A o rimanere su MCP?</p><p>Per contro, abbiamo visto come il protocollo A2A consenta, all’atto pratico, l’invocazione remota di qualsiasi tipo di funzione remota passando i parametri, ad esempio, nella parte Data o nel campo <em>metadati: </em>basterebbe una convenzione tra agenti comunicanti o un’estensione formale del protocollo.</p><p>Di più, la necessità di esporre lo stesso metodo contemporaneamente sui due standard non è più solo un’ipotesi scolastica ma è già stata indirizzata da molte librerie, dimostrando tra l’altro la concreta sostituibilità tra i due protocolli. Ad esempio, recentemente si è fatto notare il progetto a2ajava che promette di svolgere il compito automaticamente, tramite un paio di annotazioni. Al nostro esempio, di fatto, basterebbe aggiungere le annotazioni <em>@Tool</em> <em>@Action</em> e poco altro:</p><pre>@Service<br>@Agent(groupName =&quot;groupOfAgent&quot;, groupDescription = &quot;Agent description&quot;)<br>public class TrackingService {<br><br>    @Action(description = &quot;Get the tracking events for a specific shipment identified by the shipment number&quot;)<br>    public List&lt;TrackingEvent&gt; getTrackingEventsForShipment(<br>          String shipmentNumber ) {<br><br>        return TrackingEvent.generateMockEvents();<br>    }<br><br>}</pre><p>Come se non bastassero questi sospetti ad alimentare le preoccupazioni, ci si mette la stessa documentazione ufficiale di A2A quando propone di <a href="https://github.com/a2aproject/a2a-samples/blob/main/samples/python/agents/a2a_mcp/README.md">servire le agent card tramite server MCP</a>. Se praticata, questa strada costringerebbe ad affiancare ad agenti A2A sempre MCP server. Siamo sicuri che sviluppatori e aziende siano disposte a sobbarcarsi l’adozione di due protocolli? Non preferiranno concentrarsi solo su uno dei due per svolgere tutti i compiti?</p><p>Concludendo, a dispetto delle premesse, non sembra così improbabile una sovrapposizione tra i due protocolli e l’avvio di una nuova guerra di cui nessuno, proprio nessuno, sentiva la necessità.</p><h3>Quale protocollo preverrà?</h3><p>Onestamente, non saprei. Costretto con una pistola alla tempia, scommetterei su una versione estesa del protocollo MCP, solo in virtù della sua attuale diffusione.</p><p>Molti filosofi, tra cui Hegel, Vico ma anche mia nonna, sostengono che la storia si ripeta; potrebbe quindi avere senso tornare brevemente ad alcuni scontri tra standard passati. Ad esempio, nei lontani anni ’80 avvenne la sfida tra Betamax e VHS mostrando come la superiorità tecnica non assicuri il successo: vinse il VHS grazie a una durata maggiore, licenze aperte, prezzi più bassi ed effetto rete. Lo stesso accadde in informatica, dove REST e JSON soppiantarono SOAP, più ricco e complesso, proprio perché più semplici e leggeri da adottare. Analogo il caso nello sviluppo Java: gli Enterprise JavaBeans, potenti ma pesanti, furono superati da Spring, flessibile e pragmatico. In tutti questi esempi ha prevalso la soluzione più pratica e accessibile, non la più sofisticata. Col tempo poi, le soluzioni semplici tendono a colmare le proprie lacune e a completarsi funzionalmente.</p><blockquote>Per questo è plausibile che, tra MCP e A2A, solo un protocollo finisca per prevalere sull’altro: non necessariamente il più avanzato o completo, ma quello più <strong>facile</strong> da adottare, meglio documentato e più diffuso<em>.</em></blockquote><h3>Conclusioni</h3><p>Nonostante le intenzioni progettuali, i proclami e le rassicurazioni, A2A e MCP potrebbe non essere così complementari come si dichiarano: già adesso, sono disponibili librerie per esporre contemporaneamente la stessa applicazione tramite i due protocolli. Inoltre, la differenza tra agenti e <em>tools</em> sembra piuttosto labile nella realtà dove un server MCP può ricorrere a modelli di AI e un agente offrire accesso a risorse.</p><p>Nella nostra indagine abbiamo approfondito i due standard, scritto applicazioni in Python ADK e Java Spring AI e tentato di divinare il futuro, molto probabilmente sbagliando, come accade sempre in questi casi. 😀</p><h3>Riferimenti commentati</h3><p><strong>Articoli di confronto tra i protocolli MCP e A2A:</strong></p><ul><li><a href="https://dr-arsanjani.medium.com/complementary-protocols-for-agentic-systems-understanding-googles-a2a-anthropic-s-mcp-47f5e66b6486">https://dr-arsanjani.medium.com/complementary-protocols-for-agentic-systems-understanding-googles-a2a-anthropic-s-mcp-47f5e66b6486</a> A2a vs MCP</li><li><a href="https://www.koyeb.com/blog/a2a-and-mcp-start-of-the-ai-agent-protocol-wars">https://www.koyeb.com/blog/a2a-and-mcp-start-of-the-ai-agent-protocol-wars</a> A2a/MCP war</li><li><a href="https://becomingahacker.org/comparing-mcp-a2a-and-agntcy-in-the-ai-agent-ecosystem-f3234b85c475">https://becomingahacker.org/comparing-mcp-a2a-and-agntcy-in-the-ai-agent-ecosystem-f3234b85c475</a> Confronto tra tre protocolli</li></ul><p><strong>Documentazione ufficiale:</strong></p><ul><li><a href="https://a2a-protocol.org/latest/">a2a-protocol</a> La pagina ufficiale del protocollo a2a;</li><li><a href="https://github.com/a2aproject">a2aproject</a> La code base del protocollo a2a;</li><li><a href="https://github.com/a2aproject/a2a-samples">a2a-samples</a> Molti esempi per diversi linguaggi e framework. Di rilievo la demo che contiene un’applicazione web in grado di collegarsi a qualsiasi agente e visualizzare il traffico;</li><li><a href="https://google.github.io/adk-docs/a2a/quickstart-exposing/">adk-docs/a2a/quickstart-exposing</a> Come esporre usando il protocollo a2a un servizio scritto con adk;</li><li><a href="https://google.github.io/adk-docs/a2a/quickstart-consuming/#start-the-remote-prime-agent-server">adk-docs/remote-prime-agente-server</a> Una guida rapida per scrivere e collegare agenti adk tramite il protocollo a2a;</li><li><a href="https://a2aprotocol.ai/blog/adk-a2a-guide">a2aprotocol.ai/adk-a2a-guide</a> Utile guide per realizzare e comunicare con un agente remoto;</li><li><a href="https://modelcontextprotocol.io/docs/learn/architecture">modelcontextprotocol.io</a> Una pagina descrittiva del protocollo MCP direttamente dal sito ufficiale;</li><li><a href="https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle">modelcontextprotocol.io/lifecycle</a> Ciclo di vita di una conversazione MCP;</li><li><a href="https://docs.spring.io/spring-ai/reference/api/mcp/mcp-overview.html">docs.spring.io/mcp-overview.html</a> Dagli autori di Spring AI, una descrizione concisa ma esaustiva e molto chiara delle funzionalità offerte dal protocollo MCP;</li><li>L’agile libreria <a href="https://github.com/vishalmysore/a2ajava/blob/main/README.MD">a2ajava</a> per esporre i metodi applicazioni Spring su entrambi i protocolli, MCP e A2A;</li></ul><p><strong>Tools:</strong></p><ul><li><a href="https://github.com/modelcontextprotocol/inspector">MCP inspector</a> È uno strumento di sviluppo per testare e debuggare (i nostri) MCP servers;</li><li><a href="https://github.com/a2aproject/a2a-inspector">a2a-inspector</a> Simile al precedente, un po’ più spartano e rivolto ad agenti che implementino il protocollo A2A;</li><li><a href="https://github.com/seekrays/seekchat">seekchat</a> Applicazione desktop in grado di funzionare con diverse AI ed eseguire MCP Server;</li></ul><p><strong>Articoli relativi alla scrittura di agenti A2A e mcp:</strong></p><ul><li><a href="https://medium.com/ai-cloud-lab/building-multi-agent-ai-app-with-googles-a2a-agent2agent-protocol-adk-and-mcp-a-deep-a94de2237200">https://medium.com/ai-cloud-lab/building-multi-agent-ai-app-with-googles-a2a-agent2agent-protocol-adk-and-mcp-a-deep-a94de2237200</a> L’ultimo di una serie di articoli sulla creazione di agenti con ADK;</li><li><a href="https://medium.com/@saphynogenov/mcp-server-with-spring-ai-d38639e6391a">https://medium.com/@saphynogenov/mcp-server-with-spring-ai-d38639e6391a</a> Spring boot MCP server;</li><li><a href="https://medium.com/google-cloud/getting-started-with-google-a2a-a-hands-on-tutorial-for-the-agent2agent-protocol-3d3b5e055127">https://medium.com/google-cloud/getting-started-with-google-a2a-a-hands-on-tutorial-for-the-agent2agent-protocol-3d3b5e055127</a> A2a demo walkthrought</li><li><a href="https://medium.com/google-cloud/a-practical-guide-to-building-multi-agents-ai-systems-with-a2a-2c0e3d77af24">https://medium.com/google-cloud/a-practical-guide-to-building-multi-agents-ai-systems-with-a2a-2c0e3d77af24</a> Un bell’esempio a2a, come creare un server e come esporre delle custom AgentCard;</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0caa06088bf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Tale of Two Standards: Can A2A and MCP Coexist? ❤️or]]></title>
            <link>https://medium.com/@nicolasanti_43152/a-tale-of-two-standards-can-a2a-and-mcp-coexist-%EF%B8%8For-5bd13412cd91?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd13412cd91</guid>
            <category><![CDATA[a2a-protocol]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 08:58:18 GMT</pubDate>
            <atom:updated>2025-09-14T09:02:35.878Z</atom:updated>
            <content:encoded><![CDATA[<p>A hands-on investigation using Python ADK and Java Spring AI to find the common ground and breaking points.</p><blockquote><a href="https://medium.com/@nicolasanti_43152/la-favola-di-due-standard-a2a-e-mcp-possono-davvero-coesistere-%EF%B8%8Fvs-0caa06088bf7">(Leggi la versione italiana)</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70OderDN-SYif4phewtsuA.jpeg" /><figcaption><a href="https://www.majambiente.it/2017/10/06/un-escursione-sicura-riconoscere-e-leggere-la-segnaletica-dei-sentieri/">Original photo</a> edited with Google Gemini 2.5 Flash (aka Nano Banana)</figcaption></figure><p>A few months ago, Google introduced Agent to Agent (A2A), a new open protocol for communication between agents, which it generously <a href="https://developers.googleblog.com/en/google-cloud-donates-a2a-to-linux-foundation/">donated</a> to the Linux Software Foundation. During the presentation, the difference in purpose compared to Anthropic’s Model Context Protocol (MCP) was emphasized. The complementarity between the two protocols, reiterated in many forms and ways, is summarized in the official A2A documentation on the page eloquently titled: <a href="https://a2a-protocol.org/latest/topics/a2a-and-mcp/">A2A ❤️ MCP</a>.</p><p>Despite these efforts, concerns about overlap between the two standards have been raised by several parties, even in rather explicit terms, such as in statements by the CEO of Dagger, former founder and CEO of Docker:</p><blockquote>Anthropic pushes MCP. Google rushes A2A. Welcome to the AI Standard Wars. “But they are complementary! Each standard has a purpose” Oh my sweet summer child. This is war.</blockquote><blockquote><a href="https://x.com/solomonstre/status/1909971067113742732">Solomon Hykes</a></blockquote><p>Recently, OpenAI adopted MCP, and its absence, along with Anthropic’s, at the official A2A presentation (as reported by <a href="https://www.koyeb.com/blog/a2a-and-mcp-start-of-the-ai-agent-protocol-wars#are-a2a-and-mcp-addressing-different-use-cases">Alisdair Broshar</a>) did not go unnoticed.</p><p>In this article, we will compare two protocols, <strong>A2A</strong> and <strong>MCP</strong>, through a practical example. We will avoid an exhaustive discussion in favor of an in-depth analysis of the common and divergent points, with the aim of providing the reader with the information needed to independently choose between the two standards in the immediate future.</p><p>The article is part of a <a href="https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-be6e2f75516e">series</a><strong> </strong>dedicated to companies that already have a codebase rich in services and applications, for example written in Java, and want to make them accessible to AI.</p><p>Another way to read this article is as a tutorial for creating an MCP server in Java with Spring AI and an agent in Python with Google’s Agent Development Kit (ADK).</p><p>The entire source code is available on <a href="https://github.com/nicolinux72/a2a-vs-mcp">github</a>.</p><h3>The theory</h3><p>Google’s official narrative is well represented by the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*xgLTfQr9KP4jsYyz.png" /><figcaption><a href="https://a2a-protocol.org/latest/#why-a2a-matters">https://a2a-protocol.org/latest/#why-a2a-matters</a></figcaption></figure><p>Very briefly: agents are intelligent applications and communicate with each other, horizontally, through the A2A protocol, designed specifically for this purpose.</p><p>On the contrary, when agents need to access resources (such as database tables, web services, file systems, etc.), they must call vertically, so to speak, the MCP protocol.</p><blockquote>On paper, therefore, everything seems clear: the two protocols can coexist while pursuing distinct objectives and purposes.</blockquote><p>To summarize:</p><ul><li>agents are intelligent applications, MCP servers are not.</li><li>“Communication between agents relies on A2A and is primarily remote, whereas communication between agents and resources is mediated by an MCP server, which is typically hosted locally.</li></ul><p>Are the two protocols so independent? Really? Could they be used in ways other than those stated? Let’s check.</p><h3>Rude users: our example</h3><p>We will deepen our understanding of the two standards by creating a small application consisting of two agents (Python with ADK) and an MCP server (Java with Spring AI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*6zmsfxfaMMnagEgYltvi_Q.png" /></figure><p>The main agent first consults the remote agent via the A2A protocol. Then it contacts a local MCP server and finally responds to the customer.</p><p>The system will be designed to handle rude customers (yes, they really exist 😀): the remote agent measures the degree of hostility on a scale of 1 to 10, allowing the main agent to respond appropriately, for example by asking them to tone it down. Once this is done, the main agent contacts the MCP server to find out where the customer’s shipment is: even if rude, they deserve a response.</p><p>Below is an example of a conversation: on the right is the user’s request, on the left are the calls to the remote agent (white robot icon with JSON response) and to the MCP server (the <em>tool</em> named <em>getTrackingEventsForShipment</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5W22V9UGtAIhU1O99CpPQ.png" /></figure><p>In the following paragraphs, we will implement the three components with Spring AI and ADK libraries, to explore firsthand how the two protocols work.</p><p>Please, remember that the entire source code is available on <a href="https://github.com/nicolinux72/a2a-vs-mcp">github</a>.</p><h3>MCP Server</h3><p>The wealth of applications and web services available within a company can be made accessible to AI models relatively easily through the MCP protocol and the many, many libraries that implement it. Returning to the discussion I began a few months ago in a <a href="https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-be6e2f75516e">series</a><strong> </strong>of articles on Spring AI, we can take a step closer to the fascinating world of AI by modifying our service-level classes, annotated with @Service, so that the relevant methods are exposed via MCP.</p><p>If our Spring application is well designed, with clear, non-overlapping responsibilities at different layers, and if it respects the principle of dependency inversion, the required code change will be nothing more than adding a couple of annotations provided by the Spring AI library:</p><pre>@Service<br>public class TrackingService {<br>@Tool(description = &quot;Get the tracking events for a specific shipment identified by the shipment number&quot;)<br>    public List&lt;TrackingEvent&gt; getTrackingEventsForShipment(<br>        @ToolParam(description = &quot;14 digit shipment number&quot;) <br>              String shipmentNumber ) {<br>        return TrackingEvent.generateMockEvents();<br>    }<br>}</pre><p>It seems easy, and indeed it is, as long as you remember that AI models need clear nomenclature for methods, their parameters, and the classes involved in the call. If the legacy code uses abbreviations, ambiguous terms, or overly extended, nested, or complicated DTOs, AI models will not be able to construct calls correctly or understand when to make them.</p><p>In this example, we used the <em>@Tool</em> and <em>@ToolParam</em> annotations to explain to the models the purpose and usage of an existing company service for tracking and tracing shipments. The method name was also refactored to make it clearer.</p><p>As explained <a href="https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-be6e2f75516e">elsewhere</a>, OpenAI has introduced the term <em>tool</em> to refer, essentially, to remote function calls; this type of interaction is one of the three provided by the MCP protocol, as we will see shortly. To expose the methods of our legacy application through MCP <em>tools</em>, the annotations already added are not enough; the following simple configuration is required.</p><pre>@Bean<br>public ToolCallbackProvider weatherTools(TrackingService trackingService) {<br>    return MethodToolCallbackProvider.builder()<br>                                     .toolObjects(trackingService)<br>                                     .build();<br>}</pre><p>Compile and launch your server remembering to leave the terminal open so as not to close the application. The API key to use the Gemini model for free can be generated by connecting to Google AI Studio.</p><pre>GEMINI_API_KEY=your-gemini-api-key ./gradlew bootRun</pre><p>We will test the application with MCP Inspector, a useful and comprehensive tool for developers (listed in the bibliography). Please refer to the official pages for simple installation instructions. In the left sidebar of the web interface, we indicate SSE (Server-Sent Events) as the protocol and <a href="http://localhost:8080/sse">http://localhost:8080/sse</a> as the address, then press the [connect] button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhu-xPfgJz9MQNBVCJsa9g.png" /></figure><p>If everything went well, we can start exploring the MCP protocol using the inspector’s web interface. We find the first call to our MCP server in the panel at the bottom center, called <em>history</em>. Here it is:</p><pre># Client Request<br>{<br>  &quot;method&quot;: &quot;initialize&quot;<br>}<br><br># MCP Server Response<br>{<br>  &quot;capabilities&quot;: {<br>    &quot;logging&quot;: {},<br>    &quot;completions&quot;: {},<br>    &quot;prompts&quot;: {<br>      &quot;listChanged&quot;: true<br>    },<br>    &quot;resources&quot;: {<br>      &quot;subscribe&quot;: false,<br>      &quot;listChanged&quot;: true<br>    },<br>    &quot;tools&quot;: {<br>      &quot;listChanged&quot;: true<br>    }<br>  },<br>  &quot;serverInfo&quot;: {<br>    &quot;name&quot;: &quot;mcp-server&quot;,<br>    &quot;version&quot;: &quot;0.0.1&quot;<br>  }<br>}</pre><p>This first call allows the client to learn about the capabilities offered by the MCP server among those provided by the protocol. Let’s look at the main ones:</p><ul><li><strong>tools</strong>: the server exposes executable tools with specific parameters, i.e., functions that the client can invoke to perform targeted actions. <em>Example</em>: our method for tracking and tracing a shipment.</li><li><strong>prompts</strong>: the server can provide a list of predefined prompts or prompt templates that the client can use to simplify interaction. <em>Example</em>: a client that shows the user a list of ready-made commands, such as “Translate to English” or “Summarize this text.”</li><li><strong>resources</strong>: the server provides resources such as files, datasets, or connections to external services, which the client can consult or download. <em>Example</em>: The server offers a PDF manual or data archive that the user can access through the client interface.</li><li><strong>elicitations</strong>: allows the server to ask the client for missing information or confirmation in a structured way before proceeding with an operation. <em>Example</em>: the user asks to translate a text but does not specify the target language; the server sends a clarification request “Which language do you want to translate to?” before running the tool.</li><li><strong>logging</strong>: allows servers and clients to exchange structured log messages via MCP, out of band, useful for debugging and monitoring. Example: an IDE that receives messages such as “Document processing started” or “Database connection successful” from the server in real time.</li></ul><p>If the capability is listed in response to the initialize method, then the MCP server should implement it. In our server’s response, you will also have noticed the <em>listChanged</em> and <em>subscribe</em> fields: the first is used to notify the client that the list of objects related to a certain capability has been modified since the last request. On the other hand, <em>subscribe=true</em>, indicates the possibility of receiving updates in the event of a response modification.</p><p>Ultimately, the initialize method allows you to obtain a sort of business card for the MCP server listing its capabilities. We will see how the A2A protocol also offers a completely similar functionality with agent cards.</p><p>As for our example application, we need to modify the configurations (for example, in the <em>application.properties</em> file) because it boasts capabilities that are not implemented:</p><pre>spring.ai.mcp.server.capabilities.tool=true<br>spring.ai.mcp.server.capabilities.resource=false<br>spring.ai.mcp.server.capabilities.prompt=false<br>spring.ai.mcp.server.capabilities.completion=false<br>spring.ai.mcp.server.prompt-change-notification=true<br>spring.ai.mcp.server.tool-change-notification=false<br>spring.ai.mcp.server.resource-change-notification=true</pre><p>By restarting and reconnecting the inspector, we get a more realistic response to the <em>initialize</em> method.</p><pre>{<br>  &quot;capabilities&quot;: {<br>    &quot;logging&quot;: {},<br>    &quot;tools&quot;: {<br>      &quot;listChanged&quot;: false<br>    }<br>  },<br>  &quot;serverInfo&quot;: {<br>    &quot;name&quot;: &quot;mcp-server&quot;,<br>    &quot;version&quot;: &quot;0.0.1&quot;<br>  }<br>}</pre><p>To obtain the list of <em>tools</em> offered, select the item of the same name from the top menu of the inspector and invoke the <em>tools/list</em> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovQAb_ufGqjpwmTJzumOEw.png" /></figure><p>We can thus verify that our MCP server correctly reports the Java <em>getTrackingEventsForShipment</em> method with a precise description of the required parameters, their names, and their types. We will see that A2A does not provide similar details.</p><pre>{<br>  &quot;tools&quot;: [<br>    {<br>      &quot;name&quot;: &quot;getTrackingEventsForShipment&quot;,<br>      &quot;description&quot;: &quot;Get the tracking events for a specific shipment identified by the shipment number&quot;,<br>      &quot;inputSchema&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>          &quot;shipmentNumber&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;description&quot;: &quot;14 digit shipment number&quot;<br>          }<br>        },<br>        &quot;required&quot;: [<br>          &quot;shipmentNumber&quot;<br>        ],<br>        &quot;additionalProperties&quot;: false<br>      }<br>    }<br>  ]<br>}</pre><p>Finally, the MCP <em>tools/call</em> method allows remote invocation of our method by passing the required parameters:</p><pre># Client Request<br>{<br>  &quot;method&quot;: &quot;tools/call&quot;,<br>  &quot;params&quot;: {<br>    &quot;name&quot;: &quot;getTrackingEventsForShipment&quot;,<br>    &quot;arguments&quot;: {<br>      &quot;shipmentNumber&quot;: &quot;12345678901234&quot;<br>    },<br>    &quot;_meta&quot;: {<br>      &quot;progressToken&quot;: 0<br>    }<br>  }<br>}<br><br># MCP Server Response<br>{<br>  &quot;content&quot;: [<br>    {<br>      &quot;type&quot;: &quot;text&quot;,<br>      &quot;text&quot;: &quot;[{\&quot;timestamp\&quot;:[2025,8,22,8,59,46,298953315],\&quot;depot\&quot;:\&quot;Bologna\&quot;,\&quot;event\&quot;:\&quot;IN_DEPOT\&quot;},{\&quot;timestamp\&quot;:[2025,8,22,10,59,46,298953315],\&quot;depot\&quot;:\&quot;Bologna\&quot;,\&quot;event\&quot;:\&quot;SHIPPED\&quot;},{\&quot;timestamp\&quot;:[2025,8,23,2,59,46,298953315],\&quot;depot\&quot;:\&quot;Lione\&quot;,\&quot;event\&quot;:\&quot;IN_DEPOT\&quot;},{\&quot;timestamp\&quot;:[2025,8,23,14,59,46,298953315],\&quot;depot\&quot;:\&quot;Parigi\&quot;,\&quot;event\&quot;:\&quot;IN_DEPOT\&quot;},{\&quot;timestamp\&quot;:[2025,8,23,20,59,46,298953315],\&quot;depot\&quot;:\&quot;Parigi\&quot;,\&quot;event\&quot;:\&quot;DELIVERY\&quot;},{\&quot;timestamp\&quot;:[2025,8,24,0,59,46,298953315],\&quot;depot\&quot;:\&quot;Parigi\&quot;,\&quot;event\&quot;:\&quot;DELIVERED\&quot;}]&quot;<br>    }<br>  ],<br>  &quot;isError&quot;: false<br>}</pre><p>In conclusion, even from this brief overview, the MCP protocol clearly emerges as a framework for managing communication between an intelligent agent and a non-AI server that provides resources (such as files, directories, or databases) as well as tools (functions). The growing number of MCP servers — see <a href="https://www.pulsemcp.com/servers">pulseMCP</a> or <a href="https://mcpmarket.com/server">MCPMarket</a>— demonstrates the enthusiastic adoption of this convenient protocol by both developers and companies.</p><h3>A2A enabled remote agent</h3><p>Now let’s move on to our remote agent: as mentioned, it must evaluate the hostility of the customer’s request on a scale from 1 (friendly) to 10 (furious). This time, we will use Google’s new library simply called Agent Development Kit (ADK). The code boils down to a few lines:</p><pre>class Response(BaseModel):<br>    costumer_request: str = Field(description=&quot;the original customer request&quot;)<br>    hostility_degree: int = Field(description=&quot;the hostility tone of user request on a scale from 1 (friendly) to 10 (furious)&quot;)<br><br>root_agent = Agent(<br>    name=&quot;sentiment_agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=&quot;A specialized agent for sentiment analysis that evaluates the hostility &quot;<br>                &quot;tone of user request on a scale from 1 (friendly) to 10 (furious).&quot;,<br>    instruction=&quot;&quot;&quot;<br>        You are a sentiment analysis agent.         <br>    &quot;&quot;&quot;,<br>    output_schema=Response,<br>)</pre><p>The constructor parameters should be clear: we are instantiating an agent called <em>sentiment_agent</em> (spaces are not allowed) that uses the excellent <em>gemini-2.0-flash</em> model, calling it remotely, i.e., as SaaS. The user prompt is specified in the <em>instruction</em> field, to which the actual request from the real customer is appended. It would also be possible to add the system prompt in the <em>system_instruction</em> field, not used in our example.</p><p>Finally, the <em>output_schema</em> field forces the model to return the JSON representation of the Response class, declared above and commented appropriately.</p><blockquote>There is some confusion regarding the <em>description</em> field: many online articles suggest that it is only used for documentation purposes and has not been transferred to the model used (e.g., <em>gemini-2.0-flash</em>). While the latter observation is certainly true, the former is doubtful because, as we will see, the description is often used by the A2A protocol to describe the skills offered to a remote agent, i.e., to another external AI model. I therefore suggest that you carefully fill in the description field in terms that are understandable to an *LM.</blockquote><p>There are several ways to expose the service via A2A. For the purposes of this article, which is more focused on comparing protocols than exploring ADK, we will choose the fastest route, i.e., the one that automatically generates the agent card for us. It all boils down to the following line:</p><pre>a2a_app = to_a2a(root_agent, port=8001)</pre><p>Then, from the remote-agent folder, launch the agent:</p><pre>echo &quot;GOOGLE_API_KEY=your_api_key_here&quot; &gt;&gt; remote_agent/.env<br>poetry install<br>poetry run uvicorn remote_agent.agent:a2a_app --host localhost --port 8001</pre><p>As with the MCP server, we verify compliance with the A2A protocol using the open-source application<em> a2a-inspector</em>, which must be installed and launched following the official instructions. Open your browser at <em>localhost:5001</em> and enter the address of your agent <em>localhost/8001</em> in the text box at the top:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*g1SToy3LafX05ue6HxhUFw.png" /></figure><p>The A2A equivalent of the MCP <em>initialize</em> method consists of retrieving the agent card, a sort of business card for the agent that describes its capabilities in terms of <em>skills</em>, essentially but not exclusively. Let’s take a closer look:</p><pre>{<br>  &quot;capabilities&quot;: {},<br>  &quot;defaultInputModes&quot;: [<br>    &quot;text/plain&quot;<br>  ],<br>  &quot;defaultOutputModes&quot;: [<br>    &quot;text/plain&quot;<br>  ],<br>  &quot;description&quot;: &quot;A specialized agent for sentiment analysis that evaluates the hostility tone of user request on a scale from 1 (friendly) to 10 (furious).&quot;,<br>  &quot;name&quot;: &quot;sentiment_agent&quot;,<br>  &quot;preferredTransport&quot;: &quot;JSONRPC&quot;,<br>  &quot;protocolVersion&quot;: &quot;0.3.0&quot;,<br>  &quot;skills&quot;: [<br>    {<br>      &quot;description&quot;: &quot;A specialized agent for sentiment analysis that evaluates the hostility tone of user request on a scale from 1 (friendly) to 10 (furious). \n        I am a sentiment analysis agent. \n        Read the provided customer request and return *only* a JSON object\n        like the following:\n        {   \n            \&quot;costumer_request\&quot;: \&quot;the original customer request\&quot;,\n            \&quot;hostility_degree\&quot;: n\n        }\n        Where n is an integer between 1 (friendly) and 10 (furious).\n    &quot;,<br>      &quot;id&quot;: &quot;sentiment_agent&quot;,<br>      &quot;name&quot;: &quot;model&quot;,<br>      &quot;tags&quot;: [<br>        &quot;llm&quot;<br>      ]<br>    }<br>  ],<br>  &quot;supportsAuthenticatedExtendedCard&quot;: false,<br>  &quot;url&quot;: &quot;http://localhost:8001&quot;,<br>  &quot;version&quot;: &quot;0.0.1&quot;<br>}</pre><p>The term <em>skills</em> refers to the abilities offered by the agent. In our example, we only have <em>sentiment_agent</em> (the description is as indicated in the code). Each skill is used via a remote function call, and this is where things get interesting: unlike MCP, the input (or output) parameters are <em>standardized</em> using the Messagge type, which contains a collection of Parts.</p><pre>/**<br> * Represents a single message in the conversation between a user and an agent.<br> */<br>export interface Message {<br>  * An array of content parts that form the message body. A message can be<br>   * composed of multiple parts of different types (e.g., text and files).<br>   */<br>  parts: Part[];<br>...</pre><p>These parts can only be of three predefined types: Text, File, and Data (the latter contains a JSON object). Finally, the same message can contain several parts of diverse types, for example, an image and text.</p><p>A2A, therefore, does not allow a free listing of skill parameters with their names and types; instead, it only requires specifying the MIME content of the parts being passed — for example, <em>text/plain</em> or <em>image/jpeg</em>. The <em>defaultInputModes</em> and <em>defaultOutputModes</em> fields define the agent’s default MIME content.</p><p>Another significant difference, compared to MCP, is the absence of <em>resources</em>, <em>prompts</em>, and other <em>capabilities</em>, so A2A seems to offer less flexibility (predefined types and essence of parameter names), confirming that it is designed solely for the specific task of regulating communication between agents.</p><blockquote>However, we note that it is technically possible to use A2A to make any kind of remote call: for example, by listing the parameters in the skill description and expecting the client to pass them inside a Data type Part. Or, as an extension to the protocol, in the metadata field present at various layers. More on this later.</blockquote><p>Now let’s try making a call using the text box input at the bottom of the <em>a2a inspector</em>: we pass a customer request to check its hostility level and then open the console to check the request payload.</p><pre>{<br>  &quot;id&quot;: &quot;msg-1756282486850-c81izwfzc&quot;,<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;method&quot;: &quot;message/send&quot;,<br>  &quot;params&quot;: {<br>    &quot;configuration&quot;: {<br>      &quot;acceptedOutputModes&quot;: [<br>        &quot;text/plain&quot;,<br>        &quot;video/mp4&quot;<br>      ]<br>    },<br>    &quot;message&quot;: {<br>      &quot;kind&quot;: &quot;message&quot;,<br>      &quot;messageId&quot;: &quot;msg-1756282486850-c81izwfzc&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;where the hecks is my shipment, damn it&quot;<br>        }<br>      ],<br>      &quot;role&quot;: &quot;user&quot;<br>    }<br>  }<br>}</pre><p>The method invoked is called <em>message/send</em>, and our client is available to accept text and video messages, as indicated in the <em>acceptedOutputModes</em> field. Let’s now focus our attention on the actual content of the request to see the <em>message</em> field in action, which is of type Message, and contains the parts (<em>Part</em> object) we mentioned earlier. In this case, there is only one part of type text containing the user’s message.</p><p>Here is our agent’s response:</p><pre>{<br>  &quot;artifacts&quot;: [<br>    {<br>      &quot;artifactId&quot;: &quot;a23d5784-127c-480c-b716-3158316ac026&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;{\n\&quot;costumer_request\&quot;: \&quot;where the hecks is my shipment, damn it\&quot;,\n\&quot;hostility_degree\&quot;: 9\n}&quot;<br>        }<br>      ]<br>    }<br>  ],<br>  &quot;contextId&quot;: &quot;71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>  &quot;history&quot;: [<br>    --omissis--<br>    {<br>      &quot;contextId&quot;: &quot;71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>      &quot;kind&quot;: &quot;message&quot;,<br>      &quot;messageId&quot;: &quot;msg-1756282486850-c81izwfzc&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;where the hecks is my shipment, damn it&quot;<br>        }<br>      ],<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;taskId&quot;: &quot;35ca2e79-3a2b-4a38-bedb-fd01f6249659&quot;<br>    },<br>    {<br>      &quot;kind&quot;: &quot;message&quot;,<br>      &quot;messageId&quot;: &quot;cb2d7999-2321-4455-a20d-ba6914b1d287&quot;,<br>      &quot;parts&quot;: [<br>        {<br>          &quot;kind&quot;: &quot;text&quot;,<br>          &quot;text&quot;: &quot;{\n\&quot;costumer_request\&quot;: \&quot;where the hecks is my shipment, damn it\&quot;,\n\&quot;hostility_degree\&quot;: 9\n}&quot;<br>        }<br>      ],<br>      &quot;role&quot;: &quot;agent&quot;<br>    }<br>  ],<br>  &quot;id&quot;: &quot;35ca2e79-3a2b-4a38-bedb-fd01f6249659&quot;,<br>  &quot;kind&quot;: &quot;task&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;adk_app_name&quot;: &quot;sentiment_agent&quot;,<br>    &quot;adk_user_id&quot;: &quot;A2A_USER_71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>    &quot;adk_session_id&quot;: &quot;71f674e2-7223-4489-b1ff-abf2a2a80583&quot;,<br>    &quot;adk_invocation_id&quot;: &quot;e-4d87d690-1c50-4c8b-a606-62610e5cd965&quot;,<br>    &quot;adk_author&quot;: &quot;sentiment_agent&quot;,<br>    --omissis-- <br>    &quot;totalTokenCount&quot;: 167<br>    }<br>  },<br>  &quot;status&quot;: {<br>    &quot;state&quot;: &quot;completed&quot;,<br>    &quot;timestamp&quot;: &quot;2025-08-27T08:14:48.653439+00:00&quot;<br>  },<br>  &quot;validation_errors&quot;: []<br>}</pre><p>A bit long-winded: let’s start with the <em>artifacts</em> field, where we find the agent’s final response, followed by the JSON with the hostility score. Note that it has been passed in a text-type Part, as requested by the client.</p><p>The <em>history</em> field lists requests and responses in order, while <em>status</em> confirms that the conversation is complete.</p><h3>Main agent</h3><p>The main agent is responsible for orchestrating calls to remote agents and MCP servers. It is often referred to as the <em>host agent</em>. In our case, as mentioned, it will have to respond to each user request by first consulting the remote agent via A2A and then searching for the shipment using the local MCP server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*ngXTEnsqnXLxFwsMec1oBg.png" /></figure><p>ADK allows you to implement it easily using a sequence of agents, or rather a sequential agent, which calls the two agents (remote and local) in sequence:</p><pre>root_agent = SequentialAgent(<br>    name=&quot;pipeline_agent&quot;,<br>    sub_agents=[sentiment_agent, tracking_agent],<br>)</pre><p>The first of the two agents, <em>sentiment_agent</em>, the remote one, is defined very simply as follows:</p><pre>sentiment_agent = RemoteA2aAgent(<br>    name=&quot;sentiment_agent&quot;,<br>    description=&quot;Agent to detect customer sentiment.&quot;,<br>    agent_card=&quot;http://localhost:8001/.well-known/agent-card.json&quot;,<br>)</pre><p>It is important to indicate the URL where the agent card can be retrieved, using the well-known path convention.</p><p>The second agent is local, defined as follows:</p><pre>tracking_agent = Agent(<br>    name=&quot;helpdesk_agent&quot;,<br>    model=&quot;gemini-2.0-flash&quot;,<br>    description=(&quot;Helpdesk agent of Mercurio express courier companyservice&quot;),<br>    instruction=<br>        &quot;&quot;&quot;You are a polite agent for Mercurio, an European shipping company.<br>        Always respond in a professional and helpful manner, making sure you <br>        have satisfied the customer&#39;s requests.<br>        <br>        Before processing any customer&#39;s request check the customer&#39;s sentiment <br>        in case of negative sentiment, you should spend some words to  <br>        calm the customer before searching for the shipment.<br>        <br>        To track shipments, you need to obtain the 14-digit shipment number.<br>        Use the shipment number to track the shipment status using the right tool.<br>        Do not report the name of the depot if the parcel has been delivered.<br>        &quot;&quot;&quot;<br>    ,<br>    tools=[mcp_toolset],<br>)</pre><p>The only new feature is the <em>tools</em> parameters, where we find the instructions for contacting our MCP server, which are as follows:</p><pre>mcp_toolset = MCPToolset(<br>    connection_params=SseConnectionParams(<br>        url=&quot;http://localhost:8080/sse&quot;<br>    )<br>)</pre><p>The only relevant data is the URL to which the server responds and the use of streaming transport (Server-Sent Events).</p><p>That’s it for development. Let’s launch, compile, and test everything:</p><pre>echo &quot;GOOGLE_API_KEY=your_api_key_here&quot; &gt;&gt; main_agent/.env<br>poetry install<br>poetry run adk web</pre><p>This time we used the <em>adk web</em> command, which opens the web interface for the agent shown at the beginning of this article.</p><blockquote>To summarize, the adk command offers three ways for starting a service: <strong>run</strong>, i.e., from the console; <strong>api_server</strong>, i.e., as a server; and <strong>web</strong>, which offers a rather convenient user interface for development.</blockquote><h3>A2A vs MCP or A2A + MCP</h3><p>So, are the two protocols truly complementary? On paper, yes. A2A only provides calls designed for agents (with predefined parameters) and no local protocol, unlike MCP, which regulates calls to <em>resources</em>, <em>prompts</em>, and <em>functions</em> with any signature. It also provides local communication based on standard output.</p><p>Nevertheless, and regardless of whether the design intentions are sincere or not, both protocols allow remote functions to be called in a more or less orthodox manner. The distinction between agents and <em>tools</em> is not so clear-cut in reality: if an MCP server, even our example, used an AI model to implement its <em>tools</em>, would it become an agent? And if it ran remotely, as already provided for by the protocol, would it then be a remote agent? Should it then switch to the A2A protocol or remain on MCP?</p><p>On the other hand, we have seen how the A2A protocol could allow remote invocation of any type of remote function by passing parameters, for example, in the Data section or in the <em>metadata</em> field: all that would be needed is an agreement between communicating agents or a formal extension of the protocol.</p><p>Furthermore, the need to expose the same method simultaneously on both standards is no longer just a theoretical hypothesis but has already been addressed by many libraries, demonstrating, among other things, the concrete substitutability between the two protocols. For example, the <em>a2ajava</em> project has recently been noted, which promises to perform the task automatically, using a couple of annotations. In our example, in fact, it would be sufficient to add the annotations @Tool, @Action, and little else:</p><pre>@Service<br>@Agent(groupName =&quot;groupOfAgent&quot;, groupDescription = &quot;Agent description&quot;)<br>public class TrackingService {<br>@Action(description = &quot;Get the tracking events for a specific shipment identified by the shipment number&quot;)<br>    public List&lt;TrackingEvent&gt; getTrackingEventsForShipment(<br>          String shipmentNumber ) {<br>        return TrackingEvent.generateMockEvents();<br>    }<br>}</pre><p>As if these suspicions weren’t enough to fuel concerns, the official A2A documentation itself suggests <a href="https://github.com/a2aproject/a2a-samples/blob/main/samples/python/agents/a2a_mcp/README.md">serving agent cards via MCP servers</a>. If implemented, this approach would require MCP servers to always accompany A2A agents. Are we sure that developers and companies are willing to take on the adoption of two protocols? Wouldn’t they prefer to focus on just one of the two to perform all tasks?</p><blockquote>In conclusion, despite the initial assumptions, an overlap between the two protocols — and the onset of a new conflict that no one truly wanted — does not seem all that unlikely.</blockquote><h3>Which protocol will prevail?</h3><p>Honestly, I don’t know. With a gun to my head, I would bet on an extended version of the MCP protocol, simply because of its current prevalence.</p><p>Many philosophers, including Hegel, Vico, and even my grandmother 🙂, argue that history repeats itself; it may therefore be useful to briefly revisit some past clashes between standards. For example, back in the 1980s, there was a battle between Betamax and VHS, showing that technical superiority does not guarantee success: VHS won thanks to its longer life, open licenses, lower prices, and network effect. The same thing happened in computer science, where REST and JSON replaced SOAP, which was richer and more complex, precisely because they were simpler and easier to adopt. The case of Java development is similar: Enterprise JavaBeans, powerful but heavy, were surpassed by Spring Framework, which is flexible and pragmatic. In all these examples, the most practical and accessible solution prevailed, not the most sophisticated one. Over time, simple solutions tend to fill their gaps and become functionally complete.</p><blockquote>For this reason, it is plausible that, between MCP and A2A, only one will prevail over the other: not necessarily the most advanced or complete, but the one that is easiest to adopt, best documented, and most widespread.</blockquote><h3>Conclusions</h3><p>Despite the design intentions, proclamations, and reassurances, A2A and MCP may not be as complementary as claimed: libraries already exist that expose the same application through both protocols. Moreover, the distinction between agents and tools appears blurred in practice, as an MCP server can leverage AI models while an agent can provide access to resources.</p><p>In our investigation, we explored the two standards, wrote applications in Python ADK and Java Spring AI, and attempted to predict the future, most likely getting it wrong, as always happens in these cases 😁.</p><h3>Annotated r<strong>eferences</strong></h3><h4>Articles comparing MCP and A2A protocols:</h4><ul><li><a href="https://dr-arsanjani.medium.com/complementary-protocols-for-agentic-systems-understanding-googles-a2a-anthropic-s-mcp-47f5e66b6486">https://dr-arsanjani.medium.com/complementary-protocols-for-agentic-systems-understanding-googles-a2a-anthropic-s-mcp-47f5e66b6486</a> A2a vs MCP</li><li><a href="https://www.koyeb.com/blog/a2a-and-mcp-start-of-the-ai-agent-protocol-wars">https://www.koyeb.com/blog/a2a-and-mcp-start-of-the-ai-agent-protocol-wars</a> A2a/MCP war</li><li><a href="https://becomingahacker.org/comparing-mcp-a2a-and-agntcy-in-the-ai-agent-ecosystem-f3234b85c475">https://becomingahacker.org/comparing-mcp-a2a-and-agntcy-in-the-ai-agent-ecosystem-f3234b85c475</a> Three protocols</li></ul><p><strong>Official documentation:</strong></p><ul><li><a href="https://a2a-protocol.org/latest/">a2a-protocol</a> official protocol website.</li><li><a href="https://github.com/a2aproject">a2aproject</a> protocol a2a code base.</li><li><a href="https://github.com/a2aproject/a2a-samples">a2a-samples</a> Many examples for different languages and frameworks. Of particular note is the demo containing a web application capable of connecting to any agent and displaying traffic.</li><li><a href="https://google.github.io/adk-docs/a2a/quickstart-exposing/">adk-docs/a2a/quickstart-exposing</a> How to expose a service written with adk using the a2a protocol.</li><li><a href="https://google.github.io/adk-docs/a2a/quickstart-consuming/#start-the-remote-prime-agent-server">adk-docs/remote-prime-agente-server</a> A quick guide to writing and connecting adk agents using the a2a protocol.</li><li><a href="https://a2aprotocol.ai/blog/adk-a2a-guide">a2aprotocol.ai/adk-a2a-guide</a> Useful guides for setting up and communicating with a remote agent.</li><li><a href="https://modelcontextprotocol.io/docs/learn/architecture">modelcontextprotocol.io</a> A page describing the MCP protocol directly from the official website.</li><li><a href="https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle">modelcontextprotocol.io/lifecycle</a> Life cycle of an MCP conversation.</li><li><a href="https://docs.spring.io/spring-ai/reference/api/mcp/mcp-overview.html">docs.spring.io/mcp-overview.html</a> From the authors of Spring AI, a concise but comprehensive and very clear description of the features offered by the MCP protocol.</li><li>The agile library <a href="https://github.com/vishalmysore/a2ajava/blob/main/README.MD">a2ajava</a> to expose Spring application methods on both protocols, MCP and A2A.</li></ul><p><strong>Tools:</strong></p><ul><li><a href="https://github.com/modelcontextprotocol/inspector">MCP inspector</a> It is a development tool for testing and debugging MCP servers.</li><li><a href="https://github.com/a2aproject/a2a-inspector">a2a-inspector</a> Similar to the previous one, a little more basic and aimed at agents who implement the A2A protocol.</li><li><a href="https://github.com/seekrays/seekchat">seekchat</a> Desktop application capable of working with different AIs and running MCP Server.</li></ul><p><strong>Articles related to writing A2A and MCP agents:</strong></p><ul><li><a href="https://medium.com/ai-cloud-lab/building-multi-agent-ai-app-with-googles-a2a-agent2agent-protocol-adk-and-mcp-a-deep-a94de2237200">https://medium.com/ai-cloud-lab/building-multi-agent-ai-app-with-googles-a2a-agent2agent-protocol-adk-and-mcp-a-deep-a94de2237200</a> The last in a series of articles on creating agents with ADK.</li><li><a href="https://medium.com/@saphynogenov/mcp-server-with-spring-ai-d38639e6391a">https://medium.com/@saphynogenov/mcp-server-with-spring-ai-d38639e6391a</a> Spring boot MCP server;</li><li><a href="https://medium.com/google-cloud/getting-started-with-google-a2a-a-hands-on-tutorial-for-the-agent2agent-protocol-3d3b5e055127">https://medium.com/google-cloud/getting-started-with-google-a2a-a-hands-on-tutorial-for-the-agent2agent-protocol-3d3b5e055127</a> A2a demo walkthrought</li><li><a href="https://medium.com/google-cloud/a-practical-guide-to-building-multi-agents-ai-systems-with-a2a-2c0e3d77af24">https://medium.com/google-cloud/a-practical-guide-to-building-multi-agents-ai-systems-with-a2a-2c0e3d77af24</a> A good example of a2a, how to create a server and how to expose custom AgentCards.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd13412cd91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Primer on Backpropagation with a Numerical Example,
Diagrams, and Python Code]]></title>
            <link>https://medium.com/@nicolasanti_43152/a-primer-on-backpropagation-with-a-numerical-example-diagrams-and-python-code-254c0ea2fa49?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/254c0ea2fa49</guid>
            <category><![CDATA[feedforward-networks]]></category>
            <category><![CDATA[numerical-example]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gradient]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 09:50:23 GMT</pubDate>
            <atom:updated>2025-07-27T09:50:23.759Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Primer on Backpropagation with a Numerical Example,<br>Diagrams and Python Code</h3><p><em>A self-contained introduction to the well-known backpropagation algorithm illustrated step by step, providing the mathematical elements necessary for understanding and a numerical example with which to verify what has been learned. A Python script with Keras and TensorFlow to verify the calculations performed completes the exposition (available on </em><a href="https://github.com/nicolinux72/backpropagation"><em>GitHub</em></a><em>).</em></p><p>Introduction Backpropagation, short for backward propagation of errors, is perhaps the most iconic algorithm of modern machine learning. Suffice it to say that, until the mid-1980s, no one believed in the possibility of training a multilayer network anymore! The story is very interesting and reveals how a mistaken belief can delay scientific development even by decades.</p><p>Although the first simple artificial neural network dates back to Mcculloch and Pitts (1943), it was with Rosenblatt (1962) that the theory and hardware needed to implement the first neural network called perceptron were developed. The hardware needed to implement it is depicted in the photos below where we can also see Charles Wightman (project engineer) adjusting Mark I Perceptron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*EUTjHJMm4IyCun5eBAoq1g.png" /></figure><p>Perceptron has several layers but only one trainable so, in modern terms, it is a one-layer neural network, obviously subject to major limitations formally demonstrated by Minsky and Papert (1969). And here we come to the exact moment when machine learning based on neural networks was in danger of being completely abandoned because the two authors firmly believed, although without providing proof, that the same limitations of perceptron would also apply to neural networks with more than one layer (deep learning).</p><p>This widespread belief led to a suspension of interest, funding and research in the period from 1970 to the first half of the 1980s. Among other things, researchers could not pursue the study of multilayer 1 models because there was no way to train them: the techniques used by perceptron were not applicable except for networks with only one layer.</p><p>Then, as sometimes happens, a series of innovations contributed to the revival of neural networks and, among these, the most relevant was the invention1 of the backpropagation algorithm by Rumelhart, Hinton, and Williams (1986). The activation and loss functions had already been made differentiable, and backpropagation allows the derivative (more precisely the gradient) of the loss function to be calculated by moving backwards from the errors (difference between the value predicted by the model and the actual value), going up from the last layer to the first. The most relevant aspect, as we shall see in this article, is the possibility of reusing the calculations already made by the neural network in its forward pass (from the first layer to the last) to calculate the gradient, which saves resources and makes it possible to handle even very deep neural networks.</p><p>We will begin our exposition by recalling the few elements of mathematics necessary for understanding, which are limited to the multiplication of matrices and vectors and the calculation of derivatives of linear functions. We will then formally define a multilayer neural network and focus on a numerical example with two layers. We will use what we have learned to obtain two simple and important derivatives to be used in the last paragraph to obtain the complete backpropagation algorithm. We will test our understanding through some elementary calculations on the example model, followed by a short Python script to verify their correctness.</p><p>Let us proceed, then :-)</p><h3>Matrix multiplication (and little else)</h3><p>Read the full article on <a href="https://github.com/nicolinux72/backpropagation/blob/main/article/backpropagation.pdf">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*ZohfUPRTkS7AdhsFYl3HFw.png" /></figure><h3>Multilayer dense network: formalization</h3><p>Read the full article on <a href="https://github.com/nicolinux72/backpropagation/blob/main/article/backpropagation.pdf">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Gf1CacjAGVObdt7pNz3E8w.png" /></figure><pre>model = keras.Sequential([<br>  layers.Input(shape=(2,)),<br>  layers.Dense(3, activation=&#39;tanh&#39;, use_bias=False),<br>  layers.Dense(2, activation=&#39;linear&#39;, use_bias=False)<br>])</pre><h3>Four simple derivatives (in fact, only two)</h3><p>Read the full article on <a href="https://github.com/nicolinux72/backpropagation/blob/main/article/backpropagation.pdf">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*WBlNO76VOmkg0y2m9vA5tw.png" /></figure><h3>Backpropagation algorithm</h3><p>Read the full article on <a href="https://github.com/nicolinux72/backpropagation/blob/main/article/backpropagation.pdf">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*mtyextosmdXunrYpuucPyA.png" /></figure><h3>Checking the calculations</h3><p>We add code to instruct our script to perform the gradient calculation in order to check the accuracy of our results. When comparing, we take into account the rounding to two decimal digits used in our examples.</p><p>Python code:</p><pre># setup auto-differentiation<br>with tf.GradientTape() as tape:<br>y_pred = model(x) # Forward pass<br>loss = tf.reduce_mean(tf.square(y_true - y_pred)) # MSE (L2)<br># Compute gradient<br>grads = tape.gradient(loss, model.trainable_variables)<br># show gradients for our datapoint (direct)<br>print(&quot;--- Input:&quot;, x.numpy(), &quot;\n&quot;)<br>print(&quot;--- Gradients&quot;)<br>print(f&quot;Layer 1:\n{grads[0].numpy().T}&quot;)<br>print(&quot;Output:&quot;, model.layers[0](x).numpy(), &quot;\n&quot;)<br>print(f&quot;Layer 2:\n{grads[1].numpy().T}&quot;)<br>print(&quot;Output:&quot;, y_pred.numpy(), &quot;\n&quot;)<br>print(&quot;--- Label:&quot;, y_true.numpy(), &quot;\n&quot;)</pre><p>We calculate the gradient using the self-differentiation of TensorFlow.</p><h3>Conclusions</h3><p>In this article, we illustrated the backpropagation algorithm step by step by placing theory side by side with a small neural network used to refine intuition and carry out calculations. We did not skimp on graphs and insights, going as far as implementing a simple Python script using Keras and TensorFlow, available on <a href="https://github.com/nicolinux72/backpropagation">GitHub</a>.</p><h3>References</h3><ul><li>Bishop, Christopher Michael and Hugh Bishop (2023). Deep Learning — Foundations and Concepts. Ed. by Springer Cham. 1st ed. isbn: 978–3–031–45468–4. doi: <a href="https://doi.org/10.1007/978-3-">https://doi.org/10.1007/978-3-</a> 031–45468–4.</li><li>Rumelhart, David E., Geoffrey E. Hinton, and Ronald J. Williams (Oct. 1986). “Learning Representations by Back-propagating Errors”. In: Nature 323. Seminal paper that popularized backpropagation in neural networks., pp. 533–536. 10</li><li>Werbos, Paul J. (1974). “Beyond Regression: New Tools for Prediction and Analysis in the Behavioral Sciences”. First application of backpropagation to neural networks. PhD Dissertation. Harvard University.</li><li>Linnainmaa, Seppo (1970). “Taylor Expansion of the Accumulated Rounding Error”. Introduces reverse mode automatic differentiation, foundational for backpropagation. Master’s Thesis. University of Helsinki.</li><li>Minsky, Marvin and Seymour Papert (1969). Perceptrons: An Introduction to Computational Geometry. Cambridge, MA, USA: MIT Press. Rosenblatt, F. (1962). Principles of Neurodynamics: Perceptrons and the Theory of Brain Mechanisms. Cornell Aeronautical Laboratory. Report no. VG-1196-G-8. Spartan Books. url: <a href="https://books./">https://books.</a> google.it/books?id=7FhRAAAAMAAJ.</li><li>Kelley, Henry J. (1960). “Gradient Theory of Optimal Flight Paths”. In: Journal of the Institute of the Aeronautical Sciences 30.10. Early gradient method in control, precursor to backprop., pp. 947–954.</li><li>Mcculloch, Warren and Walter Pitts (1943). “A Logical Calculus of Ideas Immanent in Nervous Activity”. In: Bulletin of Mathematical Biophysics 5, pp. 127–147.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=254c0ea2fa49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG apps for legacy spring developers — part 2]]></title>
            <link>https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-part-2-e4a6744d0b22?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a6744d0b22</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rag-application]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 07:08:01 GMT</pubDate>
            <atom:updated>2024-09-07T07:08:01.997Z</atom:updated>
            <content:encoded><![CDATA[<h3>RAG apps for legacy spring developers — part 2</h3><p>Introduction to RAG apps and review of the new Spring AI library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ucaYJss_nKV6NugW38M5WA.png" /></figure><p>←<a href="https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-be6e2f75516e"><em>First Part of this article</em></a></p><p>The new Spring AI library is about to be released in version 1.0, what better opportunity to present the operating of RAG applications to us, legacy Java developers?</p><p>If you’ve been using Spring for a lifetime but don’t know anything about LLM, this review will give you a comprehensible explanation of how a chatbot, summarizing or classifying documents, and querying private documents applications works.</p><p>In this field, the langchain python library is the master, so it will be my concern to systematically compare it with the implementation choices of Spring AI.</p><p>Italian prompts can, perhaps, be appreciated, to show a localized use of the famous ChatGPT.</p><p>As usual, the source code of the project is available on <a href="https://github.com/nicolinux72/spring-ai-article">github</a> and you will find a long-annotated bibliography.</p><p>Related Articles:</p><ul><li><a href="https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-b5d5aea66f73">Italian version of this articles</a></li><li><a href="https://medium.com/@nicolasanti_43152/local-code-llama-with-gradio-and-hugging-face-1153112046ec?source=your_stories_page-------------------------------------">Local code llama with gradio and hugging face</a></li><li><a href="https://medium.com/@nicolasanti_43152/bootstrap-a-llama-assistant-on-personal-data-16062fa5aa6d?source=your_stories_page-------------------------------------">Bootstrap a LLaMa assistant on personal data</a></li></ul><h3>Embeddings</h3><p>A natural language sentence can be classified by several characteristics, and each characteristic can be scored between -1 and 1. For example, does the sentence talk about Paris? Does it have a positive feeling? Do sunsets have anything to do with it? Are we talking about the color red? Are we talking about computers? Are we talking about Apple computers?</p><p>At each question or, more precisely, at each quality of the text is assigned a score and the list of these scores forms an array (or a vector/<a href="https://medium.com/@nicolasanti_43152/what-are-tensors-58bc4c751f9f">tensor</a> if you are a mathematician) called embedding, characterized by high dimensionality. ChatGPT, for example, uses 1536 scores.</p><p>Let’s look at a class for producing embeddings:</p><pre>@Service public class EmbeddingsManager {<br><br>  @Autowired EmbeddingModel embeddingModel;<br><br>  public EmbeddingResponse encode(List&lt;String&gt; texts) {<br>          return embeddingModel.call(<br>                  new EmbeddingRequest(texts,<br>                          OpenAiEmbeddingOptions.builder()<br>                                  //.withModel(&quot;text-embedding-ada-002&quot;)<br>                                  .build()));<br>  }<br>}</pre><p>Notes:</p><ul><li>EmbeddingModel is the prototype of the class to produce embeddings using different models, one for concrete implementation;</li><li>Commented line shows how to select a specific model from OpenAI;;</li></ul><p>Here’s a client to create a couple of vectors:</p><pre>EmbeddingResponse encoded = <br>               embeddingsManager.encode(List.of(&quot;Let&#39;s try something&quot;));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*bnmIgSG8NJnJ5A-MI7vsig.png" /></figure><p>Note:</p><ul><li>The debugging session shows the embedding created, just one (size = 1) with all 1536 floats between -1 and 1 in it;</li></ul><p>An embedding only makes sense, it is understandable, only from the model that generated it, so make sure you use the same model for both creation and use.</p><blockquote>One clarification: the semantics encapsulated in an embedding is not distributed orthogonally in the individual dimensions, as I let it be understood in this section, but expressed by the direction of the vectors, that is, by a precise combination of the components. For example, starting with the vector “King” and adding the direction encapsulating the meaning of <em>gender</em>, one should arrive near the vector “Queen.”</blockquote><h3>Vector Database</h3><p>If the embedding represents the content of a text, therefore its semantics, why not persist both, text and vector, on a table? To do this, you need a vector database, also called vector store, so one that can persist and search for vectors:</p><pre>CREATE TABLE IF NOT EXISTS public.vector_store<br>(<br>    id uuid NOT NULL DEFAULT uuid_generate_v4(),<br>    content text COLLATE pg_catalog.&quot;default&quot;,<br>    metadata json,<br>    embedding vector(1536),<br>    CONSTRAINT vector_store_pkey PRIMARY KEY (id)<br>)</pre><p>The DDL (Data Definition Language) above refers to the historic Postgresql, transformed into a vector store by the pgvector extension that threw it into the fray of the new vector databases, which have sprung up on the market like mushrooms in recent years.</p><p>Columns are easy to understand:</p><ul><li><strong>Id</strong>: A uuid used as the primary key;</li><li><strong>Text</strong>: the plain text;</li><li><strong>Metadata</strong>: metadata in json format;</li><li><strong>Embedding</strong>: our vector calculated by LLM;</li></ul><p>Spring AI, and certainly langchain, allow you to save texts, metadata and embeddings in a very simple way:</p><pre>List&lt;Document&gt; documents = List.of(<br>        new Document(getText(&quot;classpath:/data/fatti_curiosi.txt&quot;), <br>        Map.of(&quot;meta1&quot;, &quot;meta1&quot;))<br>        );<br> <br>vectorStore.add(documents);</pre><p>Let’s check that the data are stored in the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*-6E413Ps7xk_6cHRKviyAw.png" /></figure><p>Business documents are stored in a wide variety of formats (pdf, word, json, etc.), so specific classes are needed to read them. Langchain and the llamaindex python library allow you to work with dozens of several types. Spring AI also offers features for the most common formats, such as word:</p><pre>List&lt;Document&gt; readWordDoc() {<br>  var wordDoc = new DefaultResourceLoader().getResource(&quot;classpath:/etl/article.docx&quot;);<br>  TikaDocumentReader tikaDocumentReader = new TikaDocumentReader(wordDoc);<br>  TokenTextSplitter splitter = new TokenTextSplitter(500, 400, 10, 1000, true);<br>  return  splitter.apply(tikaDocumentReader.read());<br>}</pre><p>Notes:</p><ul><li>For this kind of document, Spring AI delegates reading to the Apache Foundation’s excellent Tika library;</li><li>The code loads the Microsoft word version of the article you are reading;</li><li>The last few lines deal with breaking the entire document into smaller parts, sometimes called chunks;</li></ul><p>The latter is a necessary operation because LLMs have insurmountable limits relating to the length of the prompts and the whole document may not fit in them. Also, the larger the document to be analyzed, the longer it takes for the model to respond. Finally, by putting elements unrelated to the user’s request into context, it could confuse the LLM and lead it to respond incorrectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*SyDq_oF93fTx0IkgCHdiog.png" /></figure><p>We then divide the document into smaller parts: in the example we are setting the default, minimum and maximum sizes (in tokens and characters) and putting the ‘\n’ in the chunks.</p><p>A sometimes better approach is to divide document by paragraphs, but much depends on the document dealt with so, unfortunately, there is no general rule for this operation so relevant to the quality of the LLM responses.</p><h3>Retrieval</h3><p>Now, any data is saved in a database just to be able to search and extract it quickly. The novelty offered by vector databases consists in being able to carry out semantic searches, i.e. find documents whose content is similar to a past one. Similar content means nearby embedding vectors.</p><p>The steps are quite simple:</p><pre>public Collection&lt;Document&gt; retreive(String question) {<br>    var fb = new FilterExpressionBuilder();<br>    return vectorStore.similaritySearch((<br>            SearchRequest.query(question)<br>                    .withTopK(3)<br>                    .withFilterExpression( fb.eq(&quot;source&quot;, &quot;article.docx&quot;).build())<br>     ));<br>}</pre><p>Notes:</p><ul><li>The embedding is calculated for the text passed by the user, the one of which we have to find similar documents in our vector store. I repeat here the warning to use the same model for both saving and searching;</li><li>Leave it to the vector database to extract the first <em>k</em> most similar documents, exactly three in the example</li><li>We set a search filter on metadata;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*pMXrWAI0PMgJ0sjMpGqaCw.png" /></figure><p>In the search for embeddings close to the one passed by the user, vector databases generally use two types of algorithms:</p><p>· <strong>L2 squared</strong>: it is nothing more than the square of the (Euclidean) distance between two points (vectors) in the (hyper-)plane, the green line in the graph on the left;</p><p>· <strong>Cosine similarity</strong>: given the two points (vectors), the two semi-straight lines are drawn towards the origin of the axes. The cosine of the angle of these two lines is often the most widely used metric for the distance between vectors;</p><h3>Retrieval augmented generation</h3><p>Each LLM has been trained on millions of datasets, therefore, it knows many topics in the public domain but not all of them and certainly knows nothing about our documents, those internal to companies, procedures, products.</p><p>To enable him to answer these issues as well, one could proceed with training but, since it is an expensive task in terms of resources and time, therefore of money, a shorter way is often used: RAG applications.</p><p>The operation, in general, is easy to understand:</p><ul><li>the user asks for something (e.g. “How can I ask for a refund?”);</li><li>(<strong>Retrieval</strong>) we perform the same search on our vector databases and extract the most relevant documents, for example, three chunks from the pdf relating to the internal refund procedure;</li><li>(<strong>Augmentation</strong>) stuff in the message with the role USER the contents retrieved in the previous point…</li><li>(<strong>Generation</strong>) …so that the LLM can use them to respond to user;</li></ul><p>Here’s a sample chat using this very article to increase the context of the LLM:</p><pre>request:<br>   SYSTEM: You are the assistant of a development team. Your job is to stay <br>           informed about new technologies, Read scientific articles <br>           and answer questions from developers.<br>   USER:  Is there an analogy between legacy db app and LLL app?<br>          <strong>Context information is below.<br>          ---------------------<br>          RAG apps for legacy spring developers<br>          Introduction to RAG apps and Spring AI<br>          With a continuous confrontation his langchain.<br>          A SQL analogy<br>          Our legacy applications interface with those peculiar external <br>          services that are relational dbs using simple text structure <br>          in the SQL language. Interaction with LLMs is also configured <br>          as a call to services intermediated by simple text, <br>          in this case called prompt, structured but in natural <br>          language, ours.<br>          (omissis...)<br>          ---------------------<br>          Given the context and provided history information and not prior knowledge,<br>          reply to the user comment. If the answer is not in the context, inform<br>          the user that you can&#39;t answer the question.</strong><br>          <br>response:<br>   ASSISTANT: The analogy between legacy database applications and large <br>              language model (LLM)-based applications is that both use <br>              structured text to interact with external services. <br>              In the case of legacy applications, structured text is SQL, <br>              while for LLM applications, structured text is a natural <br>              language prompt. <br>              Both types of applications need some sort of abstraction <br>              layer to handle communication with external services. <br>              For legacy applications, this is often handled by a DAO class <br>              and the use of database-specific drivers (such as ODBC or JDBC). <br>              For LLM applications, libraries such as Langchain provide <br>              the abstraction needed to interact with different <br>              language models.<br>              If you have any further questions or need more details on a <br>              specific aspect, please let me know!</pre><p>Note:</p><ul><li>the documents retrieved from the vector database have been added to the USER message and the LLM has been instructed on how to use them (from the phrase <em>Context information is below</em>);</li></ul><p>RAG features are added to ChatClient through the QuestionAnswerAdvisor in Spring AI:</p><pre>@Service public class RAGManager {<br>    ChatClient chatClient;<br>    public RAGManager(@Value(&quot;classpath:/prompts/rag-system.st&quot;) Resource flowersSystem,<br>                      ChatClient.Builder builder, ChatMemory chatMemory, VectorStore vectorStore) {<br>        <br>        chatClient = builder<br>            .defaultSystem(flowersSystem)<br>            .defaultAdvisors(List.of(new MessageChatMemoryAdvisor(chatMemory),<br>                                     new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults()<br>                                                                   .withTopK(3)),<br>                                     new ClearThreadUnsafeLoggerAdvisor()))<br>            .build();<br>    }</pre><p>The call is quite similar to the previous ones:</p><pre>public String ragResponse(String message) {<br>    return chatClient.prompt()<br>            .user(message)<br>            .advisors(a -&gt; a.param(QuestionAnswerAdvisor.FILTER_EXPRESSION, &quot;source == &#39;article.docx&#39;&quot;))<br>            .call()<br>            .content();<br>}</pre><p>Note:</p><ul><li>· Let’s see here a different way to set a filter on database metadata;</li></ul><p>All simple, perhaps too simple; the current implementation of Spring AI is still extremely basic: using the last user prompt for semantic search can be very misleading, as evidenced by the following chat.</p><pre>request:<br>   USER: There is an analogy between legacy database app and LLL app?<br>response:<br>   ASSISTANT: Of course, blah blah blah<br>request:<br>   <strong>USER: tell me more?</strong></pre><p>Searching on the vector store for something like “<em>tell me more</em>” will hardly lead to the desired result. The Chain designed for langchain’s RAG is called ConversationalRetrievalChain and solves the problem by using, within it, two different chains: CondenseQuestionChain takes care of summarizing the conversation and using the summary, including the last prompt, for semantic search; the second, CombineDocsChain uses the output of the first to respond to the user.</p><p>In fact, the whole theme offers ample room for improvement for Spring AI: the <em>k </em>documents retrieved from the database can, of course, be entered directly into the prompt (<em>prompt stuff</em>), or they could be evaluated with a score to include only the best ones (<em>map_rerank</em>), or synthesized, as mentioned, or even refine the search from one document to another (<em>refine</em>). These and other possibilities are offered by langchain only.</p><h3>Conclusions</h3><p>Spring AI seems like a very well-engineered library as, on the other hand, is the tradition of the entire Spring Framework. At present, the foundations have been laid for future developments that we expect to fill the considerable gap in functionality compared to langchain, trusting to be able to write our next RAG application in Java.</p><p>In this regard, I would like to point out the existence of the <strong>langchain4j</strong> library, a project independent from langchain but openly inspired from it: it would certainly be interesting to compare its architecture with that of Spring AI, perhaps in a future article.</p><h3>Bibliography</h3><p><a href="https://docs.spring.io/spring-ai/reference">https://docs.spring.io/<strong>spring-ai</strong>/reference</a> the official documentation of the new Spring AI library</p><p><a href="https://platform.openai.com/playground">https://platform.openai.com/<strong>playground</strong></a> a web console where you can interactively try out prompts, tools, and calls to OpenAI models</p><p><a href="https://python.langchain.com/">https://python.<strong>langchain</strong>.com</a> the official documentation of the world-famous Python langchain library</p><p><a href="https://llamaindex.ai/">https://<strong>llamaindex</strong>.ai</a> a python library to persist documents in various formats and in a multitude of different vector databases</p><p><a href="https://github.com/ggerganov/llama.cpp">https://github.com/ggerganov/<strong>llama.cpp</strong></a> an open-source project to deliver different models, even locally</p><p><a href="https://github.com/vllm-project/vllm">https://github.com/vllm-project/<strong>vllm</strong></a> another project similar to the previous one to provide several LLMs also locally</p><p><a href="https://www.h2database.com/">https://www.<strong>h2databas</strong>e.com</a> an excellent in-memory database</p><p><a href="https://www.postgresql.org/">https://www.<strong>postgresql</strong>.org</a> a formidable database, as long-lived as the elephant that symbolizes it</p><p><a href="https://github.com/pgvector/pgvector">https://github.com/pgvector/<strong>pgvector</strong></a> Postgresql extension to persist and search for embedding vectors</p><p><a href="https://github.com/langchain4j/langchain4j">https://github.com/langchain4j/<strong>langchain4j</strong></a> independent project compared to langchain but with a similar architecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a6744d0b22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG apps per sviluppatori Spring legacy — parte II]]></title>
            <link>https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-parte-ii-03532dc4639f?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/03532dc4639f</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[rag-application]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 07:07:41 GMT</pubDate>
            <atom:updated>2024-09-07T07:07:41.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>RAG apps per sviluppatori Spring legacy — parte II</h3><p>Introduzione alle RAG app e recensione della nuova libreria Spring AI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ucaYJss_nKV6NugW38M5WA.png" /></figure><p>← <a href="https://medium.com/@nicolasanti_43152/b5d5aea66f73"><em>La prima parte di questo articolo</em></a></p><p>La nuova libreria Spring AI sta per essere rilasciata nella versione 1.0, quale occasione migliore per presentare il funzionamento delle applicazioni RAG a noi sviluppatori Java legacy?</p><p>Se usate da una vita Spring ma non sapete nulla di LLM, questa recensione vi illustrerà in modo comprensibile il funzionamento di massima di un’applicazione tipo chatbot, riassunto o classificazione di documenti e interrogazioni su documenti privati.</p><p>In questo campo, la libreria python langchain la fa da padrona, sarà quindi mia premura confrontarla sistematicamente con le scelte implementative di Spring AI.</p><p>Possono, forse, essere apprezzati i prompt italiani, per mostrare un impiego localizzato del famoso ChatGPT.</p><p>Come al solito, il codice sorgente del progetto è disponibile su <a href="https://github.com/nicolinux72/spring-ai-article">github</a> e troverete una lunga bibliografia commentata.</p><p>Articoli collegati:</p><ul><li><a href="https://medium.com/@nicolasanti_43152/local-code-llama-with-gradio-and-hugging-face-1153112046ec?source=your_stories_page-------------------------------------">Local code llama with gradio and hugging face</a></li><li><a href="https://medium.com/@nicolasanti_43152/bootstrap-a-llama-assistant-on-personal-data-16062fa5aa6d?source=your_stories_page-------------------------------------">Bootstrap a LLaMa assistant on personal data</a></li></ul><h3>Embeddings</h3><p>Una frase in linguaggio naturale può essere valutata in base a diverse caratteristiche e a ciascuna assegnare un punteggio compreso tra -1 e 1. Ad esempio, nella frase si parla di Parigi? Ha un sentimento positivo? C’entrano i tramonti? Si parla del colore rosso? Trattiamo di computer? Trattiamo di computer Apple?</p><p>Ad ogni domanda o, più precisamente, ad ogni qualità del testo si assegna un punteggio e la lista di questi punteggi forma un array (o un vettore/<a href="https://medium.com/@nicolasanti_43152/what-are-tensors-58bc4c751f9f">tensore</a> se siete matematici) chiamato embedding, caratterizzato dall’alta dimensionalità, ovvero moltissimi punteggi. ChatGPT, ad esempio, ne usa 1536.</p><p>Vediamo una classe per produrre embedding:</p><pre>@Service public class EmbeddingsManager {<br>    @Autowired EmbeddingModel embeddingModel;<br>    public EmbeddingResponse encode(List&lt;String&gt; texts) {<br>        return embeddingModel.call(<br>                new EmbeddingRequest(texts,<br>                        OpenAiEmbeddingOptions.builder()<br>                                //.withModel(&quot;text-embedding-ada-002&quot;)<br>                                .build()));<br>    }<br>}</pre><p>Note:</p><ul><li>EmbeddingModel è il prototipo della classe per produrre embeding usando diversi modelli, uno per implementazione concreta;</li><li>La riga commentata mostra come selezionare un modello specifico di OpenAI;</li></ul><p>Ecco un client per creare un paio di vettori:</p><pre>EmbeddingResponse encoded = <br>               embeddingsManager.encode(List.of(&quot;Proviamo con qualcosa&quot;));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*bnmIgSG8NJnJ5A-MI7vsig.png" /></figure><p>Nota:</p><ul><li>La sessione di debug mostra l’embedding creato, uno solo (size = 1) con tutte i 1536 float compresi tra -1 e 1 che lo compongono;</li></ul><p>Un embedding ha senso, cioè è comprensibile, solo dal modello che l’ha generato quindi, assicuratevi di usare lo stesso modello sia per la creazione sia l’uso.</p><blockquote>Una precisazione: la semantica racchiusa in un embedding non è ripartita ortogonalmente nelle singole dimensioni, come lascio intendere in questo paragrafo, ma espressa dalla direzione dei vettori, cioè da una precisa combinazione dei componenti. Ad esempio, partendo dal vettore “Re” e aggiungendo la direzione che incapsula il significato di genere, si dovrebbe giungere vicino al vettore “Regina”.</blockquote><h3>Vector Database</h3><p>Se l’embedding rappresenta il contenuto di un testo, quindi la sua semantica, perché non persistere entrambi, testo e vettore, su una tabella? Per farlo, occorre un database vettoriale, chiamati anche vector store, cioè in grado di persistere e ricercare vettori:</p><pre>CREATE TABLE IF NOT EXISTS public.vector_store<br>(<br>    id uuid NOT NULL DEFAULT uuid_generate_v4(),<br>    content text COLLATE pg_catalog.&quot;default&quot;,<br>    metadata json,<br>    embedding vector(1536),<br>    CONSTRAINT vector_store_pkey PRIMARY KEY (id)<br>)</pre><p>La DDL (Data Definition Language) qui sopra si riferisce allo storico Postgresql, mutato in vector store dall’estensione pgvector che lo ha gettato nella mischia dei nuovi database vettoriali, spuntati sul mercato come funghi negli ultimi anni.</p><p>Le colonne sono di facile comprensione:</p><ul><li><strong>Id</strong>: un uuid usato come chiave primaria;</li><li><strong>Text</strong>: il testo in chiaro;</li><li><strong>Metadata</strong>: json con i metadati;</li><li><strong>Embedding</strong>: il nostro vettore calcolato da OpenAI;</li></ul><p>Spring AI, e certamente langchain, consentono di salvare testi, metadati ed embedding in modo molto semplice:</p><pre>List&lt;Document&gt; documents = List.of(<br>        new Document(getText(&quot;classpath:/data/fatti_curiosi.txt&quot;), <br>        Map.of(&quot;meta1&quot;, &quot;meta1&quot;))<br>        );<br> <br>vectorStore.add(documents);</pre><p>Verifichiamo che i dati siano inseriti in tabella:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*-6E413Ps7xk_6cHRKviyAw.png" /></figure><p>I documenti aziendali sono conservati nei più svariati formati (pdf, word, json, ecc.), per leggerli servono quindi delle classi specifiche. Langchain e la libreria python llamaindex consentono di lavorare con decine di tipologie diverse. Anche Spring AI offre funzionalità per i formati più comuni, ad esempio word:</p><pre>List&lt;Document&gt; readWordDoc() {<br>  var wordDoc = new DefaultResourceLoader().getResource(&quot;classpath:/etl/article.docx&quot;);<br>  TikaDocumentReader tikaDocumentReader = new TikaDocumentReader(wordDoc);<br>  TokenTextSplitter splitter = new TokenTextSplitter(500, 400, 10, 1000, true);<br>  return  splitter.apply(tikaDocumentReader.read());<br>}</pre><p>Note:</p><ul><li>Per questo genere di documenti, Spring AI delega la lettura all’ottima libreria Tika dell’Apache Foundation;</li><li>Il codice carica la versione word proprio dell’articolo che state leggendo;</li><li>Le ultime righe si occupano di spezzare l’intero documento in parti più piccole, denominate, a volte, chunk;</li></ul><p>Si tratta, quest’ultima, di un’operazione necessaria perché gli LLM hanno dei limiti invalicabili relativi alla lunghezza dei prompt e tutto il documento potrebbe proprio non starci dentro. Inoltre, più è grande il documento da analizzare, più tempo serve al modello per rispondere. Infine, inserendo nel contesto anche elementi estranei alla richiesta dell’utente, potrebbe confondere LLM e portarlo a rispondere in modo scorretto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*SyDq_oF93fTx0IkgCHdiog.png" /></figure><p>Quindi, suddividiamo il documento in parti più piccole: nell’esempio stiamo impostando le dimensioni (in token e caratteri) di default, minime e massime e riportando il “\n” nei chunk.</p><p>Un approccio a volte migliore consiste nel ripartire per paragrafi, ma molto dipende dal documento trattato per cui, purtroppo, non esiste una regola generale per questa operazione così rilevante per la qualità delle risposte dell’LLM.</p><h3>Retrieval</h3><p>Ora, qualsiasi dato è salvato in un database solo per poterlo ricercare ed estrarre velocemente. La novità offerta dai database vettoriali consiste nel poter effettuare ricerche semantiche, ovvero trovare dei documenti il cui contenuto sia simile ad uno passato. Contenuti simili, significa vettori di embedding vicini.</p><p>I passaggi sono molto semplici:</p><pre>public Collection&lt;Document&gt; retreive(String question) {<br>    var fb = new FilterExpressionBuilder();<br>    return vectorStore.similaritySearch((<br>            SearchRequest.query(question)<br>                    .withTopK(3)<br>                    .withFilterExpression( fb.eq(&quot;source&quot;, &quot;article.docx&quot;).build())<br>  ));<br>}</pre><p>Note:</p><ul><li>Si calcola l’embedding per il testo passato dall’utente (question), quello di cui dobbiamo trovare documenti simili nel nostro vector store. Ripeto qui l’avvertimento di usare lo stesso modello per il salvataggio e la ricerca;</li><li>Lasciate al database vettoriale il compito di estrarre i primi <em>k</em> documenti più simili, tre nell’esempio;</li><li>Impostiamo un filtro di ricerca sui metadati;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*pMXrWAI0PMgJ0sjMpGqaCw.png" /></figure><p>Nella ricerca di embedding vicini a quello passato dall’utente, i database vettoriali utilizzano generalmente due tipi di algoritmi:</p><ul><li><strong>L2 squared</strong>: non è altro che il quadrato della distanza (euclidea) tra due punti (vettori) nel (iper-)piano, la linea verde nel grafico a sinistra;</li><li><strong>Coseno di similitudine</strong>: dati i due punti (vettori), si tracciano le due semirette verso l’origine degli assi. Il coseno dell’angolo di queste due rette è spesso la metrica più usata per la distanza tra vettori;</li></ul><h3>Retrieval augmented generation</h3><p>Ogni LLM è stato addestrato su milioni di dataset, quindi conosce molti argomenti di dominio pubblico ma non tutti e certamente non sa nulla dei nostri documenti, quelli interni alle aziende, le procedure, i prodotti.</p><p>Per metterlo in grado di rispondere anche su questi temi, si potrebbe procedere con l’addestramento ma, trattandosi di un’incombenza costosa in termini di risorse e di tempo, quindi di denaro, spesso si ricorre ad una via più breve: le applicazioni RAG.</p><p>Il funzionamento, in linea generale, è di facile comprensione:</p><ul><li>L’utente chiede qualcosa (e.g. “Come posso chiedere un rimborso?”);</li><li>(<strong>Retrieval</strong>) effettuiamo la stessa ricerca sui nostri database vettoriali ed estraiamo i documenti più rilevanti, ad esempio, tre chunk dal pdf relativo alla procedura interna dei rimborsi;</li><li>(<strong>Augmentation</strong>) inseriamo nel messaggio con ruolo USER i contenuti recuperati al punto precedente…</li><li>(<strong>Generation</strong>) …in modo che l’LLM possa usarli per rispondere all’utente;</li></ul><p>Ecco una chat di esempio utilizzando proprio questo articolo per aumentare il contesto dell’LLM:</p><pre>request:<br>   SYSTEM: Sei l&#39;assistente di un team di sviluppo. Il tuo compito è restare <br>           informato sulle nuove tecnologie, leggere articoli scientifici <br>           e rispondere alle domande degli sviluppatori.<br>           <strong>Context information is below.<br>           ---------------------<br>           RAG apps for legacy spring developers<br>           Introduzione alle RAG app e a Spring AI<br>           Con un confronto continuo su langchain.<br>           Una analogia SQL<br>           Le nostre applicazioni legacy si interfacciano con quei peculiari <br>           servizi esterni che sono di db relazionali utilizzando <br>           del semplice testo struttura nel linguaggio SQL. <br>           Anche l&#39;interazione con gli LLM si configura come una chiamata <br>           a servizi intermediata da semplice testo, in questo caso <br>           chiamato prompt, strutturato ma in linguaggio naturale, il nostro.<br>           (omissis…)<br>           ---------------------<br>           Given the context and provided history information and not prior knowledge,<br>           reply to the user comment. If the answer is not in the context, inform<br>           the user that you can&#39;t answer the question.</strong><br>    <br>   USER: C&#39;è un&#39;analogia tra legacy db app e LLL app?<br><br>response:<br>   ASSISTANT: L&#39;analogia tra le applicazioni legacy per database e <br>              le applicazioni basate su modelli linguistici di grandi <br>              dimensioni (LLM) è che entrambe utilizzano del testo <br>              strutturato per interagire con servizi esterni. Nel caso <br>              delle applicazioni legacy, il testo strutturato è SQL, <br>              mentre per le applicazioni LLM, il testo strutturato <br>              è un prompt in linguaggio naturale. <br>              <br>              Entrambi i tipi di applicazioni necessitano di una sorta di <br>              livello di astrazione per gestire la comunicazione <br>              con i servizi esterni. Per le applicazioni legacy, <br>              questo è spesso gestito da una classe DAO e l&#39;uso <br>              di driver specifici per il database (come ODBC o JDBC). <br>              Per le applicazioni LLM, librerie come Langchain forniscono <br>              l&#39;astrazione necessaria per interagire con diversi <br>              modelli linguistici.<br>              <br>              Se hai ulteriori domande o hai bisogno di più dettagli <br>              su un aspetto specifico, fammelo sapere!</pre><p>Note:</p><ul><li>allo USER message sono stati aggiunti i documenti recuperati dal database vettoriale e istruito l’LLM su come usarli (dalla frase <em>Context information is below</em>);</li><li>La parte di template usata dal RAG è in inglese: ChatGPT comprende le istruzioni e non confonde le due lingue rispondendo in italiano, quella dell’utente. Spring Ai consente, in ogni caso, di sostituire agilmvente il template nel costruttore della classe QuestionAnswerAdvisor;</li></ul><p>Le funzionalità di RAG si aggiungono a ChatClient tramite l’advisor QuestionAnswerAdvisor presente nella libreria Spring AI:</p><pre>@Service public class RAGManager {<br>    ChatClient chatClient;<br>    public RAGManager(@Value(&quot;classpath:/prompts/rag-system.st&quot;) Resource flowersSystem,<br>                      ChatClient.Builder builder, ChatMemory chatMemory, VectorStore vectorStore) {<br>        <br>        chatClient = builder<br>            .defaultSystem(flowersSystem)<br>            .defaultAdvisors(List.of(new MessageChatMemoryAdvisor(chatMemory),<br>                                     new QuestionAnswerAdvisor(vectorStore, SearchRequest.defaults()<br>                                                                   .withTopK(3)),<br>                                     new ClearThreadUnsafeLoggerAdvisor()))<br>            .build();<br>    }</pre><p>La chiamata è molto simile alle precedenti:</p><pre>public String ragResponse(String message) {<br>    return chatClient.prompt()<br>            .user(message)<br>            .advisors(a -&gt; a.param(QuestionAnswerAdvisor.FILTER_EXPRESSION, &quot;source == &#39;article.docx&#39;&quot;))<br>            .call()<br>            .content();<br>}</pre><p>Note:</p><ul><li>Vediamo qui un modo diverso per impostare un filtro sui metadati del database;</li></ul><p>Tutto semplice, forse troppo: l’implementazione attuale di Spring AI è ancora molto elementare, utilizzare l’ultimo prompt dell’utente per la ricerca semantica può essere molto forviante, come testimonia la seguente chat:</p><pre>request:<br>   USER: C&#39;è un’analogia tra legacy db app e LLL app<br>response:<br>   ASSISTENT: Eccome, bla bla bla<br>request:<br>   <strong>USER: dimmi di più?</strong></pre><p>Ricercare sul vector store qualcosa di simile a “dimmi di più” difficilmente condurrà al risultato sperato. La Chain progettata per il RAG di langchain si chiama ConversationalRetrievalChain e risolve il problema utilizzando, al suo interno, due diverse catene: CondenseQuestionChain si occupa di riassumere la conversazione e utilizzare il riassunto, compreso l’ultimo prompt, per la ricerca semantica; la seconda, CombineDocsChain utilizza l’output della prima per rispondere all’utente.</p><p>In vero, tutto il tema offre ampi margini di miglioramento per Spring AI: i <em>k</em> documenti recuperati dal database possono, certamente, essere inseriti direttamente nel prompt (prompt stuff), oppure potrebbero essere valutati con un punteggio per inserire solo i migliori (map_rerank), oppure sintetizzati, come si diceva, oppure ancora raffinare la ricerca da un documento all’altro (refine). Queste e altre possibilità sono offerte da langchain.</p><h3>Conclusioni</h3><p>Spring AI sembra una libreria molto ben ingegnerizzata come, d’altronde, è tradizione di tutto lo Spring Framework. Allo stato attuale, sono state poste le basi per gli sviluppi futuri che ci aspettiamo colmino il notevole gap di funzionalità rispetto a langchain, confidando di potere scrivere la nostra prossima RAG application in Java.</p><p>A tal riguardo, segnalo l’esistenza della libreria <strong>langchain4j</strong>, progetto indipendente da langchain a cui però si ispira apertamente: sarebbe certamente interessante confrontarne l’architettura con quella di Spring AI, magari in un prossimo articolo.</p><h3>Bibliografia</h3><p><a href="https://docs.spring.io/spring-ai/reference">https://docs.spring.io/<strong>spring-ai</strong>/reference</a> la documentazione ufficiale della nuova libreria Spring AI</p><p><a href="https://platform.openai.com/playground">https://platform.openai.com/<strong>playground</strong></a> una web console dove provare interattivamente prompt, tool e chiamate ai modelli di OpenAI</p><p><a href="https://python.langchain.com/">https://python.<strong>langchain</strong>.com</a> la documentazione ufficiale della famosissima libreria python langchain</p><p><a href="https://llamaindex.ai/">https://<strong>llamaindex</strong>.ai</a> una libreria python per persistere documenti in vari formati e in una moltitudine di database vettoriali diversi</p><p><a href="https://github.com/ggerganov/llama.cpp">https://github.com/ggerganov/<strong>llama.cpp</strong></a> un progetto open-source per erogare diversi modelli, anche localmente</p><p><a href="https://github.com/vllm-project/vllm">https://github.com/vllm-project/<strong>vllm</strong></a><strong> </strong>un altro progetto analogo al precedente per erogare diversi LLM anche localmente</p><p><a href="https://www.h2database.com/">https://www.<strong>h2database</strong>.com</a> un ottimo database in memoria</p><p><a href="https://www.postgresql.org/">https://www.<strong>postgresql</strong>.org</a> un database formidabile, longevo come l’elefante che lo simboleggia</p><p><a href="https://github.com/pgvector/pgvector">https://github.com/<strong>pgvector</strong>/pgvector</a> estensione di postgresql per persistere e ricercare vettori di embedding</p><p><a href="https://github.com/langchain4j/langchain4j">https://github.com/<strong>langchain4j</strong>/langchain4j</a> progetto indipendente rispetto a langchain ma dalla architettura simile</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03532dc4639f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG apps per sviluppatori Spring legacy]]></title>
            <link>https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-b5d5aea66f73?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5d5aea66f73</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rag-application]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 07:06:00 GMT</pubDate>
            <atom:updated>2024-09-07T07:06:00.613Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduzione alle RAG app e recensione della nuova libreria Spring AI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ucaYJss_nKV6NugW38M5WA.png" /></figure><p>La nuova libreria Spring AI sta per essere rilasciata nella versione 1.0, quale occasione migliore per presentare il funzionamento delle applicazioni RAG a noi sviluppatori Java legacy?</p><p>Se usate da una vita Spring ma non sapete nulla di LLM, questa recensione vi illustrerà in modo comprensibile il funzionamento di massima di un’applicazione tipo chatbot, riassunto o classificazione di documenti e interrogazioni su documenti privati.</p><p>In questo campo, la libreria python langchain la fa da padrona, sarà quindi mia premura confrontarla sistematicamente con le scelte implementative di Spring AI.</p><p>Possono, forse, essere apprezzati i prompt italiani, per mostrare un impiego localizzato del famoso ChatGPT.</p><p>Come al solito, il codice sorgente del progetto è disponibile su <a href="https://github.com/nicolinux72/spring-ai-article">github</a> e troverete una lunga bibliografia commentata.</p><p>Articoli collegati:</p><ul><li><a href="https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-parte-ii-03532dc4639f">Seconda parte di questo articolo</a></li><li><a href="https://medium.com/@nicolasanti_43152/local-code-llama-with-gradio-and-hugging-face-1153112046ec?source=your_stories_page-------------------------------------">Local code llama with gradio and hugging face</a></li><li><a href="https://medium.com/@nicolasanti_43152/bootstrap-a-llama-assistant-on-personal-data-16062fa5aa6d?source=your_stories_page-------------------------------------">Bootstrap a LLaMa assistant on personal data</a></li></ul><h3>Una analogia SQL</h3><p>Le nostre applicazioni legacy si interfacciano con quei peculiari servizi esterni che sono i database relazionali utilizzando del semplice testo strutturato in linguaggio SQL. Anche l’interazione con gli LLM si configura come una chiamata a servizi intermediata da semplice testo, in questo caso chiamato <strong>prompt</strong>, strutturato in linguaggio naturale.</p><p>In assenza di una libreria di Object to Relation Mapping (ORM) quale JPA o Hibernate, la soluzione più comune per accedere ad un DB consiste nel delegare ad una classe la composizione dell’SQL partendo da alcuni template di stringa. Classe e template sono collocati nel livello detto di persistenza (noto anche come DAO) che hanno il compito di astrarre i dettagli di connessione e comunicazione con un database specifico al resto dell’applicazione.</p><pre>select {fields_list} from {tables_list} where 1=1 {where_clauses}</pre><p>L’astrazione è resa possibile ricorrendo anche ai cosiddetti driver (odbc, jdbc): codice sviluppato direttamente dal produrre del database (es. postgress, oracle, mysql).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*HNozSB2tHQEDiNvBZ22eYw.png" /></figure><p>Vale lo stesso per un’applicazione di linguaggio che, utilizzando dei template di testo, deve produrre dei prompt comprensibili per uno specifico LLM ed occuparsi della connessione e comunicazione con questi, astraendo i dettagli al resto dell’applicazione.</p><pre>Sei un PM di una software house. Scrivi un riassunto di {max_words} <br>parole massimo basandosi sul seguente project charter: {synopsis}</pre><p>Anche qui, la comunicazione è resa possibile dall’impiego di codice sviluppato dal produttore del modello di AI (llama, openai). Su queste, si collocano ulteriori livelli di software per fruire in modo uniforme ai diversi LLM, astrazioni fornite da librerie come langchain.</p><h3>Completion</h3><p>L’utilizzo di un LLM, dunque, nella sua forma più semplice, si concretizza in una chiamata ad un servizio web e, tra i livelli applicativi, si colloca alla stessa altezza dei repository (aka DAO). Prego, notare che il livello di competenza non cambierebbe qualora il database fosse locale, ad esempio <em>H2DB</em>, o l’LLM venisse erogato localmente, ad esempio tramite <em>vllm</em> o <em>llama.cpp</em>.</p><p>Nella libreria <em>langchain</em> la famiglia di classi che si occupano di interfacciarsi con un LLM si chiamano Chain, perché pensate per essere collegate in cascata l’una all’altra. Richiedono, nella forma più elementare, due elementi: un modello LLM e dei template per il prompt. Nella libreria Spring AI, la classe equivalente si chiama ChatClient e richiede gli stessi elementi: un modello derivato da ChatModel e dei template derivanti da PromptTemplate.</p><p>Le chiamate all’LLM, si pensi ad una chat, devono contenere almeno due tipi di messaggi, ciascuno relativo ad un partecipante o, come di dice, ad un <strong>ruolo</strong>:</p><p>· <strong>USER</strong>: sono i messaggi inseriti dall’essere umano che interagisce con l’AI;<br>· <strong>ASSISTENT</strong>: è la risposta dell’AI;</p><p>A questi se ne aggiungono due, forse meno intuitivi che sono <strong>SYSTEM</strong> e <strong>TOOL</strong>, di quest’ultimo parleremo più avanti. I messaggi con ruolo SYSTEM forniscono indicazioni generali al modello. Ad esempio:</p><pre>Sei un assistente educato e volenteroso di una software house. <br>Il tuo compito è rispondere cortesemente alle richieste dei clienti, <br>cercando di renderti utile, comprendere a fondo il problema del cliente <br>e raccogliere tutte le informazioni necessarie <br>per aprire l&#39;eventuale ticket.<br><br>Le informazioni necessarie sono:<br> * il codice cliente<br> <strong>{more_infos}</strong></pre><p>Note:</p><ul><li>Qui sopra vediamo un altro esempio di prompt template che prevede un unico valore <em>more_infos</em> da valorizzare al momento della chiamata;</li></ul><p>La nostra classe, nel livello di servizio, è responsabile dei template per produrre i prompt per i diversi ruoli. Vediamone un esempio:</p><pre>@Service<br>public class CompletionManager {<br><br>   ChatClient chatClient;<br><br>    public CompletionManager(@Value(&quot;classpath:/prompts/flowers-system.st&quot;) Resource flowersSystem,<br>                             ChatClient.Builder builder) {<br><br>        chatClient =  builder<br>                .defaultSystem(flowersSystem)<br>                .build();<br>    }  <br>    …<br>}</pre><p>Note:</p><ul><li>Il template del messaggio con ruolo SYSTEM è letto da un file esterno presente nel classpath perché più comodo da fruire e modificare da sviluppatori, prompt engineering, ecc.;</li><li>La classe è marcata con lo stereotipo <em>service</em>, si colloca allo stello livello applicativo dei repository, come dicevamo;</li><li>ChatClient svolge una funzione simile ai driver JDBC ed è istanziata e conservata nella nostra classe;</li></ul><p>Vediamo un altro semplice template, in questo caso senza variabili:</p><pre>Sei un agente utile e gentile, ti intendi di fiori e della produzione <br>mondale delle varie nazioni.<br>Rispondi con un semplice elenco di nazioni, senza ulteriori commenti.</pre><p>Il metodo per chiamare effettivamente il modello:</p><pre>  public String chatResponse(String message) {<br>        return chatClient.prompt()<br>                //.advisors(new SimpleLoggerAdvisor())<br>                .advisors(new ClearThreadUnsafeLoggerAdvisor())<br>                .user(message)<br>                .call()<br>                .content();<br>    }</pre><p>Note:</p><ul><li>La richiesta dell’utente è veicolata tramite la stringa message;</li><li>Stiamo usando un Advisor realizzato da me per trascrivere in forma più chiara la comunicazione con l’LLM. È una classe profondamente insicura, con il solo pregio di loggare la chat in modo più confortevole per i lettori di questo articolo. In produzione usate invece SimpleLoggerAdvisor, fornita da Spring AI;</li></ul><p>Infine, ecco un esempio di client della nostra classe:</p><pre>completionManager.chatResponse(&quot;Quali sono le prime tre nazioni esportatrici di tulipani?&quot;);</pre><p>E relativa risposta:</p><pre>request:<br>   SYSTEM: Sei un agente utile e gentile, ti intendi di fiori e della <br>           produzione mondale delle varie nazioni.<br>           Rispondi con un semplice elenco di nazioni, <br>           senza ulteriori commenti.<br>   USER:   Quali sono le prime tre nazioni esportatrici di tulipani?<br><br>response:<br>   ASSISTANT: 1. Paesi Bassi<br>              2. Polonia<br>              3. Germania</pre><p>Le risposte dell’AI, evidentemente, non sono prodotte dalle nostre applicazioni quindi niente template per loro: è però possibile istruire il modello affinché ci risponda in un formato particolare, ad esempio in JSON. Fino a poco tempo fa, non era cosa semplice convincere un LLM a restituire solo del JSON perché spesso lo anticipava con un commento entusiastico tipo: <em>“certo che posso rispondere con un JSON eccolo di seguito:”</em>.</p><p>Ora è possibile forzare il formato di risposta fuori dal prompt, direttamente nella chiamata a servizio:</p><pre>public Works entity(String message) {<br><br>  var outputConverter = new BeanOutputConverter&lt;&gt;(CompletionManager.Works.class);<br><br>  ChatResponse response =chatClient.prompt()<br>          .advisors(new ClearThreadUnsafeLoggerAdvisor())<br>          .system(&quot;Sei un fine letterato, amante della poesia polacca e desideroso di rendela noto in tutto il mondo.&quot;)<br>          .options(OpenAiChatOptions.builder()<br>                  .withModel(OpenAiApi.ChatModel.GPT_4_O_MINI)<br>                  .withResponseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, outputConverter.getJsonSchema()))<br>                  .build())<br>          .user(message)<br>          .call()<br>          .chatResponse();<br><br>  String content = response.getResult().getOutput().getContent();<br><br>  return outputConverter.convert(content);<br><br>}</pre><p>Note:</p><ul><li>Tramite la classe OpenAIChatOptions, stiamo passando delle opzioni specifiche del modello usato. Oltre a indicare il formato di risposta, esistono molte altre opzioni, come la temperatura della risposta;</li><li>Abbiamo usato un diverso modello di OpenAI, il buon <em>gpt-4o-mini</em>;</li><li>Abbiamo sostituito il messaggio di default di SYSTEM, solo per mostrare come sia possibile;</li><li>Nella variabile <em>content</em>, la stringa JSON restituita dal modello;</li></ul><p>Ora, la nostra classe ha il compito di restituire le risposta dell’LLM in un formato indipendente dal modello per renderlo fruibile dagli altri livelli applicativi. Nell’esempio, se la richiesta fosse avere una lista delle poesie più belle della poetessa polacca Wisława Szymborska, dovremo definite un DTO apposito e restituirne un’istanza.</p><pre>record Works(@JsonProperty(required = true, value = &quot;works&quot;) Work[] works,<br>             @JsonProperty(required = true, value = &quot;poet_name&quot;) String poet) {<br><br>        record Work(@JsonProperty(required = true, value = &quot;title&quot;) String title,<br>                    @JsonProperty(required = true, value = &quot;year&quot;) Integer year) {<br>        }<br>}}</pre><h3>Memoria</h3><p>Dopo innumerevoli conversazioni con ChatGPT o Gemini o LLama può, forse, stupire scoprire che gli LLM sono servizi stateless: ogni chiamata è indipendente dalle altre e non esiste alcuna sessione. Verifichiamolo:</p><pre> completionManager.chatResponse(&quot;Quali sono le prime tre nazioni esportatrici di tulipani?&quot;);<br> completionManager.chatResponse(&quot;E la quarta?&quot;);</pre><p>La risposta sarà simile a:</p><pre>request:<br>   SYSTEM: Sei un agente utile e gentile, ti intendi di fiori…<br>   USER: Quali sono le prime tre nazioni esportatrici di tulipani?<br>response:<br>   ASSISTANT: 1. Paesi Bassi<br>              2. Stati Uniti<br>              3. Giappone<br>request:<br>   SYSTEM: Sei un agente utile e gentile, ti intendi di fiori…<br>   USER: E la quarta?<br>response:<br>   ASSISTANT: <strong>Mi dispiace, ma non sono sicuro di cosa tu stia chiedendo. <br>              Puoi fornirmi più contesto o chiarire la tua domanda?</strong></pre><p>Per poter sostenere una conversazione, è necessario riportare nel prompt più recente la conversazione avvenuta fino a quel momento.</p><p>Questa iniezione nel prompt (sia esso SYSTEM o USER) è indicata spesso come <em>stuff prompting </em>ed è compito della nostra applicazione occuparsene, ricorrendo alle apposite classi delle diverse librerie che generalmente prendono il nome di Memory.</p><p>Spring AI presenta un paio di classi molto basilari per la gestione della memoria, per usarle bisogna aggiungere l’apposito advisor all’istanza di ChatClient:</p><pre>@Bean ChatMemory chatMemory() {<br>      return new InMemoryChatMemory();<br>}<br><br>...<br><br>chatClient =  builder<br>      .defaultSystem(flowersSystem)<br>      .defaultAdvisors(List.of(new MessageChatMemoryAdvisor(chatMemory) ))<br>      .build();</pre><p>Dopo questa modifica, verifichiamo la risposta la nuova conversazione generata:</p><pre>request:<br>   SYSTEM: Sei un agente utile e gentile, ti intendi di fiori…<br>   USER: Quali sono le prime tre nazioni esportatrici di tulipani?<br>response:<br>   ASSISTANT: - Paesi Bassi<br>              - Germania<br>              - Francia<br>request:<br>   SYSTEM: Sei un agente utile e gentile, ti intendi di fiori…<br>   <strong>USER: Quali sono le prime tre nazioni esportatrici di tulipani?</strong><br>   <strong>ASSISTANT: - Paesi Bassi<br>              - Germania<br>              - Francia</strong><br>   USER: E la quarta?<br>response:<br>   ASSISTANT: Italia</pre><p>Nota:</p><ul><li>nella seconda richiesta è stata inserita (stuffata) anche la conversazione precedente;</li></ul><p>La capacità di persistere una conversazione su file o database è delegata a classi chiamate da langchain History: tale libreria offre molteplici opzioni di persistenza mentre Spring AI, al momento, solo una tramite la classe CassandraChatMemory (indovinate su quale database salva? 😊)</p><p>Aggiungere al contesto tutta la conversazione trova il suo ostacolo più grande nella limitatezza del prompt: ogni LLM accetta solo un certo numero di caratteri (token, più precisamente) e non uno di più. Anche i costi sarebbero un problema da prendere in considerazione perché le tariffa si basano sui token, che sono frazioni delle parole inserite nei prompt. Per questi motivi, langchain presenta delle classi, ad esempio ConversationSummaryMemory, che riassumo la conversazione precedente, in modo da iniettare nel prompt solo questo estratto. Ovviamente, a prezzo di maggiori interazioni con il modello.</p><h3>Funzioni</h3><p>Nello svolgere il proprio compito, un LLM può ricorrere a delle funzioni esterne. Attenzione, non è in grado di invocarle, può semplicemente chiedere alla nostra applicazione di farlo.</p><pre>{<br>  &quot;$schema&quot;: &quot;https://json-schema.org/draft/2020-12/schema&quot;,<br>  &quot;name&quot;: &quot;orderStatusService&quot;,<br>  &quot;description&quot;: &quot;Restituisce lo stato dell&#39;ordine&quot;,<br>  &quot;parameters&quot;: {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>      &quot;order_code&quot;: {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;description&quot;: &quot;Il codice dell&#39;ordine, e.g. XX-427&quot;<br>      }<br>    },<br>    &quot;required&quot;: [&quot;order_code&quot;]<br>  }<br>}</pre><p>Bisogna passare al modello il json schema delle funzioni a cui può attingere, l’esempio qui sopra si riferisce ad una funzione per ottenere lo stato di un ordine; l’unico parametro è il codice identificativo dell’ordine. LLM utilizza solo le descrizioni, i nomi di funzione e parametri per capire come usarli, che devono quindi essere molto chiari ed esaustivi.</p><p>Il json schema viene prodotto partendo dal nostro codice sorgente, mediante annotazioni.</p><pre>@Service<br>public class OrderStatusService implements Function&lt;OrderStatusService.Request, OrderStatusService.Response&gt; {<br><br>    @JsonClassDescription(&quot;Restituisce lo stato dell&#39;ordine&quot;)<br>    public record Request(@JsonProperty(required = true, value = &quot;order_code&quot;)<br>                              @JsonPropertyDescription(&quot;Il codice dell&#39;ordine, e.g. XX-427&quot;) String orderCode) {<br>    }<br><br>    public record Response(Status status) {<br>    }<br><br>    public enum Status {<br>        RICEIVED, SEND, REFIUSED, DELIVERED;<br><br>        public static Status getRandom() {<br>            Status[] stati = values();<br>            return stati[new Random().nextInt(stati.length)];<br>        }<br>    }<br><br>    public Response apply(Request request) {<br>        return new Response(Status.getRandom());<br>    }<br>}</pre><p>Note:</p><ul><li>Esistono molti modi per configurare le funzioni da passare all’LLM, qui presento un modo alternativo rispetto alla documentazione ufficiale, definendo una componente di Spring in cui è possibile iniettare altri bean del contesto;</li><li>Le descrizioni passate all’LLM sono mutuate del componente e dalle annotazioni json, ricordate di aggiungerle e di descriverle con semplicità e chiarezza;</li><li>Java non è un linguaggio funzionale, nonostante l’introduzione di lambda e interfacce funzionali nel lontano Java 8. Per passare una funzione all’LLM serve un po’ più di codice rispetto a linguaggi dinamici. Il nostro componente, di conseguenza, implementa l’interfaccia funzionale di default del JDK, dove l’invocazione avviene attraverso il metodo apply;</li><li>In questo esempio, lo stato dell’ordine è restituito in modo casuale tra i valori dell’enumeratore Status;</li></ul><p>Il funzionale deve essere poi passato all’istanza di ChatModel, lo facciamo in un altro componente, come negli esempi precedenti:</p><pre>@Service<br>public class AgentManager {<br><br>    ChatClient chatClient;<br><br>    public AgentManager(@Value(&quot;classpath:/prompts/tool-system.st&quot;) Resource toolSystem,<br>                        ChatClient.Builder builder) {<br><br><br>        chatClient =  builder<br>                .defaultSystem(toolSystem)<br>                .defaultAdvisors(new ClearThreadUnsafeLoggerAdvisor())<br>                .defaultOptions(OpenAiChatOptions.builder()<br>                        .withFunction(&quot;orderStatusService&quot;)<br>                        .build())<br>                .build();<br>    }<br><br>    public String tools(String message) {<br>        return chatClient.prompt()<br>                .user(message)<br>                .call()<br>                .content();<br>    }<br><br>}</pre><p>Nota:</p><ul><li>Troviamo l’unica novità è tra le opzioni del modello, dove passiamo il riferimento al bean chiamato orderStatusService;</li></ul><p>Nel dialogo tra l’applicazione e il modello interviene il ruolo TOOL, la quarta e ultima tipologia di messaggio.</p><pre>request:<br>   SYSTEM: Sei l&#39;assistente virtuale di una libreria online. Rispondi <br>           agli utenti con estrema gentilezza, ricorda loro di specificare <br>           sempre il codice dell&#39;ordine, saluta ricordando il nome <br>           dell&#39;azienda: &quot;Scripta Manent&quot;<br>   USER: In quale stato è l&#39;ordine con codice AB-621?<br><br>response:<br>   ASSISTANT: Sarò felice di aiutarti! Un momento, per favore, mentre verifico <br>              lo stato dell&#39;ordine con codice AB-621.  <br>              orderStatusService({&quot;order_code&quot;:&quot;AB-621&quot;})<br><br><strong>--&gt; la nostra applicazione richiama la funzione e li restituisce all&#39;LLM &lt;--</strong><br>request:<br>   <strong>TOOL: ToolResponse[id=call_527S70lYLcYLAgeKe4GmWjcc, <br>          name=orderStatusService, responseData={&quot;status&quot;:&quot;RICEIVED&quot;}]</strong><br><br>response:<br>   ASSISTANT: Il tuo ordine con codice AB-621 è attualmente in fase <br>              di spedizione. Grazie per averci contattato e <br>              buona giornata da Scripta Manent!</pre><p>L’assistente richiede all’applicazione di invocare una specifica funzione di cui ci passa i parametri {“order_code”:”AB-621&quot;}. Spring si comporta da agente ed effettua per noi la chiamata, passando i valori ottenuti all’LLM {“status”:”RICEIVED”} con la successiva chiamata, usando un messaggio di tipo TOOL.</p><p>Nota:</p><ul><li>La mia classe di log non riesce a riportare i messaggi dell’agente perché avvengono dentro la classe <em>OpenAIChatModel</em>, prima che ogni advisor sia invocato. È possibile comunque recuperarli debuggando il metodo <em>OpenAIChatModel.doGetChatResponse</em> , oppure alzare il livello di logging del client http, dall’<em>application.yaml</em>:</li></ul><pre>logging:<br>  level:<br>    org.springframework.web.client: DEBUG</pre><p>Il modello può richiedere l’invocazione successiva di diverse funzioni prima di rispondere al prompt dell’utente.</p><p>Nella nomenclatura di langchain, una Chain in grado di invocare funzioni si chiama Agent mentre un AgentExecutor esegue uno (o più) Agent fino a quando l’LLM richiede di invocare nuove funzioni. Sostanzialmente, gestisce la parte di conversazione che richiede l’esecuzione di funzioni. In Spring AI, come si è visto, l’unica classe ChatModel a comportarsi da agente nel caso in cui siano specificate delle funzioni.</p><h3>Fine della prima parte</h3><p>Nella <a href="https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-parte-ii-03532dc4639f">prossima e ultima parte di questo articolo</a> parleremo di embeddings, vector store, document retrieval e RAG application.</p><p>Grazie per la lettura.</p><h3>Bibliografia</h3><p><a href="https://docs.spring.io/spring-ai/reference">https://docs.spring.io/<strong>spring-ai</strong>/reference</a> la documentazione ufficiale della nuova libreria Spring AI</p><p><a href="https://platform.openai.com/playground">https://platform.openai.com/<strong>playground</strong></a> una web console dove provare interattivamente prompt, tool e chiamate ai modelli di OpenAI</p><p><a href="https://python.langchain.com/">https://python.<strong>langchain</strong>.com</a> la documentazione ufficiale della famosissima libreria python langchain</p><p><a href="https://llamaindex.ai/">https://<strong>llamaindex</strong>.ai</a> una libreria python per persistere documenti in vari formati e in una moltitudine di database vettoriali diversi</p><p><a href="https://github.com/ggerganov/llama.cpp">https://github.com/ggerganov/<strong>llama.cpp</strong></a> un progetto open-source per erogare diversi modelli, anche localmente</p><p><a href="https://github.com/vllm-project/vllm">https://github.com/vllm-project/<strong>vllm</strong></a><strong> </strong>un altro progetto analogo al precedente per erogare diversi LLM anche localmente</p><p><a href="https://www.h2database.com/">https://www.<strong>h2database</strong>.com</a> un ottimo database in memoria</p><p><a href="https://www.postgresql.org/">https://www.<strong>postgresql</strong>.org</a> un database formidabile, longevo come l’elefante che lo simboleggia</p><p><a href="https://github.com/pgvector/pgvector">https://github.com/<strong>pgvector</strong>/pgvector</a> estensione di postgresql per persistere e ricercare vettori di embedding</p><p><a href="https://github.com/langchain4j/langchain4j">https://github.com/<strong>langchain4j</strong>/langchain4j</a> progetto indipendente rispetto a langchain ma dalla architettura simile</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5d5aea66f73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG apps for legacy spring developers]]></title>
            <link>https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-be6e2f75516e?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/be6e2f75516e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rag-application]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-ai]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 07:05:33 GMT</pubDate>
            <atom:updated>2024-09-07T07:05:33.396Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction to RAG apps and review of the new Spring AI library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*ucaYJss_nKV6NugW38M5WA.png" /></figure><p>The new Spring AI library is about to be released in version 1.0, what better opportunity to present the operating of RAG applications to us, legacy Java developers?</p><p>If you’ve been using Spring for a lifetime but don’t know anything about LLM, this review will give you a comprehensible explanation of how a chatbot, summarizing or classifying documents, and querying private documents applications works.</p><p>In this field, the langchain python library is the master, so it will be my concern to systematically compare it with the implementation choices of Spring AI.</p><p>Italian prompts can, perhaps, be appreciated, to show a localized use of the famous ChatGPT.</p><p>As usual, the source code of the project is available on <a href="https://github.com/nicolinux72/spring-ai-article">github</a> and you will find a long-annotated bibliography.</p><p>Related Articles:</p><ul><li><a href="https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-part-2-e4a6744d0b22">Second part of this article</a></li><li><a href="https://medium.com/@nicolasanti_43152/rag-apps-per-sviluppatori-spring-legacy-b5d5aea66f73">Italian version of this articles</a></li><li><a href="https://medium.com/@nicolasanti_43152/local-code-llama-with-gradio-and-hugging-face-1153112046ec?source=your_stories_page-------------------------------------">Local code llama with gradio and hugging face</a></li><li><a href="https://medium.com/@nicolasanti_43152/bootstrap-a-llama-assistant-on-personal-data-16062fa5aa6d?source=your_stories_page-------------------------------------">Bootstrap a LLaMa assistant on personal data</a></li></ul><h3>A SQL analogy</h3><p>Our legacy applications interface with those peculiar external services that are relational databases using simple structured text in SQL language. Interaction with LLMs is also configured as a call to services intermediated by plain text, in this case called <strong>prompt</strong>, structured in natural language.</p><p>In the absence of an Object to Relation Mapping (ORM) library such as JPA or Hibernate, the most common solution to access a database is to delegate the composition of SQL to a class using some string templates. Class and templates are placed in the layer called persistence (aka DAO) which has the task of abstracting the details of connection and communication with a specific database to the rest of the application.</p><pre>select {fields_list} from {tables_list} where 1=1 {where_clauses}</pre><p>Abstraction is also made possible using the so-called drivers (odbc, jdbc), developed directly from the database producer (e.g. postgress, oracle, mysql).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*HNozSB2tHQEDiNvBZ22eYw.png" /></figure><p>The same is true for a language application that, using text templates, must produce understandable prompts for a specific LLM and take care of the connection and communication with them, abstracting the details from the rest of the application.</p><pre>You are a PM of a software house. Write a summary of {max_words} <br>words maximum based on the following project charter: {synopsis}</pre><p>Here too, communication is made possible using code developed by the manufacturer of the AI model (llama, openai). Over these, there are further layers of software to access different LLMs in the same way, abstractions provided by libraries such as langchain.</p><h3>Completion</h3><p>The use of an LLM, therefore, in its simplest form, takes the form of a call to a web service and, among the application layers, is placed at the same height as the repositories (aka DAO). Please, note that the layer would not change if the database was running locally, e.g. <em>H2DB</em>, or the LLM was delivered locally, e.g. via <em>vllm</em> or <em>llama.cpp</em>.</p><p>In the <em>langchain</em> library, the family of classes that interfacing with an LLM are called Chain, because they are designed to be linked to each other. They require, in the most basic form, two elements: an LLM model and templates for the prompt. In the Spring AI library, the equivalent class is called ChatClient and requires the same elements: a model derived from ChatModel and templates derived from PromptTemplate.</p><p>Calls to the LLM, think of a chat, must contain at least two types of messages, each relating to a participant or, as it says, to a <strong>role</strong>:</p><p>· <strong>USER: </strong>these are the messages entered by the human being interacting with the AI;</p><p>· <strong>ASSISTANT:</strong> is the AI’s answer;</p><p>To these are added two, less intuitive ones which are <strong>SYSTEM</strong> and <strong>TOOL,</strong> the latter we will talk about later. Messages with the SYSTEM role provide general guidance to the model. For example:</p><pre>You are a polite and willing assistant to a software house. <br>Your job is to respond politely to customer requests, <br>trying to make yourself useful, fully understand the customer&#39;s problem <br>and collect all the information necessary to open the eventual ticket.<br><br>The information required is:<br>* the customer number<br><strong>{more_infos}</strong></pre><p>Notes:</p><ul><li>Above we see another example of a prompt template that provides a single <em>more_infos</em> value to be valued at call time;</li></ul><p>Our class, in the service layer, is responsible for the templates used to produce the prompts for separate roles. Let’s look at an example:</p><pre>@Service<br>public class CompletionManager {<br>    ChatClient chatClient;<br>    public CompletionManager(@Value(&quot;classpath:/prompts/flowers-system.st&quot;) Resource flowersSystem,<br>                             ChatClient.Builder builder) {<br>        chatClient =  builder<br>                .defaultSystem(flowersSystem)<br>                .build();<br>    }  <br>    …<br>}</pre><p>Notes:</p><ul><li>The message template for the SYSTEM role is read from an external file located in the classpath because it is more convenient to access and modify by developers, prompt engineering, etc.;</li><li>The class is marked with the <em>service</em> stereotype, it is placed at the same application layer as the repositories, as we said;</li><li>ChatClient plays a similar role to JDBC drivers and is instantiated and stored in our class;</li></ul><p>Let’s see another simple template, in this case without variables:</p><pre>You are a helpful and kind agent, you know about flowers and the world <br>production of various nations. Respond with a simple list of countries, <br>without further comment.</pre><p>Here the method to call the model:</p><pre>public String chatResponse(String message) {<br>        return chatClient.prompt()<br>                //.advisors(new SimpleLoggerAdvisor())<br>                .advisors(new ClearThreadUnsafeLoggerAdvisor())<br>                .user(message)<br>                .call()<br>                .content();<br>    }</pre><p>Notes:</p><ul><li>The user’s request is conveyed through the string <em>message</em>;</li><li>We are using an Advisor wrote by me to log the communication with the LLM in a clearer form. It is a deeply insecure class, with the only merit of logging the chat in a more comfortable way for the readers of this article. In production, please use SimpleLoggerAdvisor, powered by Spring AI;</li></ul><p>Finally, here’s an example of a client of our class:</p><pre>completionManager.chatResponse(&quot;What are the top three tulip exporting nations?&quot;);</pre><p>And related answer:</p><pre>request:<br>   SYSTEM: You are a helpful and kind agent, you know about flowers <br>           and the world production of the various nations. Respond with <br>           a simple list of countries, without further comment.<br>   USER: Which are the top three tulip exporting nations?<br><br>response:<br>   ASSISTANT: 1. Netherlands<br>              2. Poland<br>              3. Germany</pre><p>The AI’s responses, evidently, are not produced by our applications so there is no template for them: however, it is possible to instruct the model to respond to us in a particular format, for example in JSON. Until recently, it was not so easy to convince an LLM to return only JSON because it often anticipated it with an enthusiastic comment like: <em>“of course I can respond with a JSON here it is:”</em>.</p><p>Now you can force the response format out of the prompt, directly in the service call:</p><pre>public Works entity(String message) {<br>  var outputConverter = new BeanOutputConverter&lt;&gt;(CompletionManager.Works.class);<br>  ChatResponse response =chatClient.prompt()<br>          .advisors(new ClearThreadUnsafeLoggerAdvisor())<br>          .system(&quot;You are a fine man of letters, a lover of Polish poetry and eager to make it known all over the world.&quot;)<br>          .options(OpenAiChatOptions.builder()<br>                  .withModel(OpenAiApi.ChatModel.GPT_4_O_MINI)<br>                  .withResponseFormat(new ResponseFormat(ResponseFormat.Type.JSON_SCHEMA, outputConverter.getJsonSchema()))<br>                  .build())<br>          .user(message)<br>          .call()<br>          .chatResponse();<br>  String content = response.getResult().getOutput().getContent();<br>  return outputConverter.convert(content);<br>}</pre><p>Notes:</p><ul><li>Using the OpenAIChatOptions class, we’re passing in model-specific options. In addition to indicating the response format, there are many other options, such as the temperature of the response;</li><li>We used a different model from OpenAI, the good <em>gpt-4o-mini</em>;</li><li>We’ve replaced the default SYSTEM message, just to show that this is possible;</li><li>In the <em>content variable</em>, the JSON string returned by the model;</li></ul><p>Now, our class has the responsibility of returning the LLM answers in a model-independent format to make it usable by the other application layers. In the example, if the request is to have a list of the most beautiful lyrics by the Polish poet Wisława Szymborska, we will have to define a special DTO and return an instance.</p><pre>record Works(@JsonProperty(required = true, value = &quot;works&quot;) Work[] works,<br>             @JsonProperty(required = true, value = &quot;poet_name&quot;) String poet) {<br>    <br>      record Work(@JsonProperty(required = true, value = &quot;title&quot;) String title,<br>                    @JsonProperty(required = true, value = &quot;year&quot;) Integer year) {<br>        }<br>}}</pre><h3>Memory</h3><p>After countless conversations with ChatGPT or Gemini or LLama, it may perhaps be surprising to discover that LLMs are stateless services: each call is independent of the others and there is no session. Let’s check it:</p><pre>completionManager.chatResponse(&quot;What are the top three tulip exporting nations?&quot;);<br>completionManager.chatResponse(&quot;And the fourth?&quot;);</pre><p>The answer will look like:</p><pre>request:<br>   SYSTEM: You are a helpful and kind agent,you know about flowers...<br>   USER: Which are the top three tulip exporting nations?<br><br>response:<br>   ASSISTANT: 1. Netherlands<br>              2. United States<br>              3. Japan<br>request:<br>   SYSTEM: You are a helpful and kind agent you know about flowers...<br>   USER: And the fourth?<br><br>response:<br>   <strong>ASSISTANT:</strong> <strong>I&#39;m sorry, but I&#39;m not sure what you&#39;re asking. Can you give <br>              me more context or clarify your question?</strong></pre><p>To be able to hold a dialog, you must report in the most recent prompt the conversation that has taken place so far.</p><p>This injection into the prompt (be it SYSTEM or USER) is often referred to as <em>stuff prompting </em>and it is the task of our application to take care of it, using the appropriate classes of the different libraries that generally take the name of Memory.</p><p>Spring AI has a couple of very basic classes for memory management; to use them you need to add the appropriate advisor to the ChatClient instance:</p><pre>@Bean ChatMemory chatMemory() {<br>      return new InMemoryChatMemory();<br>}<br><br>...<br>chatClient =  builder<br>      .defaultSystem(flowersSystem)<br>      .defaultAdvisors(List.of(new MessageChatMemoryAdvisor(chatMemory) ))<br>      .build();</pre><p>After this change, let’s verify the response to the newly generated conversation:</p><pre>request:<br>   SYSTEM: You are a helpful and kind agent,you know about flowers...<br>   USER: Which are the top three tulip exporting nations?<br><br>response:<br>   ASSISTANT: - Netherlands<br>              - Germany<br>              - France<br>request:<br>   SYSTEM: You are a helpful and kind agent,you know about flowers...<br>   <strong>USER: Which are the top three tulip exporting nations?</strong><br>   <strong>ASSISTANT: - Netherlands<br>              - Germany<br>              - France</strong><br>   USER: And the fourth?<br><br>response:<br>   ASSISTANT: Italy</pre><p>Note:</p><ul><li>in the second request, the previous conversation was also inserted (stuffed);</li></ul><p>The ability to persist a conversation on files or databases is delegated to classes called by langchain History: this library offers multiple persistence options while Spring AI, at the moment, only one through the CassandraChatMemory class (guess which database it saves on? 😊 )</p><p>Adding the whole conversation to the context finds its biggest obstacle in the limitation of the prompt: each LLM accepts only a certain number of characters (tokens, more precisely) and not one more. Costs would also be an issue to consider because the fees are based on tokens, which are fractions of the words entered in the prompts. For these reasons, langchain has classes, such as ConversationSummaryMemory, which summarize the previous conversation, so that only this excerpt is injected into the prompt. Obviously, at the price of more interactions with the model.</p><h3>Functions</h3><p>In carrying out its task, an LLM can resort to external functions. Be careful, it is not able to invoke them, it can simply ask our application to do so.</p><pre>{<br>  &quot;$schema&quot;: &quot;https://json-schema.org/draft/2020-12/schema&quot;,<br>  &quot;name&quot;: &quot;orderStatusService&quot;,<br>  &quot;description&quot;: &quot;Returns the status of the order&quot;,<br>  &quot;parameters&quot;: {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>      &quot;order_code&quot;: {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;description&quot;: &quot;The order code, e.g. XX-427&quot;<br>      }<br>    },<br>    &quot;required&quot;: [&quot;order_code&quot;]<br>  }<br>}</pre><p>You must pass the json schema of the functions it can call to the model, the example above refers to a function to get the state of an order; the only parameter is the order identification code. LLM only uses descriptions, function names, and parameters to understand how to use them, which must therefore be very clear and comprehensive.</p><p>The json schema is produced starting from our source code, using annotations.</p><pre>@Service<br>public class OrderStatusService implements Function&lt;OrderStatusService.Request, OrderStatusService.Response&gt; {<br>@JsonClassDescription(&quot;Returns the status of the order&quot;)<br>    public record Request(@JsonProperty(required = true, value = &quot;order_code&quot;)<br>                              @JsonPropertyDescription(&quot;The order code, e.g. XX-427&quot;) String orderCode) {<br>    }<br>    public record Response(Status status) {<br>    }<br>    public enum Status {<br>        RICEIVED, SEND, REFIUSED, DELIVERED;<br>        public static Status getRandom() {<br>            Status[] stati = values();<br>            return stati[new Random().nextInt(stati.length)];<br>        }<br>    }<br>    public Response apply(Request request) {<br>        return new Response(Status.getRandom());<br>    }<br>}</pre><p>Notes:</p><ul><li>There are many ways to configure the functions to be passed to the LLM, here I present an alternative way to the official documentation, defining a component of Spring in which it is possible to inject other beans of the context;</li><li>The descriptions passed to the LLM are borrowed from the component and json annotations, remember to add them and describe them with simplicity and clarity;</li><li>Java is not a functional language, despite the introduction of lambdas and functional interfaces way back in Java 8. Passing a function to the LLM requires a little more code than dynamic languages. Our component, therefore, implements the default functional interface of the JDK, where the invocation takes place through the apply method;</li><li>In this example, the order status is returned randomly among the values of the Status enumerator;</li></ul><p>The functional must be passed to the ChatModel instance; we do it in another component, as in the previous examples:</p><pre>@Service<br>public class AgentManager {<br>    ChatClient chatClient;<br>    public AgentManager(@Value(&quot;classpath:/prompts/tool-system.st&quot;) Resource toolSystem,<br>                        ChatClient.Builder builder) {<br><br>        chatClient =  builder<br>                .defaultSystem(toolSystem)<br>                .defaultAdvisors(new ClearThreadUnsafeLoggerAdvisor())<br>                .defaultOptions(OpenAiChatOptions.builder()<br>                        .withFunction(&quot;orderStatusService&quot;)<br>                        .build())<br>                .build();<br>    }<br>    public String tools(String message) {<br>        return chatClient.prompt()<br>                .user(message)<br>                .call()<br>                .content();<br>    }<br>}</pre><p>Note:</p><ul><li>The only novelty is among the options of the model, where we pass the reference to the bean called <em>orderStatusService</em>;</li></ul><p>In the dialogue between the application and the model, the TOOL role intervenes. Is the fourth and last type of message:</p><pre>request:<br>   SYSTEM: You are the virtual assistant of an online bookstore. <br>           Respond to users with extreme kindness, remind them to always <br>           specify the order code, greet by remembering the name <br>           of the company: &quot;Scripta Manent&quot;<br><br>   USER: What status is the order with code AB-621 in?<br><br>response:<br>   ASSISTANT: I&#39;ll be happy to help you! A moment, please, while I check <br>              the status of the order with code AB-621.  <br>              orderStatusService({&quot;order_code&quot;:&quot;AB-621&quot;})<br><br>   <strong>… our application invokes the function<br></strong>request:<br>   <strong>TOOL: ToolResponse[id=call_527S70lYLcYLAgeKe4GmWjcc, <br>         name=orderStatusService, responseData={&quot;status&quot;:&quot;RICEIVED&quot;}]</strong><br><br>response:<br>   ASSISTANT: Your order with code AB-621 is currently being shipped. Thank you for contacting us and have a nice day from Scripta Manent!</pre><p>The assistant asks the application to invoke a specific function for which it passes the parameter: {“order_code”:”AB-621&quot;}. Spring acts as an agent and makes the call for us, passing the values obtained to the LLM {“status”:”RICEIVED”} with the next call, using a TOOL message.</p><p>Note:</p><ul><li>My log class fails to report agent messages because they happen inside the <em>OpenAIChatModel</em> class, before each advisor is invoked. You can still retrieve them by debugging the <em>OpenAIChatModel.doGetChatResponse </em>method<em> .</em>Or raise the logging level of the HTTP client in the <em>application.yaml</em>:</li></ul><pre>logging:<br>  level:<br>    org.springframework.web.client: DEBUG</pre><p>The model may require the subsequent invocation of several functions before responding to the user’s prompt.</p><p>In langchain nomenclature, a Chain capable of invoking functions is called an Agent while an AgentExecutor run one (or more) Agents until the LLM requests to invoke functions. Essentially, it handles the part of the conversation that requires functions to be performed. In Spring AI, as we have seen, it is the only ChatModel class to act as an agent in case functions are specified.</p><h3>End of part one</h3><p>The article continues in the <a href="https://medium.com/@nicolasanti_43152/rag-apps-for-legacy-spring-developers-part-2-e4a6744d0b22">next and last part</a>, where we will address the topics of embeddings, vector store, document retrieval and RAG application.</p><p>Thank you for reading.</p><h3>Bibliography</h3><p><a href="https://docs.spring.io/spring-ai/reference">https://docs.spring.io/<strong>spring-ai</strong>/reference</a> the official documentation of the new Spring AI library</p><p><a href="https://platform.openai.com/playground">https://platform.openai.com/<strong>playground</strong></a> a web console where you can interactively try out prompts, tools, and calls to OpenAI models</p><p><a href="https://python.langchain.com/">https://python.<strong>langchain</strong>.com</a> the official documentation of the world-famous Python langchain library</p><p><a href="https://llamaindex.ai/">https://<strong>llamaindex</strong>.ai</a> a python library to persist documents in various formats and in a multitude of different vector databases</p><p><a href="https://github.com/ggerganov/llama.cpp">https://github.com/ggerganov/<strong>llama.cpp</strong></a> an open-source project to deliver different models, even locally</p><p><a href="https://github.com/vllm-project/vllm">https://github.com/vllm-project/<strong>vllm</strong></a> another project similar to the previous one to provide several LLMs also locally</p><p><a href="https://www.h2database.com/">https://www.<strong>h2databas</strong>e.com</a> an excellent in-memory database</p><p><a href="https://www.postgresql.org/">https://www.<strong>postgresql</strong>.org</a> a formidable database, as long-lived as the elephant that symbolizes it</p><p><a href="https://github.com/pgvector/pgvector">https://github.com/pgvector/<strong>pgvector</strong></a> Postgresql extension to persist and search for embedding vectors</p><p><a href="https://github.com/langchain4j/langchain4j">https://github.com/langchain4j/<strong>langchain4j</strong></a> independent project compared to langchain but with a similar architecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be6e2f75516e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML, loss, and likelihood]]></title>
            <link>https://medium.com/@nicolasanti_43152/ml-loss-and-likelihood-e0a5ff4ae594?source=rss-a64fa76f94b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0a5ff4ae594</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[loss]]></category>
            <category><![CDATA[logistical-regression]]></category>
            <category><![CDATA[likelihood]]></category>
            <dc:creator><![CDATA[Nicola Santi]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 07:04:38 GMT</pubDate>
            <atom:updated>2024-09-07T07:04:38.593Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Where do loss functions come from?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*FT-PGZloQ-werCBmWKHJ1w.png" /></figure><p>While studying linear regression, I came across my first loss function, also called an error function. It was the <em>sum-of-squares</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*2ZTDj6vk7w10pMi8zneZ_A.png" /></figure><p>I immediately wondered why I had to use this function and not another: why was it divided by 2 and not by 3 or why raise to the square and not to the fourth, or take the absolute value?</p><p>Tutorials and documentation generally do not explain the origin of this function which appeared, in my eyes, completely arbitrary.</p><p>Going deeper into texts such as [3] in the bibliography, it turns out that there is a methodology to obtain the most correct loss function given the problem to be addressed based on maximizing <em>likelihood</em>.</p><p>In this article, I will try to clarify the origin of the most common loss functions (sum-of-squares and cross-entropy) focusing more on the method than on the calculations, which will still be reported for completeness but in a simplified form.</p><p>Let’s start 😊</p><h3>Probability function</h3><p>We toss a coin ten times, what is the probability of getting 4 heads up? Statistics provide us with a special function (called probability) to calculate it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*vX14Y19PJhK61Q3Gct0sQw.png" /></figure><p>We leave the calculations to the computers and accept that the probability is about 20.5%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*Qmzg53PdLi4FdiC1MeGwUg.png" /></figure><p>This probability function (called binomial) expects as input the number t of <em>heads</em> on ten coin tosses as input, and calculates the probability using as <em>a fixed datum</em> the probability <em>q</em> that, in a single toss, heads will come out. Let’s say 50%, as usual.</p><p>We can use the same probability function, varying <em>t</em>, to find out the probabilities of getting different numbers <em>t</em> of heads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*zqJ-xQTrOR2t6zi5ZNhiKA.png" /></figure><p>In general, a (discrete) probability function gives us the probabilities that the random variable is equal to a certain value <em>t</em>, assuming other <em>parameters q</em> as constants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*cUhfLg7-7lwuyQ4D3CqQmw.png" /></figure><p>It reads: the probability of <em>t</em> given <em>q</em>.</p><h3>Likelihood function</h3><p>And if, by tossing the coin ten times, we get heads 9 times, how likely would it be <em>to </em>think that we were dealing with a rigged coin? That is, that <em>q </em>is not really equal to 50%?</p><p>Very likely, we agree, but how much exactly? The idea behind likelihood is to always use our probability function (the binomial) but in reverse, that is, keeping <em>t</em> fixed (9 times heads) and varying <em>q</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*wJLn0lPyLJwJqqtBrXRnFA.png" /></figure><p>Here are the results for different values of <em>q</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*cG0kPq8KAO1z66bYdGXdIg.png" /></figure><p>Even from a quick read, it would seem more <em>likely</em> that <em>q</em> is closer to 90% than 50%.</p><p>When we use the probability function in this way, i.e. not to calculate the probability of a certain outcome <em>t </em>based on fixed parameters <em>q</em> but, on the contrary, to calculate precisely those values of <em>q</em>, taking the evidence obtained t at face value, the probability function becomes a likelihood function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*SWblF3YfQHtQuqoR0ekBuA.png" /></figure><p>In words it is even easier: we are wondering, given that 9 heads have come out, given this evidence or dataset, how likely is it that <em>q</em> is .5, or .6, 0.7 or any other value?</p><p>You may have noticed that, instead of the more canonical <em>x</em>, we used the letter <em>t</em> to indicate the random variable because it indicates the truth, that is, the values that came out when the coins were thrown.</p><h3>Maximum likelihood</h3><p>To understand which was the most probable value of <em>q</em>, having obtained 9 times heads, we tried different values of <em>q</em> in the likelihood function looking for the highest one, i.e. the most probable.</p><p>The values of <em>q</em>, however, are infinite, contrary to our patience, therefore, it is better to proceed by directly maximizing the likelihood function as we studied at school, that is, first deriving it and then finding the value of <em>q</em> for which the derived function cancels out. The calculations, for now, do not interest us and we jump directly to the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*nB-8EJUn7lxT6zIyvNuUAA.png" /></figure><p>We have obtained the formula of an estimator for the parameter <em>q,</em> called maximum likelihood, which allows us to predict, after a series of heads <em>t</em>, the most likely value of <em>q</em>. As the previous table also suggested, the value is 90%: our currency is heavily rigged!</p><h3>Limitations of use</h3><p>Is always permissible to use the maximum likelihood estimator for <em>q</em> that we have just found? Of course not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*XnvjBebaQURZmIUuPurGEg.png" /></figure><p>The estimator is obtained by maximizing a specific likelihood function which in turn derives from a specific probability function, the binomial. So, whenever we are faced with a machine learning task that has that precise probability function, or a very similar one, then our estimator for <em>q </em>will provide useful values.</p><p>When, on the other hand, the probability function of <em>t </em>is very different from the binomial, our estimator will produce very poor results.</p><p><strong>Note:</strong> At this point, you should have a pretty good idea of what the maximum likelihood method is. In the next two paragraphs, we will apply the same method to two problems of machine learning, regression and classification, to obtain the sum-of-squares and cross-entropy loss functions, respectively. Mathematics will perhaps be a little more complex, even if only slightly: the invitation is to use it only if can be useful to you, otherwise continue to follow the general reasoning. In particular, the next paragraph calculates a maximum likelihood estimator for a normal distribution, safely skip it if you are not interested in calculations.</p><h3>Gaussian distribution</h3><p>Let’s look at another example of a likelihood function moving, as in the previous paragraphs, from the probability function. In this case, a normal (or Gaussian) distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*b9cLv35xz1r2L-PggM6CNg.png" /></figure><p>The formula is vaguely intimidating, on the other hand the graph is very simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*z3a493Wy6LqhM_59kg9XZQ.png" /></figure><p>We see four normal distributions that depend on only two parameters, the mean and the variance and are perfectly symmetrical, with no outliers.</p><p>Extracting <em>N</em> linearly <em>independent samples</em>, the probability function that that sample will come out is given by the product of the probabilities of the individual samples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*96IrOd6uwLbPbfb74mbV7g.png" /></figure><p>Which, for what has been said, can be considered our likelihood function, inverting variable and parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*lUgvBFm1WUwysK_FqKsfyg.png" /></figure><p>Often, a logarithmic transformation function is applied to the likelihood function that does not change its maximum value (mean and variance) but greatly simplifies the calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*2nR7J1nBGM1XQtv-gKitZw.png" /></figure><p>This function is called, unsurprisingly, log-verisimilitude.</p><p>We just have to find the maximum respect, for example, to the parameter μ to obtain the maximum likelihood estimator of the mean. Suffice it to note that the last two addends do not depend on μ, so we can ignore them. Just like the first variance in the denominator, which scales the function but does not change its maximum. Then, we derive and find zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*oRCn6s8mAhTdvgBfHGvDYw.png" /></figure><p>The calculations are very simple, as you can see, and lead to the maximum likelihood estimator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*eXGy_smIcbSNEvO_9dh1Ww.png" /></figure><h3>Loss Functions</h3><p>Machine learning libraries, for each model, suggest that we use specific loss functions (also called error functions) for evaluation or training, but they do not always explain why to use those functions and not others, so much so that the choice may seem completely arbitrary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*QG7kDIKM_iPJruAPFMXXjA.png" /></figure><p>In reality, commonly used loss functions are nothing more than (transformations) of likelihood functions. They are created by following the steps schematized above: it all starts by assuming a certain probability function from which to extract N linearly independent samples and find the likelihood function with respect to the parameters of the model, as we have already seen. The loss function is nothing more than the opposite of the likelihood function (or log-likelihood) because our model will have to take care of minimizing it (instead of maximizing it).</p><p>In the next paragraphs, we will see this process in detail for two common machine learning tasks:</p><ul><li>Linear regression;</li><li>Binary classification;</li></ul><blockquote><strong>Note: </strong>To keep the promise of simplifying calculations, in the next few paragraphs we will completely ignore the concept of bases, also called features, by directly using the <strong><em>x</em></strong> input values. <em>The purpose of this article is to provide rigorous insight even at the expense of mathematical rigor.</em></blockquote><h3>Linear regression</h3><p>The task consists of guessing the value of the real variable <em>t</em>, assuming that it can be predicted using a linear function of some <em>variables</em><strong><em> x</em></strong> (and of the learnable parameters <strong>w </strong>of the model):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*XGJzIcF4ghg_dgR7M1yQvQ.png" /></figure><p>We also hypothesize a certain noise around our variable <em>t</em>, which disturbs our readings and prevents us from seeing its real value. Finally, we assume that this noise is distributed as a normal with mean <em>y()</em> and some variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*E7hitRbs0KuC-tNllzQdbg.png" /></figure><p>Graphically:</p><figure><img alt="Bishop, figure 2.11" src="https://cdn-images-1.medium.com/max/313/1*6BpLXzBKKdZLd_7p5RbSmg.png" /><figcaption>Bishop, figure 2.11</figcaption></figure><p>Under these assumptions, having obtained <em>N</em> linearly independent samples {tn, <strong>xn</strong>}, the likelihood function (or rather, the logarithm of this function) is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*Anz_leCiy9HDewDJ1Rjvww.png" /></figure><p>If we discard, as we have seen, additive and multiplicative constants (with respect to the w weights for which we are deriving) and multiply by -1, we get the well-known loss (or error) function called <em>sum-of-squares</em> that we have known since our first machine learning model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*2ZTDj6vk7w10pMi8zneZ_A.png" /></figure><p>That’s it.</p><p>To recap, the <em>sum-of-square </em>loss function coincides, for our minimization problem, with the likelihood function under very precise assumptions:</p><ul><li>the variable <em>t</em> has detection errors that are distributed like a normal;</li><li>the mean of this variable is a linear function of <em>parameters</em><strong><em> w</em></strong>;</li></ul><p>The less true these assumptions are, the less accurate a model trained with this loss function will be.</p><h3>Binary classification</h3><p>It consists of predicting the value of the variable t (also called label) which can only be:</p><ul><li>t=0, then the observation <strong><em>x</em></strong> belongs to class C₁;</li><li>t=1, then the observation <strong><em>x</em></strong> belongs to class C₂;</li></ul><p>The so-called logistic regression model (a rather ambiguous name because it is not regression but classification) allows the use of a linear function for this task to which a nonlinear function called activation (whose inverse is called link in the statistical literature) is subsequently applied:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*G2Q3HQT4PxrijpaPcD4sFQ.png" /></figure><p>The specific activation function in the formula is called <em>logistic sigmoid</em> (in the figure below) and allows us to obtain values between (0,1) that we can interpret as the probability <em>p(C</em>₁<em>|x), </em>i.e. the probability of being in class <em>C</em>₁<em> </em>given the input <strong><em>x</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*R2-ew1R856pD6Tub_yip5A.png" /></figure><p>But what are the assumptions behind such a function? Without going into too much mathematical detail, it is required that the class-conditional probability (density) function p<em>(</em><strong><em>x|C</em></strong>₁<em>) </em>be distributed as a multivariate normal, and so far, we do not deviate from the usual assumptions. In addition, however, it is also assumed that the covariance matrix <strong>∑ </strong>is the same for all classes</p><p>Under these conditions, the input value space is divided into decision regions whose boundaries are linear, and thus the linear model of our logistic regression is justified.</p><blockquote><strong>Note</strong>: Decision regions are a partition of the input value space, if a specific <strong>x</strong> value falls in the decision region of, say, class <em>C</em>₁<em> </em>then our model would classify <strong>x</strong> as belonging to that class. In the figure below on the right, taken from [3], we see three decision regions, only between the red and the blue the border is linear. The figure on the left shows the normal density function from which the decision areas are derived.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*kBGvwPuDaz_Zf6v_Y7sg8g.png" /><figcaption>Bishop, figure 5.14</figcaption></figure><p>Thus, interpreting <em>y()</em> as the probability <em>p(C</em>₁<em>|x) </em>and <em>(1-y)</em> as the probability of <em>p(C</em>₂<em>|x), </em>the (conditional) probability distribution becomes the binomial:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*Zy8t_cjtHEQH7xCVVEo8zQ.png" /></figure><p>Under the assumption of independent samples, the likelihood will therefore be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*qoSBbcQ4v8b_Nb2sGk5IlA.png" /></figure><p>We can obtain the loss function by taking the likelihood function with the minus sign and applying a logarithmic transformation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*uOUMqQE7dRQocxwC2DxqSw.png" /></figure><p>We thus obtain the well-known loss function called <em>cross-entropy</em> proposed by all machine learning libraries for logistic regression (with sigmoid activation function).</p><p>Using a different loss function for this type of problem, such as <em>sum-of-squares</em>, produces longer training and worse generalization (Simard, Steinkraus and Platt, 2003) reiterating the core of this article: loss functions cannot be chosen at random but derive from likelihood on a specific probability function.</p><p>Conversely, using cross-entropy when the class-conditional function is not normal or the covariance matrix is not the same for all classes, will still lead to poor results.</p><h3>Validity of assumptions</h3><p>When is it safe to assume that probability distributions are normal? In other words, how good our models, activation and loss functions are.</p><p>Statistics suggest that the normal distribution is, in general, a good approximation of the true distribution when the random variables derive from multiple factors independent of each other. Furthermore, and more precisely, the central limit theorem states that the sum of a large number of independent distributions tends to distribute as a normal.</p><p>This theorem provides the most robust theoretical basis for using normal distribution in many machine learning tasks.</p><p>However, the ultimate meaning of this article is to remember that normal distribution is not always a correct assumption and assuming it can lead to incorrect or poor results. Examples include:</p><p>· <strong>Outlier distributions</strong>: the normal is symmetrical, outliers are not contemplated. In this case, there are more appropriate distributions such as <em>Cauchy</em>’s or <em>Student’s t</em>;</p><p>· <strong>Asymmetric samples</strong>: the normal is symmetrical, in fact. On these data, the <em>logarithmic normal</em> distribution or <em>the Gamma</em> work better;</p><p>· <strong>Categories</strong>: The normal is a continuous distribution over real variables, using it to directly infer categories, for example variables that can take as values, for example, only 0 or 1, is not a good choice. Please note that the logistic regression model presented in this article is not used directly to infer the category but to determine its probability p(Cₖ|<strong>x</strong>), as opposed to models such as discriminant functions which, precisely because of this limitation, generally have worse performance;</p><h3>Conclusions</h3><p>This article adds to the millions of others related to likelihood functions, trying to clarify the origin of some loss functions and, ultimately, warning about the assumptions and limitations of using the most basic machine learning models.</p><p>Thanks for reading 😊</p><h3>References</h3><p>1. <a href="https://homepage.divms.uiowa.edu/~mbognar/applets/bin.html">https://homepage.divms.uiowa.edu/~mbognar/applets/bin.html</a> <em>Calculation and graph of the binomial distribution, all online.</em></p><p>2. <a href="https://statproofbook.github.io/P/bin-mle.html">https://statproofbook.github.io/P/bin-mle.html</a><em> Proof of the likelihood estimator for the binomial distribution.</em></p><p>3. <a href="https://www.bishopbook.com/">https://www.bishopbook.com/</a> <em>A comprehensive, rigorous and very clear manual that I recommend to anyone who wants to understand deep learning in depth.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0a5ff4ae594" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>