Question-Answer with Various AI Models
Simon-Pierre Boucher
2024-09-14

This Python script generates answers to a question using multiple models from OpenAI, Anthropic, and Mistral APIs. Here is a summary of its main components:

1. Environment Setup:

  • load_dotenv(): This function loads environment variables (API keys) from a .env file, allowing secure access to the APIs for OpenAI, Anthropic, and Mistral.

2. Question Answering Functions:

  • openai_question_answer():

    • This function sends a user question (and optional context) to OpenAI's models (e.g., gpt-4) via an API request.
    • The function formats the input as a user message, sends it to OpenAI’s API, and retrieves the generated answer.
    • It supports configurable parameters like temperature, max tokens, and stop sequences.
  • anthropic_question_answer():

    • Similar to the OpenAI function, this sends a question (and context) to Anthropic’s models (e.g., claude-3-5-sonnet) using an API request.
    • The function constructs the request and retrieves the generated response from the Anthropic API.
  • run_mistral():

    • This is a helper function that sends user input to Mistral’s API to retrieve a response.
    • It handles the API request and returns the response generated by the model (e.g., mistral-medium-latest).
  • mistral_question_answer():

    • This function formats the question (and optional context) for Mistral and uses the run_mistral() function to generate an answer.

3. Aggregated Question Answering:

  • answer_question_with_all_models():
    • This function iterates through lists of models for OpenAI, Anthropic, and Mistral, generating answers for a given question and context.
    • The function stores the responses in a dictionary, with the keys being the model names and the values being the generated answers.
    • It loops through multiple models for each API and calls the respective functions to fetch answers.

4. Main Program:

  • API Keys and Question Setup:

    • The API keys are fetched from environment variables.
    • The question posed in this example is: "What are the effects of climate change on polar bears?"
    • A detailed context is provided, explaining how climate change affects polar bears, such as habitat loss and malnutrition due to shrinking ice.
  • Model Lists:

    • Lists of models for OpenAI (gpt-3.5-turbo, gpt-4), Anthropic (claude-3-5-sonnet, claude-3-opus), and Mistral (open-mistral-7b, mistral-medium-latest) are specified.
  • Generating Answers:

    • The function answer_question_with_all_models() is called to generate answers from all models for the given question and context.
  • Results Output:

    • The script prints the results for each model, displaying the model name, word count, and the generated answer.

Purpose:

This script is useful for comparing how different AI models from OpenAI, Anthropic, and Mistral respond to the same question and context. It enables cross-model evaluation, providing a comprehensive way to benchmark different large language models for question-answering tasks.

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_question_answer(api_key, question, context=None, model="gpt-4", temperature=0.7, max_tokens=1024, stop=None):
    """
    Generates an answer to a given question based on provided context using the OpenAI API.
    """
    if context:
        prompt_content = f"Context: {context}\n\nQuestion: {question}"
    else:
        prompt_content = f"Question: {question}"

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

    data = {
        "model": model,
        "messages": [
            {"role": "user", "content": prompt_content}
        ],
        "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_answer = response_json["choices"][0]["message"]["content"].strip()
        return generated_answer
    else:
        return f"Error {response.status_code}: {response.text}"
In [3]:
def anthropic_question_answer(api_key, question, context=None, model="claude-3-5-sonnet-20240620", temperature=0.7, max_tokens=1024):
    """
    Generates an answer to a given question based on provided context using the Anthropic API.
    """
    if context:
        prompt_content = f"Context: {context}\n\nQuestion: {question}"
    else:
        prompt_content = f"Question: {question}"

    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": prompt_content}
        ]
    }

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

    if response.status_code == 200:
        response_json = response.json()
        generated_answer = response_json["content"][0]["text"].strip()
        return generated_answer
    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_question_answer(api_key, question, context=None, model="mistral-medium-latest", temperature=0.7, max_tokens=1024):
    """
    Generates an answer to a given question based on provided context using the Mistral API.
    """
    if context:
        user_message = f"Context: {context}\n\nQuestion: {question}"
    else:
        user_message = f"Question: {question}"
        
    return run_mistral(api_key, user_message, model=model)
