Few Shot Prompting with Various AI Models
Simon-Pierre Boucher
2024-09-14

This Python script is designed to generate responses to a few-shot prompt using several large language models (LLMs) via APIs from OpenAI, Anthropic, and Mistral. Here is a breakdown of its key components:

  1. Loading Environment Variables:

    • The load_dotenv() function loads API keys for the different LLM services from a .env file. This helps securely manage sensitive credentials like API keys (OPENAI_API_KEY, ANTHROPIC_API_KEY, MISTRAL_API_KEY).
  2. Function: openai_few_shot_prompt():

    • This function sends a few-shot learning prompt to the OpenAI API to generate a response from a model (e.g., gpt-4).
    • It constructs the prompt by appending example prompts and responses to the user-provided input.
    • API request parameters include model type, temperature, and token limits.
    • If the API call is successful, it returns the model-generated response.
  3. Function: anthropic_few_shot_prompt():

    • Similar to the OpenAI function, this one constructs a few-shot prompt and makes a request to Anthropic's API (e.g., using models like claude-3-5-sonnet).
    • The response is returned after being processed from the JSON data received from the API.
  4. Function: run_mistral():

    • This function makes a request to the Mistral API with the user’s message, model, and configuration settings (e.g., temperature, token limits).
    • It returns the Mistral model’s generated content or an error if the API call fails.
  5. Function: mistral_few_shot_prompt():

    • This function builds a few-shot prompt and calls run_mistral() to generate a response using the Mistral API.
  6. Function: generate_few_shot_prompts_with_all_models():

    • This function loops through several OpenAI, Anthropic, and Mistral models to generate responses to the same prompt using different models.
    • It stores the responses in a dictionary where the keys are the model names and the values are the generated outputs.
    • The function supports multiple models for each service, such as gpt-4, claude-3-opus, and mistral-medium-latest.
  7. Main Program Execution:

    • API keys are fetched from environment variables.
    • A user prompt is provided (e.g., "Describe the impact of climate change on polar bears"), along with examples.
    • Lists of model names for each service are specified.
    • The generate_few_shot_prompts_with_all_models() function is called to generate responses for the prompt from all the models.
    • The results are printed, showing the response and word count for each model.

This script allows users to experiment with different LLMs and compare their responses to a given prompt, facilitating evaluation across various models from different providers.

In [1]:
import os
from dotenv import load_dotenv
import requests
import json

# Charger les variables d'environnement
load_dotenv()
/Users/simon-pierreboucher/Desktop/notebook/venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
  warnings.warn(
Out[1]:
True
In [2]:
def openai_few_shot_prompt(api_key, prompt, examples, model="gpt-4", temperature=0.7, max_tokens=1024, stop=None):
    """
    Generates a response based on a few-shot prompt using the OpenAI API.
    """
    # Build the few-shot prompt
    few_shot_prompt = ""
    for example in examples:
        few_shot_prompt += f"Example prompt: {example['prompt']}\n"
        few_shot_prompt += f"Example response: {example['response']}\n\n"
    few_shot_prompt += f"Prompt: {prompt}\nResponse:"

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    data = {
        "model": model,
        "messages": [
            {"role": "user", "content": few_shot_prompt}
        ],
        "temperature": temperature,
        "max_tokens": max_tokens
    }
    
    if stop:
        data["stop"] = stop

    response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, data=json.dumps(data))

    if response.status_code == 200:
        response_json = response.json()
        generated_response = response_json["choices"][0]["message"]["content"].strip()
        return generated_response
    else:
        return f"Error {response.status_code}: {response.text}"
