DEV Community

Cover image for Build Your Own AI API With Google Gemini and Air Pipe
Kav Pather for Air Pipe

Posted on • Originally published at blog.airpipe.io on

Build Your Own AI API With Google Gemini and Air Pipe

Artificial Intelligence is at the forefront of innovation, and with Google Gemini AI, developers can unlock advanced capabilities for their applications. However, creating a custom API to tap into Geminis full power can seem complex without the right tools.

Thats where Air Pipe comes in. Air Pipe is a fast, scalable, and secure API platform that simplifies the process of building, deploying, and managing APIs. In this guide, well show you how to leverage Google Gemini AIs API and Air Pipe to create your own AI-powered API in just a few easy steps.

Whether you're looking to automate tasks, enhance your app with AI, or streamline data processing, this tutorial will walk you through generating a Google Gemini API key and configuring a simple yet powerful API using Air Pipe. By the end, you'll have a fully functioning API ready to deployallowing you to integrate cutting-edge AI with ease.

Lets dive in and build something amazing with Google Gemini and Air Pipe!

Step-by-Step Guide to Build Your Own AI API

This tutorial will focus on the cloud platform deployment but will also work seamlessly for self hosted deployments, you can learn how to self host here https://docs.airpipe.io/docs/tutorial/setup .

Prerequisites:

Step 0: Get your Google Gemini API Key

Navigate to https://aistudio.google.com/app/apikey and select Create API Key.

Get Gemini API Key

Create a new project if you have not already.

Create New Google Project

For production deployments we understand your API keys are sensitive, we provide encrypted variable (secret) support https://docs.airpipe.io/docs/configuration/managed-variables .

The examples below will utilize this system storing the key as gemini-key which is then accessed with a|ap_var::gemini-key| .

Other secret stores are also supported.

Gemini API Key

Step 1: Create your Configuration

Once signed in to your Air Pipe account, head to Configurations > Add New.

Add Configuration

Step 2: Create a HTTP POST interface

In the YAML editor paste the below example. Here we simply define a HTTP POST interface and route called gemini/query. We further define our first action to check the body of the payload for a text attribute to exist and assert that it must be less than 20 characters (this is a simple example for illustrative purposes).

Assertions are important to understand as we can control what the user is allowed to input, and then we can further control the outcome of the API and action with the configured tests .

name: AskGemini

interfaces:
  gemini/query: # http route will be defaulted to this interface name
    method: POST
    input: a|body
    output: http

    actions:
      - name: CheckBody
        input: a|body # access the post body as the input to assert
        assert:
          tests:
            - value: text
              is_not_null: true
              is_less_than: 20 # limit the amount of characters

Enter fullscreen mode Exit fullscreen mode

Step 3: Retrieving the full Gemini Response

Lets extend the configuration and pass the text attribute to the Google Gemini API, we do this using a|CheckBody::text| in our configuration. We will also use workflow control, to ensure the CheckBody action succeeds before querying Google Gemini AI with run_when_succeeded.

We are using Action Variables to dynamically substitute the value into the payload, see our docs on variable substitutions for further details and options.

💡 Important! In the URL field below we are using a|ap_var::gemini-key| this implies we have a variable stored on the Air Pipe platform named gemini-key to access. See Managed Variables if youd like to do the same. Otherwise update this with your key or use your own secret store or environment variable if self hosting.

name: AskGemini

interfaces:
  gemini/query:
    method: POST
    input: a|body
    output: http

    actions:
      - name: CheckBody
        input: a|body
        assert:
          tests:
            - value: text
              is_not_null: true
              is_less_than: 20 # limit the amount of characters

      - name: QueryGemini
        run_when_succeeded: [previous] # only run after CheckBody succeeds
        http: 
          url: https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=a|ap_var::gemini-key|
          method: POST
          headers:
            content-type: application/json
          body: | # substitute the 'text' we just validated in 'CheckBody' into the body payload
            {"contents":[{"parts":[{"text":"a|CheckBody::text|"}]}]}

Enter fullscreen mode Exit fullscreen mode

Step 4: Deploy and Test

  • Set your permission as USER_WITH_PUBLIC_READ

  • Select Deploy to Staging and Deploy to Production and hit create.

Use your favorite API testing tool, or do a curl to your endpoints, lets try the gemini/query route, make sure you update your organization uuid in the route.

