How you can Entry and Use Gemini API for Free – KDnuggets #Imaginations Hub

How you can Entry and Use Gemini API for Free – KDnuggets #Imaginations Hub
Image source - Pexels.com



Picture by Writer
 

Gemini is a brand new mannequin developed by Google, and Bard is changing into usable once more. With Gemini, it’s now doable to get nearly good solutions to your queries by offering them with photographs, audio, and textual content.

On this tutorial, we are going to be taught in regards to the Gemini API and easy methods to set it up in your machine. We can even discover numerous Python API features, together with textual content era and picture understanding.

 

 

Gemini is a brand new AI mannequin developed by collaboration between groups at Google, together with Google Analysis and Google DeepMind. It was constructed particularly to be multimodal, that means it will probably perceive and work with several types of information like textual content, code, audio, photographs, and video.

Gemini is essentially the most superior and largest AI mannequin developed by Google thus far. It has been designed to be extremely versatile in order that it will probably function effectively on a variety of programs, from information facilities to cell gadgets. Because of this it has the potential to revolutionize the way in which wherein companies and builders can construct and scale AI purposes.

Listed below are three variations of the Gemini mannequin designed for various use instances:

  • Gemini Extremely: Largest and most superior AI able to performing advanced duties.
  • Gemini Professional: A balanced mannequin that has good efficiency and scalability.
  • Gemini Nano: Most effective for cell gadgets.

 

How to Access and Use Gemini API for Free
Picture from Introducing Gemini

 

Gemini Extremely has state-of-the-art efficiency, exceeding the efficiency of GPT-4 on a number of metrics. It’s the first mannequin to outperform human consultants on the Large Multitask Language Understanding benchmark, which exams world information and drawback fixing throughout 57 numerous topics. This showcases its superior understanding and problem-solving capabilities.

 

 

To make use of the API, now we have to first get an API key you can can from right here: https://ai.google.dev/tutorials/setup

 
How to Access and Use Gemini API for Free
 

After that click on on “Get an API key” button after which click on on “Create API key in new venture”.

 
How to Access and Use Gemini API for Free
 

Copy the API key and set it as an setting variable. We’re utilizing Deepnote and it’s fairly simple for us to set the important thing with the identify “GEMINI_API_KEY”. Simply go to the combination, scroll down and choose setting variables.

 
How to Access and Use Gemini API for Free
 

Within the subsequent step, we are going to instal the Python API utilizing PIP:

pip set up -q -U google-generativeai

 

After that, we are going to set the API key to Google’s GenAI and provoke the occasion.

import google.generativeai as genai
import os

gemini_api_key = os.environ["GEMINI_API_KEY"]
genai.configure(api_key = gemini_api_key)

 

 

After establishing the API key, utilizing the Gemini Professional mannequin to generate content material is easy. Present a immediate to the `generate_content` operate and show the output as Markdown.

from IPython.show import Markdown

mannequin = genai.GenerativeModel('gemini-pro')
response = mannequin.generate_content("Who's the GOAT within the NBA?")

Markdown(response.textual content)

 

That is wonderful, however I do not agree with the listing. Nonetheless, I perceive that it is all about private choice.

 
How to Access and Use Gemini API for Free
 

Gemini can generate a number of responses, referred to as candidates, for a single immediate. You’ll be able to choose essentially the most appropriate one. In our case, we had just one respons.

 

How to Access and Use Gemini API for Free
 

Let’s ask it to put in writing a easy recreation in Python.

response = mannequin.generate_content("Construct a easy recreation in Python")

Markdown(response.textual content)

 

The result’s easy and to the purpose. Most LLMs begin to clarify the Python code as an alternative of writing it.

 

How to Access and Use Gemini API for Free

 

 

You’ll be able to customise your response utilizing the `generation_config` argument. We’re limiting candidate depend to 1, including the cease phrase “area,” and setting max tokens and temperature.

response = mannequin.generate_content(
    'Write a brief story about aliens.',
    generation_config=genai.sorts.GenerationConfig(
        candidate_count=1,
        stop_sequences=['space'],
        max_output_tokens=200,
        temperature=0.7)
)

Markdown(response.textual content)

 

As you’ll be able to see, the response stopped earlier than the phrase “area”. Wonderful.

 
How to Access and Use Gemini API for Free

 

 

You can too use the `stream` argument to stream the response. It’s just like the Anthropic and OpenAI APIs however quicker.

mannequin = genai.GenerativeModel('gemini-pro')
response = mannequin.generate_content("Write a Julia operate for cleansing the info.", stream=True)

for chunk in response:
    print(chunk.textual content)

 

How to Access and Use Gemini API for Free

 

 

On this part, we are going to load Masood Aslami’s picture and use it to check the multimodality of Gemini Professional Imaginative and prescient.

Load the photographs to the `PIL` and show it.

import PIL.Picture

img = PIL.Picture.open('photographs/photo-1.jpg')

img

 

Now we have a top quality picture of Rua Augusta Arch.

 
How to Access and Use Gemini API for Free
 