In [3]:
def anthropic_few_shot_prompt(api_key, prompt, examples, model="claude-3-5-sonnet-20240620", temperature=0.7, max_tokens=1024):
    """
    Generates a response based on a few-shot prompt using the Anthropic API.
    """
    # Build the few-shot prompt
    few_shot_prompt = ""
    for example in examples:
        few_shot_prompt += f"Example prompt: {example['prompt']}\n"
        few_shot_prompt += f"Example response: {example['response']}\n\n"
    few_shot_prompt += f"Prompt: {prompt}\nResponse:"

    url = "https://api.anthropic.com/v1/messages"
    
    headers = {
        "x-api-key": api_key,
        "anthropic-version": "2023-06-01",
        "content-type": "application/json"
    }

    data = {
        "model": model,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "messages": [
            {"role": "user", "content": few_shot_prompt}
        ]
    }

    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code == 200:
        response_json = response.json()
        generated_response = response_json["content"][0]["text"].strip()
        return generated_response
    else:
        return f"Error {response.status_code}: {response.text}"
In [4]:
def run_mistral(api_key, user_message, model="mistral-medium-latest"):
    url = "https://api.mistral.ai/v1/chat/completions"
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    data = {
        "model": model,
        "messages": [
            {"role": "user", "content": user_message}
        ],
        "temperature": 0.7,
        "top_p": 1.0,
        "max_tokens": 1024,
        "stream": False,
        "safe_prompt": False,
        "random_seed": 1337
    }

    response = requests.post(url, headers=headers, data=json.dumps(data))

    if response.status_code == 200:
        response_json = response.json()
        return response_json["choices"][0]["message"]["content"].strip()
    else:
        return f"Error {response.status_code}: {response.text}"

def mistral_few_shot_prompt(api_key, prompt, examples, model="mistral-medium-latest", temperature=0.7, max_tokens=512):
    """
    Generates a response based on a few-shot prompt using the Mistral API.
    """
    # Build the few-shot prompt
    few_shot_prompt = ""
    for example in examples:
        few_shot_prompt += f"Example prompt: {example['prompt']}\n"
        few_shot_prompt += f"Example response: {example['response']}\n\n"
    few_shot_prompt += f"Prompt: {prompt}\nResponse:"

    return run_mistral(api_key, few_shot_prompt, model=model)
In [5]:
def generate_few_shot_prompts_with_all_models(openai_key, anthropic_key, mistral_key, prompt, examples, openai_models, anthropic_models, mistral_models, temperature=0.7, max_tokens=100, stop=None):
    results = {}

    # Générer des réponses avec tous les modèles OpenAI
    for model in openai_models:
        openai_result = openai_few_shot_prompt(openai_key, prompt, examples, model, temperature, max_tokens, stop)
        results[f'openai_{model}'] = openai_result

    # Générer des réponses avec tous les modèles Anthropic
    for model in anthropic_models:
        anthropic_result = anthropic_few_shot_prompt(anthropic_key, prompt, examples, model, temperature, max_tokens)
        results[f'anthropic_{model}'] = anthropic_result

    # Générer des réponses avec tous les modèles Mistral
    for model in mistral_models:
        mistral_result = mistral_few_shot_prompt(mistral_key, prompt, examples, model, temperature, max_tokens)
        results[f'mistral_{model}'] = mistral_result

    return results
In [6]:
if __name__ == "__main__":
    openai_key = os.getenv("OPENAI_API_KEY")
    anthropic_key = os.getenv("ANTHROPIC_API_KEY")
    mistral_key = os.getenv("MISTRAL_API_KEY")
    prompt = "Describe the impact of climate change on polar bears."
    examples = [
        {"prompt": "Describe the impact of climate change on coral reefs.", "response": "Climate change is causing ocean temperatures to rise, leading to coral bleaching and the loss of biodiversity in coral reef ecosystems."},
        {"prompt": "Explain how deforestation affects local climates.", "response": "Deforestation leads to a decrease in transpiration, which can alter local weather patterns and contribute to a hotter, drier climate."}
    ]

    openai_models = ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo", "gpt-4o-mini", "gpt-4o"]
    anthropic_models = ["claude-3-5-sonnet-20240620", "claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307"]
    mistral_models = ["open-mistral-7b", "open-mixtral-8x7b", "open-mixtral-8x22b", "mistral-small-latest", "mistral-medium-latest", "mistral-large-latest"]

    results = generate_few_shot_prompts_with_all_models(openai_key, anthropic_key, mistral_key, prompt, examples, openai_models, anthropic_models, mistral_models)
    
    for model_name, result in results.items():
        word_count = len(result.split())
        print(f"\033[1mResult from {model_name} ({word_count} words):\033[0m\n{result}\n")