You can find your organization uuid under Configurations or in your Organization Settings.

  • Send a HTTP POST with a JSON payload eg. {"text": "tell me about dogs"} to gemini/query to retrieve the response.

  • Send a HTTP POST with a JSON payload eg. {"text": "tell me about really big dogs"} to test the length condition triggering a failure and preventing the QueryGemini action from proceeded.

https://api.airpipe.io/YOUR-ORGANIZATION-UUID/production/gemini/query

curl --location 'https://api.airpipe.io/YOUR-ORGANIZATION-UUID/production/gemini/query' \
--header 'Content-Type: application/json' \
--data '{
    "text": "tell me about dogs"
}'
Enter fullscreen mode Exit fullscreen mode

Example response:

{
    "data": {
        "CheckBody": {
            "time.ms": 0,
            "data": {
                "text": "tell me about dogs"
            },
            "message": "success"
        },
        "QueryGemini": {
            "time.ms": 4180,
            "data": {
                "status": 200,
                "headers": {
                    "content-type": "application/json; charset=UTF-8",
                    "vary": "Origin,Accept-Encoding",
                    "date": "Sun, 29 Sep 2024 15:40:42 GMT",
                    "server": "scaffolding on HTTPServer2",
                    "cache-control": "private",
                    "x-xss-protection": "0",
                    "x-frame-options": "SAMEORIGIN",
                    "x-content-type-options": "nosniff",
                    "server-timing": "gfet4t7; dur=4016",
                    "alt-svc": "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000",
                    "accept-ranges": "none"
                },
                "body": {
                    "candidates": [
                        {
                            "content": {
                                "parts": [
                                    {
                                        "text": "## Dogs: Man's Best Friend, and More!\n\nDogs, those furry, wagging companions, have been by our side for thousands of years. They're more than just pets; they're loyal friends, helpful assistants, and sometimes even family members. Let's delve into what makes dogs so special:\n\n**Origins and History:**\n\n* **Wolf Ancestry:** Domestic dogs are descended from wolves, with the earliest evidence of domestication dating back 15,000 years.\n* **Evolution:** Over time, dogs evolved to work alongside humans in various roles like hunting, herding, and guarding. This led to the development of different breeds, each with unique physical and behavioral characteristics.\n\n**Breed Diversity:**\n\n* **Over 300 Breeds:** The world boasts a fascinating variety of dog breeds, each with a distinct appearance, temperament, and purpose.\n* **Classifications:** Breeds are categorized based on their size, coat type, and intended roles, like working, herding, sporting, and companion dogs. \n* **Unique Traits:** From tiny Chihuahuas to massive Great Danes, each breed has its own personality and quirks.\n\n**Personality and Behavior:**\n\n* **Social Creatures:** Dogs are highly social animals, forming strong bonds with their human families.\n* **Intelligence and Trainability:** Many dogs are incredibly intelligent and capable of learning complex commands and tricks. \n* **Emotionally Expressive:** Dogs communicate their emotions through body language, vocalizations, and facial expressions.\n* **Individual Differences:**  While certain breeds tend to have specific temperament traits, each dog is an individual with their own unique personality.\n\n**Health and Care:**\n\n* **Lifespan:** Depending on the breed, dogs can live anywhere from 10 to 20 years.\n* **Nutrition and Exercise:** Dogs require a balanced diet and regular exercise to stay healthy and happy.\n* **Grooming:** Different breeds have different grooming needs, ranging from occasional brushing to daily baths.\n* **Veterinary Care:** Regular checkups, vaccinations, and preventative measures are crucial for maintaining good health.\n\n**Beyond Companionship:**\n\n* **Working Dogs:** Dogs play vital roles in various professions, including law enforcement, search and rescue, assistance for individuals with disabilities, and therapy work.\n* **Emotional Support:** Dogs provide emotional support, reduce stress, and improve mental well-being.\n* **Family Members:** For many families, dogs become cherished members, offering unconditional love, companionship, and joy.\n\n**Getting a Dog:**\n\n* **Research:** Before getting a dog, consider your lifestyle, living situation, and the breed's temperament and care requirements.\n* **Adopting:** Consider adopting a dog from a shelter or rescue organization, giving a loving home to a dog in need.\n* **Responsible Ownership:** Be prepared to provide a dog with a safe, loving environment, proper care, and training.\n\nDogs enrich our lives in countless ways. They offer companionship, loyalty, and unconditional love, making them truly deserving of their title: \"Man's Best Friend.\" \n"
                                    }
                                ],
                                "role": "model"
                            },
                            "finishReason": "STOP",
                            "index": 0,
                            "safetyRatings": [
                                {
                                    "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
                                    "probability": "NEGLIGIBLE"
                                },
                                {
                                    "category": "HARM_CATEGORY_HATE_SPEECH",
                                    "probability": "NEGLIGIBLE"
                                },
                                {
                                    "category": "HARM_CATEGORY_HARASSMENT",
                                    "probability": "NEGLIGIBLE"
                                },
                                {
                                    "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
                                    "probability": "NEGLIGIBLE"
                                }
                            ]
                        }
                    ],
                    "usageMetadata": {
                        "promptTokenCount": 4,
                        "candidatesTokenCount": 642,
                        "totalTokenCount": 646
                    }
                }
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 5: Clean up the Gemini Response

As you can see with the response returned above, Google Gemini returns a lot of additional data you do not need to expose to your end users. We can use post_transforms with extract_value to target the text attribute to return.

Go to Configurations and find your AskGemini configuration and click update, and paste the below.

View Transforms & Functions for further ways to manipulate your data.

name: AskGemini

interfaces:
  gemini/query:
    method: POST
    input: a|body
    output: http

    actions:
      - name: CheckBody
        input: a|body
        assert:
          tests:
            - value: text
              is_not_null: true
              is_less_than: 20 # limit the amount of characters

      - name: QueryGemini
        run_when_succeeded: [previous] # only run after CheckBody succeeds
        http: 
          url: https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=a|ap_var::gemini-key|
          method: POST
          headers:
            content-type: application/json
          body: | # substitute the 'text' we just validated in 'CheckBody' into the body payload
            {"contents":[{"parts":[{"text":"a|CheckBody::text|"}]}]} 
        post_transforms:
          - extract_value: ".body.candidates[0].content.parts[0].text"

Enter fullscreen mode Exit fullscreen mode

Example response:

    {
        "data": {
            "CheckBody": {
                "time.ms": 0,
                "data": {
                    "text": "tell me about dogs"
                },
                "message": "success"
            },
            "QueryGemini": {
                "time.ms": 4111,
                "data": "## Dogs: The Best Friends of Humans\n\nDogs, also known as **Canis lupus familiaris**, are domesticated mammals that have been companions to humans for thousands of years. Their loyalty, intelligence, and playful nature have made them beloved pets worldwide.\n\n**Here's a breakdown of some key aspects of dogs:**\n\n**Physical Characteristics:**\n\n* **Size:** Dogs come in a wide range of sizes, from tiny Chihuahuas to massive Great Danes.\n* **Coat:** Dog coats vary in length, texture, and color. Some have short, smooth coats, while others have long, fluffy fur.\n* **Tail:** Most dogs have tails that wag when they are happy. Tail length and shape can vary depending on the breed.\n* **Ears:** Dog ears come in various shapes and sizes, from floppy to erect.\n* **Snout:** Dogs have a strong sense of smell, which is aided by their long, pointed snouts.\n\n**Behavior:**\n\n* **Intelligence:** Dogs are highly intelligent animals, capable of learning complex commands and tasks.\n* **Socialization:** Dogs are social animals that thrive on interaction with humans and other dogs.\n* **Loyalty:** Dogs are known for their loyalty and devotion to their owners.\n* **Playfulness:** Dogs are playful animals that enjoy games and activities.\n* **Training:** Dogs are highly trainable, and with proper training, they can learn a wide range of behaviors.\n\n**Breeds:**\n\nThere are over 300 recognized dog breeds, each with its own unique physical characteristics and temperament. Some popular breeds include:\n\n* **Golden Retriever:** Friendly, intelligent, and eager to please.\n* **Labrador Retriever:** Loyal, playful, and known for their love of water.\n* **German Shepherd:** Intelligent, loyal, and protective.\n* **Poodle:** Intelligent, hypoallergenic, and known for their curly coats.\n* **French Bulldog:** Affectionate, playful, and known for their bat ears.\n\n**Health:**\n\n* **Lifespan:** The average lifespan of a dog is 10-13 years, but some breeds can live longer.\n* **Diet:** Dogs need a balanced diet that is rich in protein, carbohydrates, and essential nutrients.\n* **Exercise:** Most dogs need regular exercise to stay healthy and happy.\n* **Veterinary care:** Regular veterinary checkups and vaccinations are essential for maintaining a dog's health.\n\n**Benefits of Owning a Dog:**\n\n* **Companionship:** Dogs provide companionship and unconditional love.\n* **Stress relief:** Owning a dog can help reduce stress and anxiety.\n* **Exercise and activity:** Dogs encourage their owners to be more active.\n* **Improved mental health:** Studies have shown that owning a dog can improve mental health.\n* **Protection:** Some breeds are known for their protective instincts.\n\n**Conclusion:**\n\nDogs are wonderful companions that offer many benefits to their owners. Whether you're looking for a loyal friend, a playful companion, or a furry family member, there's a dog breed out there for everyone."
            }
        }
    }

Enter fullscreen mode Exit fullscreen mode

Step 6: Restricting and manipulating the text prompt

As youve seen before we can restrict the input text with certain conditions. However we may also want to restrict what we are requesting from Google Gemini AI, or want it to behave or respond in a particular way.

In our example lets say we want a maximum of 100 characters returned only.

We can simply modify the body we are sending to Google Gemini AI to prefix the text with some additional text eg. Your response to the following question should be less than 100 characters: a|CheckBody::text| .

 {"contents":[{"parts":[{"text":"Your response to the following question should be less than 100 characters: a|CheckBody::text|"}]}]}
Enter fullscreen mode Exit fullscreen mode

Complete example:

name: AskGemini

interfaces:
  gemini/query:
    method: POST
    input: a|body
    output: http

    actions:
      - name: CheckBody
        input: a|body
        assert:
          tests:
            - value: text
              is_not_null: true
              is_less_than: 20 # limit the amount of input characters

      - name: QueryGemini
        run_when_succeeded: [previous] # only run after CheckBody succeeds
        http: # store your gemini key in the hosted variables or substitute a|ap_var::gemini-key| with your key if testing # https://aistudio.google.com/app/apikey
          url: https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=a|ap_var::gemini-key|
          method: POST
          headers:
            content-type: application/json
          body: | # substitute the 'text' we just validated in 'CheckBody' into the body payload
            {"contents":[{"parts":[{"text":"Your response to the following question should be less than 100 characters: a|CheckBody::text|"}]}]} 
        post_transforms:
          - extract_value: ".body.candidates[0].content.parts[0].text"

Enter fullscreen mode Exit fullscreen mode

Example response:

    {
        "data": {
            "CheckBody": {
                "time.ms": 0,
                "data": {
                    "text": "tell me about dogs"
                },
                "message": "success"
            },
            "QueryGemini": {
                "time.ms": 1907,
                "data": "Dogs are loyal, furry companions known for their intelligence and love. 🐶 \n"
            }
        }
    }

Enter fullscreen mode Exit fullscreen mode

Now you finally have a nice clean response from Google Gemini AI for your end users to consume. We have securely stored the API key, validated the input text, cleaned the data and effectively sandboxed the output response.

So with that youre done! Whats Next?

Air Pipe provides you a fast, consistent and robust development experience that you can continue extending with confidence across anything you build.

You can further extend your configuration to connect to databases and other endpoints all in the one configuration with workflow controls at your disposal.

See:

Performance and Reliability Built on Rust

One of the core strengths of Air Pipe is that it is built on Rust , known for its memory safety , thread safety , and high performance. Whether you're managing large-scale databases or smaller applications, Rust ensures your APIs run smoothly and securely.

Why Google Gemini?

Google Gemini AI is a powerful platform for advanced natural language processing and machine learning, ideal for building intelligent, scalable applications. Its real-time capabilities and seamless integration make it a top choice for AI-driven services.

Conclusion

integrating Google Gemini AI with Air Pipe allows developers to build powerful, scalable APIs with ease. By combining Gemini's advanced AI capabilities with Air Pipe's speed, security, and simple deployment, you can create intelligent applications that handle complex tasks efficiently.

Whether you're automating workflows or enhancing data analysis, this seamless integration empowers you to innovate faster. Start building your API today and unlock new possibilities with Air Pipe and Google Gemini AI.

Ready to get started? Head over to Air Pipe and build your first Gemini API in minutes.

💡Visit Air Pipe

💡Find us on Discord

💡Google Gemini AI Examples

💡https://ai.google.dev/api/all-methods

Top comments (0)