<?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 N&#39;nane on Medium]]></title>
        <description><![CDATA[Stories by N&#39;nane on Medium]]></description>
        <link>https://medium.com/@nnane?source=rss-284fbd06680------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fQBnBAfjMnFFbIzw</url>
            <title>Stories by N&amp;#39;nane on Medium</title>
            <link>https://medium.com/@nnane?source=rss-284fbd06680------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 16:54:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nnane/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[Sénégal, Google et souveraîneté]]></title>
            <link>https://medium.com/@nnane/s%C3%A9n%C3%A9gal-google-et-souvera%C3%AEnet%C3%A9-4444ff92897e?source=rss-284fbd06680------2</link>
            <guid isPermaLink="false">https://medium.com/p/4444ff92897e</guid>
            <category><![CDATA[senegal]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[souveraineté-numérique]]></category>
            <category><![CDATA[afrique]]></category>
            <category><![CDATA[cameroun]]></category>
            <dc:creator><![CDATA[N'nane]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 20:33:25 GMT</pubDate>
            <atom:updated>2024-10-18T20:33:25.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hEyhOVbdknp36jYC.png" /></figure><p><em>Source : Le Sénégal face au dilemme du cloud : souveraineté ou dépendance ? — CIOMAG</em></p><blockquote><em>Le Sénégal et Google ont signé le 1er octobre 2024, un protocole d’accord historique pour la mise en place d’un cloud souverain à Dakar</em></blockquote><blockquote><a href="https://cybersecuritymag.africa/le-senegal-et-google-signent-un-accord-pour-creer-un-cloud-souverain"><em>Mise en place de cloud souverain en Afrique : le Sénégal et Google signent un accord pour créer une infrastructure dédiée | Africa Cybersecurity Magazine</em></a></blockquote><p>Il a été annoncé, il y a quelques jours, que Sénégal est en discussion avec Google Cloud pour lancer une initiative de cloud souverain dans le cadre de sa <a href="https://www.rts.sn/actualite/detail/a-la-une/lancement-de-la-strategie-senegal-numerique-2025-2035-le-ministre-de-leconomie-numerique-appelle-a-une-forte-implication-du-secteur">stratégie sénégal numérique 2025–2035</a>. J’ai ainsi découvert avec étonnement (et joie) l’engagement manifeste du Sénégal sur cette voie de l’affirmation numérique. La souveraîneté est un enjeu majeur pour les États pour assurer la sécurité et l’exclusivité de certaines ressources critiques.</p><p>Mais, la nouvelle du partenariat intérroge : Comment le Sénégal pourrait être souverain grâce un partenariat avec Google, une entreprise avant tout <strong>américaine</strong> ?</p><blockquote><em>Pour ceux qui ne sont pas familiers avec le concept de cloud, regardez cette vidéo : </em><a href="https://www.youtube.com/watch?v=5YawCCUxa_E"><em>Qu’est ce que le Cloud ? — YouTube</em></a><em> et écoutez ces discussions pour être plus au fait sur les enjeux de la souveraîneté numérique : </em><a href="https://www.youtube.com/watch?v=tfa34GWjfJM"><em>Panel 2 : QUID DE LA SECURITE DES DONNEES ? — YouTube</em></a><em> et </em><a href="https://www.youtube.com/watch?v=ZdcFto80odA"><em>SOUVERAINETÉ NUMÉRIQUE :sommes-nous sous l’emprise des GAFAM ? Alain Juillet reçoit Pascal Saubion — YouTube</em></a><em> .</em></blockquote><h3>Être souverain</h3><p>Un Cloud souverain (relativement à un État) est souvent défini comme un environnement de Cloud computing qui permet d’opérer le stockage et le traitement de ses données en conformité exclusive avec ses lois et libre d’ingérences externes <a href="https://youtu.be/ZdcFto80odA?feature=shared&amp;t=392">comme l’expliquait Pascal Saubion</a>. Pour être considéré souverain il faut répondre à des <a href="https://learn.microsoft.com/en-us/industry/sovereignty/evaluate-sovereign-requirements">exigences</a>, il faut notamment avoir le contrôle/choix sur l’accès et le partage des données, le contrôle sur comment les infrastructures et services qui supportent le traitement de ces données sont opérées, la transparence et la gouvernance des opérations.</p><blockquote><em>Voir plus de détails ici : </em><a href="https://www.youtube.com/watch?v=Chq1LI-3d0A"><em>What is Sovereign Cloud? — YouTube</em></a></blockquote><h3>Google Cloud souverain ?</h3><h3>Google Cloud</h3><p><a href="https://cloud.google.com/?hl=en">Google Cloud</a> est une entrerpise américaine offrant des services de Cloud Computing. Son <a href="https://cloud.google.com/architecture/framework/security/shared-responsibility-shared-fate#shared_responsibility">modèle de responsabilité</a> lui incombe la responsabilité d’audit, de la gestion du matériel, des logiciels de base (OS, utilitaires, etc), du stockage des données et du réseau. Ses services sont donc accessibles presque partout dans le monde avec Internet, ses infrastructures et opérations managées par ses employés. Autant de caractéristiques qui s’opposent au concept de souveraîneté.</p><p>Cependant, ce n’est pas la première fois que le géant américain se prête à l’exercice de proposer un Cloud compatible aux restrictions susmentionnées : un essai a déjà été fait en France/Europe avec <a href="https://www.s3ns.io/en">S3NS</a> et dont je me suis inspiré pour présenter les <a href="https://www.s3ns.io/assets/White_paper_Local_controls_by_S3_NS_June_2022_Edition_011f58d819/White_paper_Local_controls_by_S3_NS_June_2022_Edition_011f58d819.pdf">dispositions qui peuvent être prises</a> dans la suite : la solution serait donc d’utiliser les datacenters américains (appartenant à Google) mais avec des règles de fonctionnement particulières pour répondre aux exigences de la souveraîneté.</p><blockquote>Si cet article vous plaît et vous en voulez encore plus, la meilleure façon de me soutenir c’est de le partager ou de vous abonner <a href="https://nnane.substack.com/subscribe">https://nnane.substack.com/subscribe</a></blockquote><h3>Des mesures possibles</h3><p>Pour répondre aux exigences que requiert la souveraîneté, il faut donc établir des modes et moyens de fonctionnement particuliers dans la relation État-Google.</p><p>Ainsi, pour s’assurer la résidence des données, et que les bonnes lois s’y appliquent malgré l’usage d’un cloud provider, l’on peut imposer des <a href="https://cloud.google.com/blog/products/identity-security/meet-data-residency-requirements-with-google-cloud?hl=en">contraintes sur la localisation des données</a> dans des data centers autorisés en utilisant des politiques logicielles. En outre, il est possible également assurer que seules les personnes autorisées aient accès aux données grâce au chiffrement systématique des données avec des clés inaccessibles de la part de Google.</p><p>Aussi, pour garantir que même les données chiffrées ne soient pas accessibles, <a href="https://cloud.google.com/assured-workloads/access-approval/docs/overview">des règles d’accès</a> (pour maintenance ou autre) strictes seraient mises en place pour demander l’autorisation explicite du gouvernement sénégalais.</p><p>Pareillement, afin de garantir le contrôle sur la chaine d’approvisionnement en logiciels et éviter des changements non autorisés (ou malicieux dans le pire des cas), l’on peut exiger des audits et validation par des experts agréés de l’infrastructure ou des logiciels utilisés. Une sorte de partage de propriété.</p><p>Et pour finir, pour se protéger de lois externes qui s’appliquent sur les personnels et ressources étrangères, avoir des exigences sur le personnel autorisé sur les sites choisis ou sur les logiciels mis en place. En illustration, la loi RPC chinoise sur le renseignement peut par exemple imposer l’espionnage à toute structure ou citoyen chinois. Il serait possible de mettre des règles de nationalité ou <a href="https://www.state.gov/securityclearances">d’elligibilité</a> dans ces data centers.</p><p>Malgré ces mesures, ça reste des compromis et un pari, car il y aura toujours une part non contrôlable. En effet, rien n’empêche (à ma connaissance) que tout contrat fait soit résilié. Aussi, certaines complications techniques rendent la perspective quasiment impossible, notamment l’existence des lois extraterritoriales invasives comme le Cloud Act américain qui donne le droit aux USA d’obtenir des opérateurs télécoms et des fournisseurs de services de Cloud des informations stockées sur leurs serveurs peu importe la localisation.</p><p>C’est en fait une <a href="https://www.aneo.eu/en/blog/cloud-souverain-cloud-de-confiance">relation “de confiance”</a> entre l’État et l’entreprise qui se fait. D’ailleurs, l’offre de Google en France est labelisée <a href="https://www.challenges.fr/entreprise/tech-numerique/accord-thales-google-bercy-abandonne-le-cloud-souverain-pour-le-plus-grand-bonheur-des-gafam_784302">“Cloud de confiance”</a> . Cette relation suscite des inquiétudes et <a href="https://www.linkedin.com/pulse/vers-des-jours-encore-plus-sombres-pour-leurope-du-guillaume-poupard-b1zve/">est sujette à critiques</a> de la part de certaines voix fortes. Cependant, ses défenseurs prônent sa nécessité car elle <a href="https://dev.to/psantus/secnumcloud-eucs-plaidoyer-pour-une-analyse-de-risques-rationnelle-47f8">semble être la voix unique viable</a> pour profiter des avantages du présent pour créer un futur souhaitable.</p><h3>Conclusion</h3><p>Comment le Sénégal pourrait être souverain grâce un partenariat avec Google, une entreprise américaine ?</p><p>La réponse est que la souveraîneté pleine ne sera sûrement pas possible au travers de ce partenariat car elle exige un contrôle absolu et une indépendance totale que l’usage d’un Cloud provider étranger ne peut pas fournir. Une relation de confiance mutuelle se présente alors comme la voie la plus envisageable en attendant l’émergence d’acteurs locaux. Un compromis, certes, mais un compris peut-être nécessaire pour l’atteinte de ses objectifs stratégiques.</p><p>Pour le moment rien n’est dit par rapport à la méthode sénégalaise, il serait donc intéressant de voir comment ils vont surmonter ce challenge.</p><p>Merci de m’avoir lu.</p><h3>A propos de moi et ce blog</h3><p>Je suis N’nane, camerounais et consultant Cloud spécialisé en data science et intelligence artificielle. Je réside en France où je travaille à accompagner des entreprises, petites et grandes, dans leur stratégie IA sur le Cloud. Sur ce blog, je partage mes expériences et avis sur l’IA, la data et le cloud, avec des contenus pratiques pour les passionnés et professionnels.</p><p>N’hésitez pas à mettre des commentaires si vous avez des questions ou des remarques, j’y répondrai avec plaisir.</p><blockquote>Si cet article vous plaît et vous en voulez encore plus, la meilleure façon de me soutenir c’est de le partager ou de vous abonner <a href="https://nnane.substack.com/subscribe">https://nnane.substack.com/subscribe</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4444ff92897e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement A genAI Code Review Bot with Google Cloud Platform]]></title>
            <link>https://medium.com/neoxia/implement-a-genai-code-review-bot-with-google-cloud-platform-2cf8c9369bdc?source=rss-284fbd06680------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf8c9369bdc</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[N'nane]]></dc:creator>
            <pubDate>Wed, 24 Apr 2024 12:50:01 GMT</pubDate>
            <atom:updated>2024-06-05T13:26:48.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BI467WL-C9nB7vnKxea_6w.png" /></figure><h3>Introduction</h3><p>In the rapidly changing landscape of software practices, DevOps principles have become essential to drive collaboration and efficiency between development and operations teams. DevOps practices emphasize continuous integration, delivery, and deployment to achieve faster development cycles and improved product quality. However, with the increasing complexity of modern applications and the demand for faster response times, innovative technologies such as generative artificial intelligence (AI) are integrated to augment and streamline DevOps processes.</p><p>This article explores the intersection of DevOps and generative AI, highlighting how AI-powered tools could revolutionize code review practices. We will look into the capabilities of generative AI models to provide insightful code reviews and discuss the implementation of an automated code review solution leveraging Google Cloud Platform (GCP) services.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F938531915%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F938531915&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1839943091-1023f19f27f517dbec745b45f507c3d51185eb109cd116486f7e119dd8219ab5-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ae1528e7424d97e04f3d21abff3511d/href">https://medium.com/media/1ae1528e7424d97e04f3d21abff3511d/href</a></iframe><h3>Generative AI in DevOps</h3><p>DevOps emphasizes agility and automation by combining software creation and operational activities in continuous, transparent cycles of build, integrate, test, monitor, respond, deliver, and deploy . The process involves iterative software practices such as continuous integration, testing, delivery, and deployment, which promote faster, higher-quality product releases with less risk. Continuous integration ensures that developers have constant access to updated and validated code, facilitating concurrent coding efforts and avoiding delays. Continuous testing ensures code functionality in various environments, identifying bugs for improvement. Automated monitoring and feedback throughout the pipeline enables real-time problem identification and responsive actions, improving system reliability and security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*6loImWueYpq-hLfQLdcjmQ.png" /><figcaption>DevOps processes Illustrated</figcaption></figure><p>As technology advances, developers are increasingly using artificial intelligence, particularly generative AI, to automate tasks, analyze data for insights, improve user experience, and optimize creative processes of software. This trend improves efficiency and promotes innovation in software creation. Stack Overflow 2023 survey shows that <a href="https://survey.stackoverflow.co/2023/#section-sentiment-and-usage-ai-tools-in-the-development-process">70% of responders have interest in using AI tools in their processes</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*yyJq2AO7vm5k5tKz7G-lkg.png" /><figcaption>Source : <a href="https://survey.stackoverflow.co/2023/#developer-tools-ai-tool-interested">StackOverflow Survey 2023</a></figcaption></figure><p>Along with growing developer interest, an <a href="https://paperswithcode.com/sota/code-generation-on-humaneval">increasing number of advanced models are being released</a>, as evidenced by the code generation rankings below. Generative AI models, moving closer to the skills of skilled developers, continually improve their ability to understand and generate code.</p><h3>Generative AI for code review in DevOps</h3><p>Generative AI can go beyond simply creating code: it can help us understand it better.</p><p>Code review is an <a href="https://en.wikipedia.org/wiki/Code_review">essential aspect of DevOps</a>, crucial for maintaining software quality (look at <a href="https://gist.github.com/thesamesam/223949d5a074ebc3dce9ee78baad9e27">XZ backdoor</a>). Traditionally, this process involves manual code inspection through pull requests. However, this method suffers from drawbacks including differences in reviewer skill levels, delays in feedback, inefficiencies in balancing review depth with feature delivery, format inconsistency, and overall boring nature especially for long pieces of code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/iamdevloper/status/397664295875805184&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/799d0bb5689f480e7ac19756de790395/href">https://medium.com/media/799d0bb5689f480e7ac19756de790395/href</a></iframe><p>Automated tools help, but current ones, based on static analysis, have limitations: they often provide disconnected feedback, are rigid and lack concrete solutions. Generative AI can improve this process by providing clear, natural reviews and helpful feedback, transforming the way we review code.</p><p>In this article, we will build an automated code review solution using generative AI. We will leverage <a href="https://cloud.google.com/?hl=en">Google Cloud Platform</a> (GCP) which has <a href="https://services.google.com/fh/files/misc/genai_privacy_google_cloud_202308.pdf">strong privacy garantees</a> regarding generative AI. GCP offers platforms such as Vertex AI and access to state-of-the-art generative AI models and even services to help Developers already like Gemini Code Assist. First, we’ll explore Gemini Code Assist and how it may help, then show how to build a custom tool using a Large Language Model (LLM) to automate pull request actions.</p><h3>Gemini Code Assist : Developer Assistance Tool</h3><p>In April 2024, Google Cloud Platform (GCP) launched <a href="https://cloud.google.com/products/gemini/code-assist?hl=en">Gemini Code Assist</a>, a coding tool available for a monthly subscription of $19 per user. This innovative solution integrates seamlessly with your IDE and Google Cloud Console.</p><p>Gemini Code Assist, is an enterprise-level coding assistance solution, supports private codebases stored on-premises, GitLab, GitHub, Bitbucket, or across multiple repositories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qrMCDErBPRGI56w6zBdag.png" /><figcaption><em>Illustration: Gemini Code Assist in action. Source: </em><a href="https://cloud.google.com/products/gemini/code-assist?hl=en"><em>Google</em></a></figcaption></figure><p>The main features of Gemini Code Assist include real-time code completion and automatic generation of blocks or functions, code explanation, leveraging Google’s Gemini 1.5 Pro model. It also provides a chat UI to discuss with your code and troubleshoot issues. This tool is designed to improve project accuracy and efficiency by providing a comprehensive overview of the project and enabling code transformation via natural language prompts.</p><p>Using its chat UI, users can request code reviews, but this requires intentional effort on the part of the user. To adhere to DevOps best practices, we aim to automate this process. Despite its comprehensive feature set, Gemini Code Assist currently lacks triggers for pull request actions, which is our primary goal.</p><p>For people with specific needs, developing a tailor-made solution can be valuable. This leads us to introduce our pull request agent bot driven by generative AI.</p><p>Our solution will benefit users who:</p><ul><li>Want to establish triggers beyond their IDE within their DevOps workflow</li><li>Desire for flexibility to explore various model options</li><li>Seek adaptability across multiple or custom platforms they use</li><li>Require the implementation of more personalized automated tasks</li></ul><p>Now let’s move on to the code.</p><h3>Pull Requests Code Review : Implementation from scratch</h3><p>We propose a simple solution that you can connect to your code repositories that will be able to leverage generative AI for automated reviews on your code.</p><p>The key components needed for our application are:</p><ul><li><a href="https://developers.google.com/workspace/guides/create-project">GCP Project:</a> This will serve as the foundation for our solution.</li><li><a href="https://github.com/">GitHub</a> (account) and Repository: Essential for testing our code.</li></ul><h4>Setup:</h4><ul><li>Create a New Folder and Environment:</li></ul><pre>bashCopy code<br>mkdir review-bot<br>cd review-bot<br>python -m venv venv<br>curl &lt;https://github.com/github/gitignore/blob/main/Python.gitignore&gt; &gt; .gitignore<br>git init<br>git add .gitignore</pre><ul><li>Create a GCP project (e.g., ‘test-review-bot’).</li><li>Ensure <a href="https://cloud.google.com/sdk/docs/install"><strong>gcloud</strong> CLI is installed</a> and initialized:</li></ul><pre>gcloud init</pre><ul><li><a href="https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini">Activate the required Gemini API</a> in your GCP project.</li></ul><h4>Accessing Google Gemini API:</h4><p>If you’re in a supported country, <a href="https://aistudio.google.com/app/apikey">create an assess Token</a> , then use the following code :</p><pre>export GOOGLE_API_KEY=&lt;YOUR API KEY&gt;</pre><pre>from langchain_google_genai import ChatGoogleGenerativeAI<br>import getpass<br>import os<br>if &quot;GOOGLE_API_KEY&quot; not in os.environ:<br>    os.environ[&quot;GOOGLE_API_KEY&quot;] = getpass.getpass(&quot;Provide your Google API Key&quot;)<br><br>if __name__==&quot;__main__&quot;:<br>  llm = ChatGoogleGenerativeAI(model=&quot;gemini-pro&quot;)<br>  print(llm.invoke(&quot;HI&quot;))</pre><p>For unsupported countries, we&#39;ll connect to GCP using our gcloud account and use this workaround to use Gemini:</p><pre>gcloud auth application-default login</pre><pre>from langchain_core.language_models.llms import LLM<br>from typing import Optional, Any, List<br>from vertexai.generative_models import (<br>    GenerationConfig,<br>    GenerativeModel,<br>    HarmBlockThreshold,<br>    HarmCategory,<br>    Part,<br>)<br>from langchain_core.callbacks.manager import CallbackManagerForLLMRun# This may change as it is available in preview only<br>from vertexai.preview.generative_models import GenerativeModel, ChatSession<br>import vertexai<br>PROJECT_ID = &quot;sandbox&quot;<br>LOCATION = &quot;us-central1&quot;<br>vertexai.init(project=PROJECT_ID, location=LOCATION)<br><br>class ChatGoogleGenerativeAI(LLM):<br>    model: str<br>    chat: Optional[ChatSession]<br>    safety_settings: Any<br>    def __init__(self: Any, *args: Any, **kwargs: Any) -&gt; None:<br>        super().__init__(*args, **kwargs)<br>        # Instantiating the ChatBot class<br>        self.model = GenerativeModel(self.model)<br>    @property<br>    def _llm_type(self) -&gt; str:<br>        return &quot;google_gemini&quot;<br>    def _call(<br>        self,<br>        prompt: str,<br>        stop: Optional[List[str]] = None,<br>        run_manager: Optional[CallbackManagerForLLMRun] = None,<br>        **kwargs: Any,<br>    ) -&gt; str:<br>        if stop is not None:<br>            raise ValueError(&quot;stop kwargs are not permitted.&quot;)<br>        response = self.model.generate_content(<br>            prompt, safety_settings=self.safety_settings<br>        )<br>        return response.text<br><br>if __name__==&quot;__main__&quot;:<br>  llm = ChatGoogleGenerativeAI(model=&quot;gemini-1.0-pro&quot;)<br>  print(llm.invoke(&quot;HI&quot;))</pre><p>We’re <a href="https://python.langchain.com/docs/modules/model_io/chat/custom_chat_model/">creating a custom LLM model </a>called ChatGoogleGenerativeAI to interact with Google Cloud Platform (GCP) using its native APIs, specifically focusing on the Vertex AI Generative Models (Gemini) service. This code defines a class that inherits from LLM (Language Learning Model) and includes settings to specify the GCP project ID (data-sandbox) and region (us-central1) for Gemini instantiation. Inside the class, we initialize a GenerativeModel object to handle chat interactions. The _call method processes user prompts, generates responses using the Gemini model, and returns the response text.</p><p>Wonderful! You can now have access to Gemini model by GCP!</p><h4><strong>Connect to GitHub</strong></h4><p>In order to comment on GitHub, your application needs a token, it will be used by the GitHub API to validate calls and enable you to read code source (if not public) or post comments.</p><p>You can <a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens">get an access token</a> that is classic or fine-grained (for more restrictions on what the token can do). If you choose a fine-grained token, you will need to choose the read access to code and metadata, read and write access to discussions and pull requests. Once you have your token, you can export it to your environment variables.</p><pre>export GITHUB_TOKEN=&lt;YOUR TOKEN&gt;</pre><p>Let’s see how to retrieve code diff (<a href="https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-comparing-branches-in-pull-requests">code comparison from two branches</a>) from a pull request. This code take the access_token, the repo and the branches that need to be compared to extract code diff. Create a utils.py file with this content:</p><pre>from typing import Optional<br>from git import Repo<br>import tempfile<br><br>def get_diff_from_repo_changes(<br>    access_token: str,<br>    repo_url: Optional[str] = None,<br>    base_branch_name: Optional[str] = None,<br>    topic_branch_name: str = &quot;main&quot;,<br>) -&gt; str:<br>    diff_content = &quot;&quot;<br>    with tempfile.TemporaryDirectory() as tmpdirname:<br>        repo_url = repo_url.replace(&quot;https://&quot;, f&quot;&lt;https://oauth2&gt;:{access_token}@&quot;)<br>        repo = Repo.clone_from(repo_url, to_path=tmpdirname)<br>        topic_branch_ref = f&quot;origin/{topic_branch_name}&quot;<br>        base_branch_ref = f&quot;origin/{base_branch_name}&quot;<br>        # Retrieve the commit hash where the HEAD is currently pointing<br>        if not base_branch_name:<br>            detached_head_commit_hash = repo.head.commit.hexsha<br>            base_branch_name = detached_head_commit_hash<br>        # Fetch the target branch from the remote<br>        repo.git.fetch(&quot;origin&quot;, topic_branch_name)<br>        # TODO: Ignore large config files diff like lock files<br>        diff_content = repo.git.diff(<br>            &quot;{}...{}&quot;.format(base_branch_ref, topic_branch_ref),<br>            ignore_blank_lines=True,<br>            ignore_space_at_eol=True,<br>        )<br>    return diff_content<br>if __name__==&quot;__main__&quot;:<br>    diff = get_diff_from_repo_changes(access_token=&quot;&quot;,repo_url=&quot;https://github.com/githubtraining/hellogitworld&quot;,base_branch_name=&quot;master&quot;,topic_branch_name=&quot;feature_division&gt;&quot;)<br>    print(diff)</pre><p>The get_diff_from_repo_changes function retrieves and returns the difference (or &quot;diff&quot;) between two branches in a Git repository that are going to be merged. It uses a provided access token for restricted repositories. The function then fetches the specified branches (base_branch_name and topic_branch_name) from the remote repository and computes the diff between them. The result, representing the changes between these branches, is returned as a string. The example in the __main__ block shows how to use this function by specifying the repository URL, base branch (master), and topic branch (feature_division) to print the resulting diff.</p><p>In our example as the code is public no access token is required, you can test the code using :</p><pre>python3 utils.py</pre><h4><strong>Create a &quot;server&quot; to respond to web requests</strong></h4><p>A webhook is an HTTP-based callback function enabling lightweight, event-driven communication between two APIs. They facilitate the flow of data from one application to another, triggering automation workflows in GitOps environments. When a pull request is initiated on GitHub, a webhook will trigger the call to the function we will define. GitHub sends a request containing all relevant information about the triggered pull request.</p><p>To begin, we need to create a function that handles incoming requests.</p><p>We will have to deploy this function on Cloud Functions, the serverless service of GCP, then configure Githtub with the URL (webhook) that it should trigger when a pull request is created.</p><p>Let&#39;s create a <a href="http://main.py/">main.py</a> file to handle web requests:</p><pre>from llm import ChatGoogleGenerativeAI<br>from utils import get_diff_from_repo_changes<br>import functions_framework<br>from flask import Request,HTTPException,Response,jsonify<br>from json.decoder import JSONDecodeError<br>from langchain.prompts import PromptTemplate<br>import requests<br>import os<br><br>@functions_framework.http<br>def review_github(request:Request)-&gt;Response:<br>    try:<br>        data = request.get_json(silent=True)<br>    except JSONDecodeError:<br>        raise HTTPException(status_code=400, detail=&quot;Invalid JSON data&quot;)<br>    topic_branch = data[&quot;pull_request&quot;][&quot;head&quot;][&quot;ref&quot;]<br>    base_branch = data[&quot;pull_request&quot;][&quot;base&quot;][&quot;ref&quot;]<br>    repo_url = data[&quot;pull_request&quot;][&quot;head&quot;][&quot;repo&quot;][&quot;html_url&quot;]<br>    owner = data[&quot;repository&quot;][&quot;owner&quot;][&quot;login&quot;]<br>    repo = data[&quot;repository&quot;][&quot;name&quot;]<br>    pull_request_id = data[&quot;number&quot;]<br>    access_token = os.environ[&quot;ACCESS_TOKEN&quot;]<br>    diff = get_diff_from_repo_changes(<br>        access_token=access_token,<br>        repo_url=repo_url,<br>        base_branch_name=base_branch,<br>        topic_branch_name=topic_branch,<br>    )<br>    # text_splitter = TokenTextSplitter(chunk_size=2000, chunk_overlap=0)<br>    # chunked_documents = text_splitter.split_documents(<br>    #     documents=[Document(page_content=diff, metadata={&quot;source&quot;: &quot;local&quot;})]<br>    # )<br>    template = (<br>        &quot;You are an expert dev at Google known for expertise in best practices.&quot;<br>        &quot;You have to do/make a code review on a diff file (where issues are detected) on changes done in code.&quot;<br>        &quot; The diff of changes to review is :&quot;<br>        &quot;------------\\n&quot;<br>        &quot;{content}\\n&quot;<br>        &quot;------------\\n&quot;<br>    )<br>    prompt_template = PromptTemplate.from_template(template)<br>    llm = GoogleGemini(version=&quot;gemini-1.0-pro&quot;)<br>    chain = prompt_template | llm<br>    review = chain.invoke({&quot;content&quot;: diff})<br>    API_URL = &quot;&lt;https://api.github.com/repos&gt;&quot;<br>    url = f&quot;{API_URL}/{owner}/{repo}/issues/{pull_request_id}/comments&quot;<br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>        &quot;Accept&quot;: &quot;application/vnd.github+json&quot;,<br>        &quot;X-GitHub-Api-Version&quot;: &quot;2022-11-28&quot;,<br>    }<br>    data = {&quot;body&quot;: review}<br>    response = requests.post(url, headers=headers, json=data)<br>            # Check for successful request<br>    if response.status_code != 201:<br>        raise HTTPException(status_code=response.status_code,message=&quot;Something went wrong&quot;)<br>    else:<br>        return jsonify(status=response.status_code)</pre><p>This function processes incoming requests to review code changes on GitHub pull requests. It extracts necessary details such as branch names and repository URLs from the request data. Using this information, it retrieves the code diff from the repository. The function then generates a review using an AI model based on the extracted diff and posts this review as a comment on the pull request via the GitHub API.</p><p>Let’s deploy our code on Google Cloud Functions, a Serverless service within Google Cloud Platform designed for deploying functions.</p><p>(IMPORTANT) To store the required libraries for our code, we use the following command:</p><pre>pip freeze &gt; requirements.txt</pre><p>The Cloud Function will use this file to install required dependencies.</p><p>In GCP, give your <a href="https://cloud.google.com/compute/docs/access/service-accounts#default_service_account">default service account</a> the <a href="https://cloud.google.com/vertex-ai/docs/general/access-control?hl=fr#aiplatform.user">Vertex AI User Role</a>, it will the the service account used by your deployed function.</p><p>Next, deploy the function using the Cloud Functions CLI:</p><pre>gcloud functions deploy review_github_func \\<br>--region=us-central1 \\<br>--runtime=python311 \\<br>--source=. \\<br>--entry-point=review_github \\<br>--trigger-http</pre><p>Upon deployment, the URL for the function will be generated and accessible.</p><p><strong>Configure Github and test it !</strong></p><p>Let’s configure our webhook to call our server on pull requests events.</p><p>Navigate to your GitHub repository and configure a webhook for your project:</p><ul><li>Go to Settings &gt; Webhooks</li><li>Select the pull request event and add the URL of your Cloud Function</li><li>Click ‘Test’ to verify connectivity</li></ul><p>Start by creating a new branch for your changes and initiating a pull request:</p><pre>git add -A<br>git commit -m &quot;time to test&quot;<br>git checkout -b &lt;branch_name&gt;<br>// some changes<br>git add -A<br>git commit -m &quot;Added changes&quot;</pre><p>Now, create a pull request. Your configured webhook should be triggered and communicate back to GitHub.</p><p>Congratulations! You’ve <a href="https://cloud.google.com/functions/docs/monitoring/logging">successfully</a> developed an application capable of responding to pull requests.</p><h4><strong>Considerations</strong></h4><p>We reached the end of this article but here are some suggestions and thought on what has been done:</p><ul><li><strong>Responsibility</strong> : It is important to remember that although genAI can provide a lot of improvements, a human should always review alongside the machine. A tool always has limitations but it can lighten the burden.</li><li><strong>Scalability</strong>: This code has been done as a Proof of Concept, don’t hesitate to challenge it and provide feedback in comments. Also, it may fail on some edge cases like very large diff, don’t hesitate to try models like Gemini 1.5 Pro for handling larger inputs.</li><li><strong>Security</strong>: Since the Cloud Function URL is publicly accessible, consider implementing request signing or other security measures to restrict access. Also, to enhance security, consider creating a Virtual Private Cloud (<a href="https://cloud.google.com/vpc-service-controls/docs/overview">VPC Service Controls</a>) to isolate your Cloud Function from other resources in your project.</li><li><strong>Extensibility</strong> : While we’re focusing on code review here, imagine deploying this AI bot in your project to help you with different code tasks, like explaining or summarizing code changes. The possibilities are only limited by what you can imagine (and what the model can do ;)).</li><li><strong>Minor Improvements</strong> : For clarity and organization, consider using a dedicated GitHub account specifically for bot activities to differentiate automated actions from personal contributions.</li><li><strong>Other ideas ?</strong> The comment section is open and don&#39;t forget to leave a clap if this article was interesting 👏🏾.</li></ul><h3>Conclusion</h3><p>In conclusion, the fusion of generative AI with DevOps represents a paradigm shift in software development methodologies. By leveraging AI-powered tools for code review and automation, developers can accelerate development cycles, improve code quality, and ultimately deliver more robust and innovative software solutions. As AI technologies continue to advance, their integration into DevOps practices promises to redefine the future of software development, enabling teams to achieve greater efficiency, agility and competitiveness in the digital age.</p><h3>References:</h3><ul><li><a href="https://en.wikipedia.org/wiki/Code_review">Code review - Wikipedia</a></li><li><a href="https://docs.github.com/en/webhooks/about-webhooks">About webhooks - GitHub Docs</a></li><li><a href="https://www.redhat.com/en/topics/automation/what-is-a-webhook">What is a webhook?</a></li><li><a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens">Managing your personal access tokens - GitHub Docs</a></li><li><a href="https://about.gitlab.com/topics/devops/">What is DevOps??</a></li><li><a href="https://www.lucidchart.com/blog/devops-process-flow">Understanding the DevOps Process Flow</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf8c9369bdc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neoxia/implement-a-genai-code-review-bot-with-google-cloud-platform-2cf8c9369bdc">Implement A genAI Code Review Bot with Google Cloud Platform</a> was originally published in <a href="https://medium.com/neoxia">neoxia</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>