How to use AutoGen on Google Colab for Free with Gemini Pro API Key

In this tutorial we show you how to use Autogen on Google Colab using the Google Gemini Pro 1.5 API key.

Requirements for this tutorial:

These are all free to use. Even the Google Gemini API key is free until May 02 but will still work after for a pay per use fee structure.

Here are videos explaining how to set this up as well as the basic instructions and code below.

Get a Free Google Gemini 1.5 API key

How to use Autogen on Google Colab

Get the Google Gemini key

Go to Google Colab and follow the above videos and instructions below.

Or, you can get all the code directly on a shared Google Colab notebook

You can use this and save it for yourself. Remember to only share with trusted people if you make a new Google Colab notebook based on this if you are storing your API key. Because this will give anyone access to it if you don’t.

Then make three cells in Google Colab with the following commands. Once you have each of these cells you can play them and run the script to use AutoGen

Cell 1 – This installs Autogen from Github on Google Colab. You can change the version number also on this but it may break the script and cause errors. In this example I forced AutoGen version 0.2.25 because the latest one broke the below script. But it could easily be fixed if you use ChatGPT and tell them the errors.

!pip install git+https://github.com/microsoft/autogen.git@v0.2.25

Cell 2 – This just imports the Gemini API key that you stored.


import os

api_key = os.environ.get("GEMINI_API_KEY")

Cell 3 – This script below allows you to run Autogen. It is currently set to have a max number of replies of the agent of 5. Also, you can change the input message and press the play button on the script. You can see the actual agents talking to each other below when you run the script.

import os
import autogen
from autogen import AssistantAgent, UserProxyAgent
from autogen.code_utils import  infer_lang
from google.colab import userdata

# Retrieve your API key securely stored as a secret
api_key= userdata.get('GEMINI_API_KEY')

if not api_key:
  raise ValueError(f"KEY: '{api_key}' is invalid")

MAX_USER_REPLIES=5
INPUT_START_MESSAGE = """
write an article about why ai growth guys is the best website for learning AI and internet marketing.  Write the article once as your first personality, and then use your other personalities
to make improvements.  In the end, give me the finished article that I can post on my website.  Make sure this article is at least 1500 words long.  If it is shorter, re write it until you succeed.
we are running this on google colab also so please don't use any localhost or try to install things that are impossible on this environment.
}
"""

# Define your model configuration
config_list_gemini = [
    {
        "model": "gemini-1.5-pro-latest",
        "api_key": api_key,
        "api_type": "google"
    }
]


# Initialize the assistant agent with the Gemini model configuration
assistant = AssistantAgent(
    name="assistant",
    llm_config={
        "cache_seed": 41,
        "config_list": config_list_gemini,
        "seed": 42
    },
)

# Initialize the user proxy agent
try:
  user_proxy = UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=MAX_USER_REPLIES,
    is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
    code_execution_config={
        "work_dir": "coding",
        "use_docker": False
    },
  )
except Exception as e:
  print(f"The following error happened: {str(e)}")
  exit()


# Start the chat between the user proxy and the assistant agent
chat_response = user_proxy.initiate_chat(
    assistant,
    message=INPUT_START_MESSAGE,
    # summary_method="reflection_with_llm",
)

chat_id = chat_response.chat_id
convs = chat_response.chat_history
total_cost = chat_response.cost[1]

print(f"CHAT REF: {chat_id}")
print(f"COST OF TRANSACTION: {total_cost}")

for conv in convs:
  content = conv['content']
  active_role = conv['role']

  print(f"{active_role}: {content}")


print("COMPLETE")
Author Andrew Best

FREE AI COURSES AND UDEMY DISCOUNTS

Get free courses on AI, Email Marketing, Growth, and Monetization strategies to grow your business and improve Your AI skills.

JOIN US

Related