Result from openai_gpt-3.5-turbo (87 words):
Climate change is causing a loss of sea ice in the Arctic, which is crucial habitat for polar bears. This loss of sea ice is making it more difficult for polar bears to hunt for their primary prey, seals, leading to malnutrition and a decline in population numbers. Additionally, as the Arctic warms, polar bears are being forced to travel longer distances to find food, putting them at risk of exhaustion and starvation. Overall, climate change is posing a significant threat to the survival of polar bears.

Result from openai_gpt-4 (84 words):
Climate change is causing a rapid loss of sea ice, which is the primary habitat of polar bears. This makes it harder for them to hunt for seals, their main food source, leading to malnutrition and decreased survival rates. Furthermore, the earlier melting of ice in the spring forces them to spend more time on land, where they don't have access to their traditional food sources and must rely on stored fat. Over time, these changes threaten the survival of the polar bear species.

Result from openai_gpt-4-turbo (86 words):
Climate change is significantly impacting polar bears, primarily through the melting of sea ice in their Arctic habitat. As the planet warms, sea ice, which polar bears rely on for hunting seals, their primary food source, is melting earlier in the spring and forming later in the fall. This change forces polar bears to spend more time on land, where food is scarce, leading to reduced body condition and lower survival rates, particularly among cubs. Additionally, the loss of ice reduces their ability to travel and

Result from openai_gpt-4o-mini (90 words):
Climate change is significantly impacting polar bears by causing the loss of sea ice, which is crucial for their hunting and breeding. As Arctic temperatures rise, the ice melts earlier in the spring and forms later in the autumn, reducing the time polar bears have to hunt seals, their primary food source. This decline in ice habitat not only leads to nutritional stress and decreased body condition but also affects the bears' reproductive success. As a result, polar bear populations are declining, and they are increasingly facing challenges in finding

Result from openai_gpt-4o (88 words):
Climate change has a profound impact on polar bears, primarily due to the loss of their sea ice habitat. As global temperatures rise, sea ice in the Arctic melts earlier in the spring and forms later in the autumn, reducing the amount of time polar bears have to hunt for their primary prey, seals. This leads to longer fasting periods, decreased body condition, and lower cub survival rates. Additionally, the shrinking ice forces polar bears to swim longer distances, which can be exhausting and sometimes fatal, particularly for

Result from anthropic_claude-3-5-sonnet-20240620 (72 words):
Climate change is causing Arctic sea ice to melt at an accelerated rate, reducing the habitat available for polar bears to hunt, rest, and breed. This loss of sea ice forces polar bears to spend more time on land, where they struggle to find adequate food sources, leading to malnutrition and declining populations. The warming temperatures also affect the availability of their primary prey, seals, further threatening their survival and reproductive success.

Result from anthropic_claude-3-opus-20240229 (81 words):
Climate change is having a significant impact on polar bears and their Arctic habitat. As global temperatures rise, sea ice is melting earlier in the spring and forming later in the fall, reducing the amount of time polar bears have to hunt for their primary prey, ringed seals. This is leading to:

1. Reduced hunting opportunities: Polar bears rely on sea ice to access their prey. With less sea ice, they have fewer chances to hunt, which can lead to malnutr

Result from anthropic_claude-3-sonnet-20240229 (83 words):
Climate change is having a significant impact on polar bears due to the loss of sea ice in the Arctic regions. Here's how climate change affects polar bears:

1. Sea ice loss: Polar bears rely on sea ice for hunting, breeding, and denning. As the Arctic warms due to climate change, sea ice is melting at an accelerated rate, reducing the area and duration of ice cover. This loss of sea ice habitat makes it harder for polar bears to find and catch

Result from anthropic_claude-3-haiku-20240307 (84 words):
Climate change is having a significant impact on polar bears. As global temperatures rise and Arctic sea ice melts at an accelerating rate, polar bears are facing severe challenges to their survival.

The loss of sea ice is the primary threat to polar bears. Polar bears rely on the sea ice as a platform for hunting their primary prey, seals. As the sea ice retreats farther from land and melts earlier in the season, polar bears are forced to spend more time on land,

Result from mistral_open-mistral-7b (85 words):
Climate change is having a significant impact on polar bears, primarily due to the melting of their Arctic habitats. As sea ice continues to decrease due to rising temperatures, polar bears lose their primary source of food, seals, which rely on the ice for breeding and resting. This food scarcity can lead to malnutrition and starvation among polar bears, causing population declines. Additionally, warmer temperatures can affect polar bear reproduction and survival, making it more difficult for them to adapt to these changing environmental conditions.

Result from mistral_open-mixtral-8x7b (93 words):
Climate change has a significant impact on polar bears, as it leads to a reduction in Arctic sea ice, which is critical habitat for these animals. With less sea ice, polar bears have a harder time hunting for their prey, such as seals, which can result in malnutrition and decreased reproduction rates. Additionally, melting sea ice forces polar bears to swim longer distances, increasing their energy expenditure and further contributing to malnutrition. These factors can lead to a decline in polar bear populations and even threaten the species' survival in the long term.

Result from mistral_open-mixtral-8x22b (93 words):
Climate change is causing sea ice to melt earlier in the year and form later, reducing the overall extent and thickness of the ice. Polar bears rely on sea ice for hunting, resting, and traveling. The loss of sea ice is leading to habitat loss and decreased access to their primary food source, seals. This can result in nutritional stress, reduced survival rates, and lower reproductive rates for polar bears. Additionally, the warming Arctic may lead to increased human-bear interactions as bears spend more time on land, potentially resulting in conflicts with people.

Result from mistral_mistral-small-latest (113 words):
Climate change is causing the Arctic sea ice to melt earlier in the spring and form later in the fall, reducing the amount of time that polar bears have to hunt for seals, their primary food source. This makes it more difficult for polar bears to maintain their energy reserves and can lead to starvation and declines in population numbers. In addition, the loss of sea ice makes it more challenging for polar bears to travel long distances and find mates, further impacting their ability to reproduce and sustain their populations. Climate change also poses risks to the denning sites that pregnant polar bears rely on for giving birth and raising their cubs.

Result from mistral_mistral-medium-latest (98 words):
Climate change is having a significant impact on polar bears and their habitats. Rising temperatures are causing sea ice to melt earlier in the spring and form later in the fall, reducing the amount of time polar bears have to hunt and feed. This can lead to decreased body condition and lower reproductive success. Additionally, as sea ice continues to decline, polar bears are being forced to spend more time on land, where food sources are limited and they may come into conflict with humans. These impacts are expected to continue and potentially worsen as climate change progresses.

Result from mistral_mistral-large-latest (136 words):
Climate change is significantly impacting polar bears, primarily through the loss of their sea ice habitat. As global temperatures rise, Arctic sea ice is melting earlier and forming later each year, reducing the time polar bears have to hunt seals, their primary prey. This decreased hunting opportunity leads to malnutrition, lower body weights, and reduced survival rates, particularly for cubs. Additionally, the melting sea ice forces polar bears to spend more time on land, leading to increased human-bear conflicts and potential habitat competition with other species like grizzly bears. The loss of sea ice also threatens the denning sites that pregnant polar bears need to give birth and nurse their cubs. Overall, climate change is a major threat to polar bear populations, with some studies predicting significant declines in their numbers if current warming trends continue.