In [5]:
def answer_question_with_all_models(openai_key, anthropic_key, mistral_key, question, context, openai_models, anthropic_models, mistral_models, temperature=0.7, max_tokens=100, stop=None):
    results = {}

    # Répondre à des questions avec tous les modèles OpenAI
    for model in openai_models:
        openai_result = openai_question_answer(openai_key, question, context, model, temperature, max_tokens, stop)
        results[f'openai_{model}'] = openai_result

    # Répondre à des questions avec tous les modèles Anthropic
    for model in anthropic_models:
        anthropic_result = anthropic_question_answer(anthropic_key, question, context, model, temperature, max_tokens)
        results[f'anthropic_{model}'] = anthropic_result

    # Répondre à des questions avec tous les modèles Mistral
    for model in mistral_models:
        mistral_result = mistral_question_answer(mistral_key, question, context, 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")
    question = "What are the effects of climate change on polar bears?"
    context = "Polar bears are increasingly threatened by climate change. As the Arctic ice melts, their habitat shrinks, making it difficult for them to hunt seals, their primary food source. This leads to malnutrition and decreased reproduction rates. Conservation efforts are crucial to mitigate these effects and protect polar bear populations."

    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 = answer_question_with_all_models(openai_key, anthropic_key, mistral_key, question, context, 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 (51 words):
The effects of climate change on polar bears include shrinking habitat due to melting Arctic ice, leading to difficulties in hunting seals, their primary food source. This results in malnutrition and decreased reproduction rates among polar bear populations. Conservation efforts are crucial to mitigate these effects and protect these iconic animals.

Result from openai_gpt-4 (33 words):
The effects of climate change on polar bears include shrinking of their habitat due to melting Arctic ice, difficulties in hunting seals which is their primary food source, malnutrition, and decreased reproduction rates.

Result from openai_gpt-4-turbo (89 words):
Climate change has profound effects on polar bears, primarily impacting their habitat and food availability. Here are the key effects:

1. **Loss of Sea Ice Habitat**: Polar bears depend on sea ice as a platform from which to hunt seals. As global temperatures rise, Arctic sea ice melts and forms later in the season, reducing the habitat available for polar bears. This trend forces bears to either swim longer distances or stay on land for extended periods, leading to increased energy expenditure and reduced access to their main food

Result from openai_gpt-4o-mini (72 words):
The effects of climate change on polar bears include:

1. **Habitat Loss**: As Arctic ice melts due to rising temperatures, polar bears lose their natural habitat. This shrinking ice limits their ability to hunt for seals, which are their primary food source.

2. **Hunting Difficulties**: With less ice coverage, polar bears face challenges in accessing hunting grounds, leading to decreased hunting success. This can result in malnutrition and starvation.

3. **Malnutrition**: Inadequate

Result from openai_gpt-4o (83 words):
Climate change has several detrimental effects on polar bears, primarily driven by the melting of Arctic ice, which is crucial to their survival. Here are the key impacts:

1. **Loss of Habitat:** As the Arctic ice melts, polar bears lose the sea ice platforms they rely on for hunting seals, their main food source. The reduction in ice forces them to travel greater distances to find food, which can be energetically costly and less successful.

2. **Malnutrition:** With less access to their primary

Result from anthropic_claude-3-5-sonnet-20240620 (67 words):
Based on the given context, the effects of climate change on polar bears include:

1. Habitat loss: As Arctic ice melts due to rising temperatures, the polar bears' habitat shrinks.

2. Hunting difficulties: The reduction in sea ice makes it harder for polar bears to hunt seals, which are their primary food source.

3. Malnutrition: With decreased access to their main prey, polar bears face malnutrition.

4.

Result from anthropic_claude-3-opus-20240229 (74 words):
Based on the given context, climate change has several detrimental effects on polar bears:

1. Habitat loss: As the Arctic ice melts due to rising temperatures, polar bears are losing their essential habitat. They rely on sea ice for hunting, breeding, and resting.

2. Difficulty in hunting: Polar bears primarily hunt seals, which they catch from the sea ice. With the shrinking ice, it becomes harder for them to find and catch their prey,

Result from anthropic_claude-3-sonnet-20240229 (80 words):
According to the given context, climate change is having several significant effects on polar bear populations:

1. Shrinking habitat: As Arctic ice melts due to rising temperatures, the sea ice habitat that polar bears depend on is shrinking. This loss of habitat makes it increasingly difficult for polar bears to hunt and survive.

2. Difficulty hunting: Polar bears primarily hunt seals from sea ice platforms. With less sea ice available, it becomes harder for them to access their main foo

Result from anthropic_claude-3-haiku-20240307 (77 words):
Based on the provided context, the key effects of climate change on polar bears are:

1. Habitat loss: As the Arctic ice melts due to climate change, the polar bears' habitat is shrinking. This makes it more difficult for them to find and access their primary food source - seals.

2. Decreased hunting success: With the shrinking ice cover, polar bears have a harder time hunting seals, which they rely on for food. This leads to malnut

Result from mistral_open-mistral-7b (274 words):
Climate change has significant impacts on polar bears. The primary effect is the melting of Arctic ice, which serves as their habitat and platform for hunting seals, their primary food source. As the ice melts and shrinks, polar bears face several challenges:

1. Decreased access to food: With less ice, polar bears have a harder time finding and catching seals, leading to malnutrition. This can weaken their immune systems and make them more susceptible to diseases.

2. Impact on reproduction: Malnutrition can also affect polar bears' reproductive health. Females may not be able to produce enough energy to survive through hibernation and successfully raise cubs. As a result, birth rates can decrease, and cub survival rates may also be lower.

3. Disruption of migration patterns: Polar bears rely on sea ice to migrate between their feeding and denning areas. Changes in sea ice conditions can disrupt these migration patterns, making it harder for them to reach essential resources at the right times.

4. Inundation of denning sites: As sea levels rise due to melting ice, coastal areas where polar bears often den can be inundated, leading to loss of valuable denning sites and potential displacement of polar bear populations.

5. Increased competition for resources: Climate change can alter the distribution and abundance of other Arctic species, leading to increased competition for resources between polar bears and other animals.

6. Thermal stress: Warmer temperatures can lead to thermal stress in polar bears, impacting their overall health and survival.

Conservation efforts are essential to mitigate these effects and protect polar bear populations, including reducing greenhouse gas emissions and working to preserve and restore Arctic sea ice.

Result from mistral_open-mixtral-8x7b (298 words):
Climate change has several significant effects on polar bears, primarily through the melting of Arctic ice. Some of these effects include:

1. Habitat loss: As Arctic ice melts due to rising temperatures, the polar bears' habitat shrinks. This makes it harder for them to hunt seals, as they rely on sea ice as a platform to catch their prey.

2. Reduced access to food: With less sea ice available, polar bears have a more challenging time finding and capturing seals, which are their primary source of food. This can lead to malnutrition and decreased body conditions.

3. Decreased reproduction rates: Malnutrition caused by reduced access to food can negatively impact polar bears' reproductive success. Females in poor body condition may not be able to sustain pregnancy or produce healthy offspring.

4. Increased cub mortality: In times of food scarcity, cubs are more vulnerable and have higher mortality rates. Mothers may abandon cubs or fail to provide adequate nutrition, leading to decreased survival rates.

5. Greater energy expenditure: Polar bears may need to travel longer distances to find food or suitable sea ice, increasing their energy expenditure. This further contributes to malnutrition and decreased body conditions.

6. Changes in distribution and abundance: As the Arctic warms, polar bears may shift their distribution towards areas with more stable sea ice. However, this could result in increased competition for resources among polar bear populations and potential conflicts with human settlements.

7. Threats from other species: As the Arctic ice melts, it is possible that other species, such as grizzly bears, could move into polar bear territories, leading to potential competition and conflicts.

Conservation efforts are crucial to mitigate these effects and protect polar bear populations. These efforts can include reducing greenhouse gas emissions, protecting critical habitats, and minimizing human-polar bear interactions.

Result from mistral_open-mixtral-8x22b (308 words):
Climate change has several adverse effects on polar bears:

1. Habitat loss: As Arctic ice melts due to rising temperatures, polar bears lose their natural habitat. Polar bears rely on sea ice for hunting, resting, and breeding. With the reduction in sea ice, their habitat shrinks, forcing them into smaller, fragmented areas.

2. Decreased access to food: Polar bears primarily hunt seals on sea ice. As the ice melts, they have less access to this food source, which leads to malnutrition and starvation.

3. Reduced reproduction rates: Malnutrition and starvation can negatively impact the reproductive health of polar bears. This can lead to lower birth rates, further threatening the survival of their species.

4. Increased competition and conflict: As their habitat shrinks, polar bears may be forced into closer proximity with each other, leading to increased competition for resources and potential conflicts.

5. Longer periods of food scarcity: With climate change, sea ice melts earlier in the year and freezes later, extending the period when polar bears may not have access to their primary food source. This can lead to prolonged fasting and increased stress on their bodies.

6. Risk of drowning: Polar bears are strong swimmers but require sea ice as resting platforms between swims. As the distance between ice floes increases, polar bears may become exhausted and drown during long swims.

7. Exposure to diseases and parasites: With climate change, new diseases and parasites may emerge in the Arctic, posing additional threats to polar bear populations.

8. Human-polar bear conflicts: As polar bears are forced into closer contact with human settlements, the risk of conflicts increases, potentially leading to the death or relocation of polar bears.

Conservation efforts are essential to mitigate these effects and protect polar bear populations. This may include habitat protection, reducing greenhouse gas emissions, and implementing policies that minimize human-polar bear conflicts.

Result from mistral_mistral-small-latest (102 words):
Climate change has several adverse effects on polar bears. Primarily, the melting of Arctic ice reduces their habitat, making it harder for them to hunt seals, which are their main food source. This forces them to swim longer distances in search of food, leading to exhaustion and malnutrition. Additionally, decreased access to seals negatively impacts their reproduction rates, as pregnant females require a high-fat diet to sustain their pregnancy and nourish their cubs. Furthermore, the warming of Arctic temperatures can also affect denning sites, potentially leading to the death of cubs. Overall, climate change poses a significant threat to polar bear populations.

Result from mistral_mistral-medium-latest (379 words):
The effects of climate change on polar bears are severe and can be observed in several ways:

1. Habitat loss: The primary effect of climate change on polar bears is the melting of Arctic sea ice, which constitutes their primary habitat. Polar bears use sea ice as a platform to hunt seals, rest, and travel. As the ice melts earlier in the spring and forms later in the fall, the bears have less time to hunt and build up their fat reserves, causing them to spend more time on land where food sources are scarce.

2. Reduced food availability: With the loss of sea ice, polar bears have reduced access to their primary food source, seals. This leads to malnutrition and starvation, particularly among cubs and pregnant females who require more energy.

3. Decreased reproduction rates: Malnutrition resulting from reduced food availability can lead to lower reproductive success. Female polar bears need to reach a certain weight to ovulate and sustain pregnancy. Insufficient food can cause delays in reproduction or even complete reproductive failure.

4. Increased mortality: Climate change-related factors such as habitat loss, reduced food availability, and decreased reproduction contribute to increased mortality among polar bears. Starvation, drowning due to longer swims between ice floes, and conflicts with humans are all potential causes of death linked to climate change.

5. Changes in distribution and behavior: As sea ice disappears, polar bears may be forced to move to new areas in search of food and suitable habitat. This can result in increased human-polar bear interactions, potentially leading to conflicts and negative outcomes for both bears and people. Additionally, changes in behavior, such as feeding on alternative food sources like bird eggs or garbage, can put polar bears at risk and negatively impact their health.

6. Potential for disease and parasites: Changes in habitat and food sources can increase the risk of disease and parasite transmission among polar bears. Warmer temperatures may also facilitate the spread of pathogens and parasites, further threatening polar bear populations.

In summary, climate change poses significant threats to polar bears through habitat loss, reduced food availability, decreased reproduction rates, increased mortality, changes in distribution and behavior, and potential for disease and parasites. Conservation efforts are crucial to mitigate these effects and protect polar bear populations.

Result from mistral_mistral-large-latest (321 words):
Climate change has several significant effects on polar bears, including:

1. **Habitat Loss**: Polar bears rely on sea ice for hunting, resting, and breeding. As global temperatures rise due to climate change, the Arctic sea ice is melting earlier in the spring and forming later in the fall, reducing the time polar bears have to hunt and build up their fat reserves.

2. **Reduced Access to Prey**: Polar bears primarily feed on seals, which they hunt from the surface of the sea ice. The loss of sea ice makes it more challenging for polar bears to catch their prey, leading to reduced food intake.

3. **Malnutrition and Starvation**: With less time to hunt and reduced access to prey, polar bears are experiencing malnutrition. This can lead to starvation, particularly for younger bears and mothers with cubs.

4. **Decreased Reproduction Rates**: The physical condition of female polar bears greatly influences their reproduction rates. With less food, females are less likely to give birth to healthy cubs, and those that are born may have lower survival rates due to the mother's poor condition.

5. **Increased Swimming Distances**: As sea ice melts and breaks apart, polar bears are forced to swim longer distances, which can be particularly challenging for young bears and can lead to drowning.

6. **Increased Human-Bear Conflicts**: With the loss of sea ice, polar bears are spending more time on land, leading to increased interactions with humans and potential conflicts.

7. **Disease and Parasites**: As temperatures rise, new diseases and parasites may become more prevalent in the Arctic, posing additional threats to polar bears' health.

8. **Potential Hybridization**: In some areas, grizzly bears are moving north as the climate warms, leading to interbreeding with polar bears. While this is a natural process, it could potentially dilute the genetic uniqueness of polar bears over time.

These effects combined make climate change a significant threat to the long-term survival of polar bear populations.