Let’s load the Gemini Professional Imaginative and prescient mannequin and supply it with the picture.

mannequin = genai.GenerativeModel('gemini-pro-vision')

response = mannequin.generate_content(img)

Markdown(response.textual content)

 

The mannequin precisely recognized the palace and supplied extra details about its historical past and structure.

 
How to Access and Use Gemini API for Free
 

Let’s present the identical picture to the GPT-4 and ask it in regards to the picture. Each fashions have supplied nearly comparable solutions. However I just like the GPT-4 response extra.

 
How to Access and Use Gemini API for Free
 

We’ll now present textual content and the picture to the API. Now we have requested the imaginative and prescient mannequin to put in writing a journey weblog utilizing the picture as reference.

response = mannequin.generate_content(["Write a travel blog post using the image as reference.", img])

Markdown(response.textual content)

 

It has supplied me with a brief weblog. I used to be anticipating longer format.

 
How to Access and Use Gemini API for Free
 

In comparison with GPT-4, the Gemini Professional Imaginative and prescient mannequin has struggled to generate a long-format weblog.

 
How to Access and Use Gemini API for Free

 

 

We will arrange the mannequin to have a back-and-forth chat session. This fashion, the mannequin remembers the context and response utilizing the earlier conversations.

In our case, now we have began the chat session and requested the mannequin to assist me get began with the Dota 2 recreation.

mannequin = genai.GenerativeModel('gemini-pro')

chat = mannequin.start_chat(historical past=[])

chat.send_message("Are you able to please information me on easy methods to begin taking part in Dota 2?")

chat.historical past

 

As you’ll be able to see, the `chat` object is saving the historical past of the consumer and mode chat.

 
How to Access and Use Gemini API for Free
 
We will additionally show them in a Markdown type.

for message in chat.historical past:
    show(Markdown(f'**message.position**: message.components[0].textual content'))

 

How to Access and Use Gemini API for Free
 

Let’s ask the observe up query.

chat.send_message("Which Dota 2 heroes ought to I begin with?")

for message in chat.historical past:
    show(Markdown(f'**message.position**: message.components[0].textual content'))

 

We will scroll down and see your entire session with the mannequin.

 
How to Access and Use Gemini API for Free

 

 

Embedding fashions have gotten more and more well-liked for context-aware purposes. The Gemini embedding-001 mannequin permits phrases, sentences, or total paperwork to be represented as dense vectors that encode semantic that means. This vector illustration makes it doable to simply examine the similarity between totally different items of textual content by evaluating their corresponding embedding vectors.

We will present the content material to `embed_content` and convert the textual content into embeddings. It’s that straightforward.

output = genai.embed_content(
    mannequin="fashions/embedding-001",
    content material="Are you able to please information me on easy methods to begin taking part in Dota 2?",
    task_type="retrieval_document",
    title="Embedding of Dota 2 query")

print(output['embedding'][0:10])

 

[0.060604308, -0.023885584, -0.007826327, -0.070592545, 0.021225851, 0.043229062, 0.06876691, 0.049298503, 0.039964676, 0.08291664]

 

We will convert a number of chunks of textual content into embeddings by passing an inventory of strings to the ‘content material’ argument.

output = genai.embed_content(
    mannequin="fashions/embedding-001",
    content material=[
        "Can you please guide me on how to start playing Dota 2?",
        "Which Dota 2 heroes should I start with?",
    ],
    task_type="retrieval_document",
    title="Embedding of Dota 2 query")

for emb in output['embedding']:
    print(emb[:10])

 

[0.060604308, -0.023885584, -0.007826327, -0.070592545, 0.021225851, 0.043229062, 0.06876691, 0.049298503, 0.039964676, 0.08291664]

[0.04775657, -0.044990525, -0.014886052, -0.08473655, 0.04060122, 0.035374347, 0.031866882, 0.071754575, 0.042207796, 0.04577447]

 

For those who’re having hassle reproducing the identical consequence, try my Deepnote workspace.

 

 

There are such a lot of superior features that we did not cowl on this introductory tutorial. You’ll be able to be taught extra in regards to the Gemini API by going to the Gemini API: Quickstart with Python.

On this tutorial, now we have realized about Gemini and easy methods to entry the Python API to generate responses. Particularly, now we have realized about textual content era, visible understanding, streaming, dialog historical past, customized output, and embeddings. Nonetheless, this simply scratches the floor of what Gemini can do.

Be happy to share with me what you have got constructed utilizing the free Gemini API. The chances are limitless.

 
 

Abid Ali Awan (@1abidaliawan) is an authorized information scientist skilled who loves constructing machine studying fashions. Presently, he’s specializing in content material creation and writing technical blogs on machine studying and information science applied sciences. Abid holds a Grasp’s diploma in Know-how Administration and a bachelor’s diploma in Telecommunication Engineering. His imaginative and prescient is to construct an AI product utilizing a graph neural community for college kids battling psychological sickness.


Related articles

You may also be interested in