Aggiungere risposte di IA generativa all'app di esempio SociaLite
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
L'app di esempio SocialLite mostra come utilizzare le API di piattaforma Android per implementare funzionalità comunemente implementate nei social network e nelle app di comunicazione. Abbiamo integrato l'API Gemini utilizzando l'SDK Firebase AI Logic per dimostrare come le funzionalità di chatbot possono essere implementate nelle tue app per Android.
Questo codice di esempio utilizza Gemini Flash, che è rapido e conveniente.
Scopri di più sui modelli Gemini. Per implementare un chatbot basato sull'IA nella demo di Socialite, abbiamo utilizzato la funzionalità delle istruzioni di sistema dell'API Gemini per modificare il comportamento del modello. In questo caso, utilizziamo il prompt "Rispondi a questa conversazione in chat come un gatto amichevole". Questa versione di SociaLite integrata con Gemini utilizza anche le funzionalità multimodali del modello per consentire al chatbot di reagire alle immagini.
Implementare l'API Gemini
L'implementazione del chatbot si trova principalmente nella classe ChatRepository.
La classe GenerativeModel ti consente di interagire con l'API Gemini, che viene istanzata come segue:
valgenerativeModel=GenerativeModel(// Set the model name to the latest Gemini model.modelName="gemini-2.0-flash-lite-001",// Set a system instruction to set the behavior of the model.systemInstruction=content{text("Please respond to this chat conversation like a friendly cat.")},)
In un ambito di coroutine, avvia una chat passando pastMessages a startChat()
per assicurarti che il modello abbia accesso alla cronologia delle conversazioni. In questo modo, il chatbot può mantenere il contesto e generare risposte coerenti che si basano sugli scambi precedenti.
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-07-27 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-07-27 UTC."],[],[],null,["# Add generative AI responses the SociaLite sample app\n\nThe [SociaLite sample app](https://github.com/android/socialite) demonstrates how to use Android\nplatform APIs to implement features that are commonly deployed in social network\nand communications apps. We have integrated the Gemini API using the Firebase AI\nLogic SDK to demonstrate how chatbot capabilities can be implemented in your\nown Android apps.\n\nThis sample code uses Gemini Flash which fast and cost-effective.\n[Learn more about the Gemini models](https://firebase.google.com/docs/ai-logic/models). To implement an AI-driven chatbot in\nthe Socialite demo, we used the [*system instructions*](https://firebase.google.com/docs/ai-logic/system-instructions)\nfunctionality of the Gemini API to modify the behavior of the model. In this\ncase, we use the prompt \"Please respond to this chat conversation like a\nfriendly cat\". This Gemini-infused version of SociaLite also uses the multimodal\ncapabilities of the model to let the chatbot react to images.\n\nImplement the Gemini API\n------------------------\n\nThe chatbot implementation is primarily located in the `ChatRepository` class.\nThe `GenerativeModel` class lets you interact with the Gemini API, which is\ninstantiated as follows: \n\n val generativeModel = GenerativeModel(\n // Set the model name to the latest Gemini model.\n modelName = \"gemini-2.0-flash-lite-001\",\n // Set a system instruction to set the behavior of the model.\n systemInstruction = content {\n text(\"Please respond to this chat conversation like a friendly cat.\")\n },\n )\n\nIn a coroutine scope, initiate a chat by passing `pastMessages` to `startChat()`\nto ensure that the model has access to conversation history. This gives your\nchatbot the ability to maintain context and generate coherent responses that\nbuild on previous exchanges. \n\n val pastMessages = getMessageHistory(chatId)\n val chat = generativeModel.startChat(\n history = pastMessages,\n )\n\nUse the `sendMessage()` method to pass messages to the model.\n\nTest the AI chatbot\n-------------------\n\nYou can test it yourself by following these steps:\n\n1. Check out the code for the [SociaLite sample app](https://github.com/android/socialite) and open it in Android Studio.\n2. Set up a Firebase Project, connect your app to the *Gemini Developer API* by following [these steps](https://firebase.google.com/docs/ai-logic/get-started?platform=android&api=dev),\n3. Replace google-services.json with your own \\& Run `app` configuration,\n4. Sync and run your app.\n5. In the SociaLite app, tap **Settings** and then tap **AI Chatbot** so that the button label reads \"*AI Chatbot: enabled*\".\n\nYou are now ready to chat!\n\nAdditional resources\n--------------------\n\n[Learn more about the Firebase AI Logic SDK](/ai/gemini)."]]