Text Generation with Various AI Models
Simon-Pierre Boucher
2024-09-14

This Python script generates text using multiple language models from OpenAI, Anthropic, and Mistral. Here's a breakdown of its components:

1. Environment Setup:

  • load_dotenv(): This loads environment variables (API keys) from a .env file, which securely stores sensitive data like API keys for OpenAI, Anthropic, and Mistral.

2. Text Generation Functions:

  • openai_generate_text():

    • This function sends a prompt to OpenAI's models (e.g., gpt-4).
    • The function uses HTTP POST to communicate with OpenAI’s API, passing the prompt and other parameters like temperature, max tokens, and stop sequences.
    • It returns the generated response or an error message if the request fails.
  • anthropic_generate_text():

    • Similar to OpenAI, this function sends a prompt to Anthropic's models (e.g., claude-3-5-sonnet).
    • It also handles HTTP POST requests and returns the generated text from the Anthropic API or an error message if it fails.
  • run_mistral():

    • This function sends a prompt to Mistral’s API (e.g., mistral-medium-latest) and retrieves the generated response.
    • It includes configurable parameters like temperature, max tokens, and others, and processes the response returned from the Mistral API.
  • mistral_generate_text():

    • This function builds the prompt specifically for Mistral and calls run_mistral() to generate a response.

3. Aggregated Text Generation:

  • generate_text_with_all_models():
    • This function takes a prompt and loops through a list of OpenAI, Anthropic, and Mistral models to generate responses from each one.
    • It stores the generated results from each model in a dictionary, keyed by the model name.
    • The responses are generated using the three different APIs (OpenAI, Anthropic, Mistral) by calling the respective functions.

4. Main Program:

  • API Keys and Prompt Setup:

    • API keys for OpenAI, Anthropic, and Mistral are loaded from environment variables.
    • The user prompt in this case is to "Create a simple, healthy recipe using chicken breast, spinach, and quinoa."
  • Model Lists:

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

    • The function generate_text_with_all_models() is called to generate responses from all models for the given prompt.
  • Results Output:

    • The results are printed for each model, showing the model name, word count, and the generated text.

Purpose:

This script is used to compare outputs from different AI models for a single prompt, allowing the user to evaluate how different models from OpenAI, Anthropic, and Mistral respond to the same input. It helps in cross-model evaluation and benchmarking.

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]:
# Fonction pour générer du texte avec OpenAI
def openai_generate_text(api_key, prompt, model, temperature=0.7, max_tokens=1024, stop=None):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    data = {
        "model": model,
        "messages": [
            {"role": "user", "content": 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_text = response_json["choices"][0]["message"]["content"].strip()
        return generated_text
    else:
        return f"Error {response.status_code}: {response.text}"
In [3]:
# Fonction pour générer du texte avec Anthropic
def anthropic_generate_text(api_key, prompt, model="claude-3-5-sonnet-20240620", max_tokens=1024, temperature=0.7):
    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}
        ]
    }

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

    if response.status_code == 200:
        response_json = response.json()
        generated_text = response_json["content"][0]["text"].strip()
        return generated_text
    else:
        return f"Error {response.status_code}: {response.text}"
In [4]:
# Fonction pour générer du texte avec Mistral
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_generate_text(api_key, prompt, model="mistral-medium-latest"):
    user_message = f"Generate text based on the following prompt:\n\n{prompt}"
    return run_mistral(api_key, user_message, model=model)
In [5]:
def generate_text_with_all_models(openai_key, anthropic_key, mistral_key, prompt, openai_models, anthropic_models, mistral_models, temperature=0.7, max_tokens=100, stop=None):
    results = {}

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

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

    # Générer du texte avec tous les modèles Mistral
    for model in mistral_models:
        mistral_result = mistral_generate_text(mistral_key, prompt, model)
        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 = "Create a simple, healthy recipe using the following ingredients: chicken breast, spinach, and quinoa."

    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_text_with_all_models(openai_key, anthropic_key, mistral_key, prompt, 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 (72 words):
Chicken, Spinach, and Quinoa Bowl

Ingredients:
- 1 chicken breast
- 1 cup quinoa
- 2 cups fresh spinach
- Salt and pepper to taste
- Olive oil

Instructions:
1. Cook the quinoa according to package instructions.
2. Season the chicken breast with salt and pepper.
3. In a large skillet, heat olive oil over medium heat. Add the chicken breast and cook for 6-8 minutes on each side, or until fully

Result from openai_gpt-4 (70 words):
Recipe: Spinach and Quinoa Stuffed Chicken Breast

Ingredients:

- 2 boneless, skinless chicken breasts
- 1 cup of cooked quinoa
- 2 cups of fresh spinach
- 2 cloves of garlic, minced
- 1 tablespoon of olive oil
- Salt and pepper to taste

Instructions:

1. Preheat your oven to 375 degrees Fahrenheit (190 degrees Celsius).

2. While the oven is heating, heat the olive oil in a skillet over

Result from openai_gpt-4-turbo (68 words):
Certainly! Here's a simple and healthy recipe using chicken breast, spinach, and quinoa:

### Ingredients:
- 2 chicken breasts (boneless and skinless)
- 1 cup quinoa
- 2 cups fresh spinach leaves
- 2 cloves garlic, minced
- 1 lemon (juice and zest)
- 2 tablespoons olive oil
- Salt and pepper, to taste
- Optional: fresh herbs (like parsley or basil), cherry tomatoes, or a pinch of

Result from openai_gpt-4o-mini (72 words):
Here's a simple and healthy recipe using chicken breast, spinach, and quinoa:

### Lemon Garlic Chicken with Spinach and Quinoa

#### Ingredients:
- 1 cup quinoa
- 2 cups water or low-sodium chicken broth
- 2 chicken breasts (about 6 oz each)
- 2 cups fresh spinach, washed and chopped
- 2 tablespoons olive oil
- 2 cloves garlic, minced
- Juice of 1 lemon
- Salt and pepper to taste
-

Result from openai_gpt-4o (69 words):
Sure, here's a simple, healthy recipe using chicken breast, spinach, and quinoa:

### Lemon Garlic Chicken with Spinach and Quinoa

#### Ingredients:
- 2 chicken breasts
- 1 cup quinoa
- 2 cups fresh spinach
- 2 cloves garlic, minced
- 1 lemon (zested and juiced)
- 2 tablespoons olive oil
- 1 teaspoon dried oregano
- Salt and pepper to taste
- 2 cups low-sodium chicken broth (

Result from anthropic_claude-3-5-sonnet-20240620 (51 words):
Here's a simple and healthy recipe using chicken breast, spinach, and quinoa:

Lemon Herb Chicken with Spinach Quinoa

Ingredients:
- 2 boneless, skinless chicken breasts
- 1 cup quinoa
- 2 cups water
- 4 cups fresh spinach
- 2 tbsp olive oil
- 1 lemon, juiced and zested
- 2

Result from anthropic_claude-3-opus-20240229 (47 words):
Here's a simple and healthy recipe using chicken breast, spinach, and quinoa:

Spinach and Quinoa Stuffed Chicken Breast

Ingredients:
- 4 boneless, skinless chicken breasts
- 1 cup cooked quinoa
- 2 cups fresh spinach, chopped
- 1/4 cup feta cheese, crumbled
- 1 clove garlic, minced

Result from anthropic_claude-3-sonnet-20240229 (48 words):
Here's a simple and healthy recipe using chicken breast, spinach, and quinoa:

Spinach and Quinoa Stuffed Chicken Breast

Ingredients:

- 4 boneless, skinless chicken breasts
- 1 cup cooked quinoa
- 2 cups fresh spinach, chopped
- 1/4 cup crumbled feta cheese (optional)
- 2 cloves garlic, min

Result from anthropic_claude-3-haiku-20240307 (51 words):
Here's a simple and healthy recipe using chicken breast, spinach, and quinoa:

Baked Chicken with Spinach and Quinoa

Ingredients:
- 4 boneless, skinless chicken breasts
- 2 cups fresh spinach, chopped
- 1 cup cooked quinoa
- 1 tbsp olive oil
- 1 tsp garlic powder
- 1 tsp dried oregano

Result from mistral_open-mistral-7b (222 words):
Title: Chicken, Spinach, and Quinoa Bowl

Ingredients:
1. 2 boneless, skinless chicken breasts
2. 2 cups of fresh spinach
3. 1 cup of uncooked quinoa
4. 2 tablespoons of olive oil
5. Salt and pepper to taste
6. 1 lemon, juiced
7. 1 clove of garlic, minced
8. 1/2 cup of chopped onion
9. 1 cup of chopped cherry tomatoes
10. 1/4 cup of crumbled feta cheese (optional)

Instructions:

1. Cook the quinoa according to the package instructions. Once cooked, set aside and let it cool.

2. Season the chicken breasts with salt, pepper, and garlic. Heat 1 tablespoon of olive oil in a skillet over medium heat. Add the chicken breasts and cook until fully cooked, about 6-8 minutes on each side. Once cooked, let it rest for a few minutes before slicing.

3. In the same skillet, heat the remaining 1 tablespoon of olive oil. Add the chopped onion and sauté until softened. Add the spinach and cook until wilted. Season with salt and pepper.

4. In a large bowl, combine the cooked quinoa, sautéed spinach and onion, sliced chicken breast, cherry tomatoes, and a squeeze of lemon juice. Mix well to combine.

5. Top with crumbled feta cheese if desired.

Enjoy your Chicken, Spinach, and Quinoa Bowl, a simple and healthy meal packed with protein, fiber, and essential nutrients.

Result from mistral_open-mixtral-8x7b (265 words):
Sure, I'd be happy to help! Here's a simple and healthy recipe that incorporates chicken breast, spinach, and quinoa.

**Chicken and Spinach Quinoa Bowl**

Ingredients:

* 1 boneless, skinless chicken breast
* 1 cup spinach
* 1/2 cup quinoa
* 1 cup low-sodium chicken broth
* 1 tablespoon olive oil
* Salt and pepper to taste
* Optional toppings: lemon slices, chopped fresh herbs (such as parsley or cilantro), sliced almonds, crumbled feta cheese

Instructions:

1. Rinse the quinoa in a fine mesh strainer and drain well.
2. Heat the olive oil in a medium saucepan over medium heat.
3. Season the chicken breast with salt and pepper on both sides, then add it to the saucepan. Cook for 4-5 minutes on each side, until it's browned and cooked through. Remove the chicken from the saucepan and set it aside.
4. Add the quinoa and chicken broth to the saucepan and bring to a boil. Reduce the heat to low, cover, and simmer for 15-20 minutes, or until the quinoa is tender and the liquid has been absorbed.
5. While the quinoa is cooking, chop the cooked chicken into bite-sized pieces.
6. When the quinoa is done, stir in the chopped spinach and chicken. Cook for an additional 2-3 minutes, until the spinach is wilted and the chicken is heated through.
7. Season with salt and pepper to taste. Serve the quinoa bowl hot, with your choice of optional toppings.

This recipe is not only simple and healthy, but also versatile. Feel free to customize it with your favorite herbs, spices, or other vegetables. Enjoy!

Result from mistral_open-mixtral-8x22b (343 words):
Title: Spinach and Quinoa Stuffed Chicken Breast

Ingredients:
- 2 boneless, skinless chicken breasts
- 1 cup fresh spinach
- 1/2 cup quinoa
- 1 cup low-sodium chicken broth
- 1 clove garlic, minced
- 1 tablespoon olive oil
- Salt and pepper to taste
- Optional: Fresh lemon for garnish

Instructions:

1. Start by cooking the quinoa. Rinse the quinoa under cold water and drain. Heat a small pot over medium heat, add the quinoa and chicken broth. Bring to a boil, then reduce heat to low, cover and let it simmer for 15 minutes or until the quinoa has absorbed all the liquid. Fluff with a fork and set aside.

2. While the quinoa is cooking, heat the olive oil in a pan over medium heat. Add the minced garlic and cook for about 1 minute until fragrant. Add the spinach and cook until wilted, about 3-4 minutes.

3. Once the spinach is cooked, add it to the cooked quinoa and mix well. Season with salt and pepper to taste.

4. Preheat your oven to 400°F (200°C).

5. Place the chicken breasts on a cutting board. Using a sharp knife, cut a horizontal slit along the thickest part of the breast to create a pocket, being careful not to cut all the way through.

6. Stuff each chicken breast with the quinoa and spinach mixture. Use toothpicks to secure the openings if necessary. Season the chicken with salt and pepper.

7. Heat the same pan used for the spinach over medium-high heat. Add the stuffed chicken breasts and sear on both sides until golden brown, about 2-3 minutes per side.

8. Transfer the seared chicken breasts to a baking dish and bake in the preheated oven for 20-25 minutes, or until the chicken is cooked through and reaches an internal temperature of 165°F (74°C).

9. Remove from the oven and let the chicken rest for a few minutes before serving. Garnish with a squeeze of fresh lemon juice if desired.

Enjoy your healthy and delicious Spinach and Quinoa Stuffed Chicken Breast!

Result from mistral_mistral-small-latest (170 words):
Sure, here's a simple, healthy recipe for you:

**Quinoa and Spinach Stuffed Chicken Breast**

Ingredients:
- 2 boneless, skinless chicken breasts
- 1 cup cooked quinoa
- 2 cups fresh spinach
- 1 clove garlic, minced
- 1/2 onion, finely chopped
- Salt and pepper to taste
- 1 tablespoon olive oil

Instructions:

1. Preheat your oven to 375°F (190°C).

2. Heat the olive oil in a pan over medium heat. Add the onion and garlic, sauté until softened.

3. Add the spinach to the pan and cook until it wilts. Remove from heat and stir in the cooked quinoa. Season with salt and pepper to taste.

4. Cut a pocket into each chicken breast. Stuff each pocket with the spinach and quinoa mixture.

5. Place the stuffed chicken breasts in a baking dish. Bake for about 25-30 minutes, or until the chicken is cooked through and the internal temperature reaches 165°F (74°C).

6. Let the chicken rest for a few minutes before serving. Enjoy your healthy and delicious meal!

Result from mistral_mistral-medium-latest (253 words):
Sure, here's a simple and healthy recipe that you can try using chicken breast, spinach, and quinoa:

**Chicken and Spinach Quinoa Bowl**

Ingredients:

* 1 lb boneless, skinless chicken breast
* 1 cup quinoa
* 2 cups water or chicken broth
* 3 cups fresh spinach
* 1 tbsp olive oil
* Salt and pepper, to taste
* Optional: lemon juice, garlic powder, and crumbled feta cheese

Instructions:

1. Rinse the quinoa in a fine mesh strainer and drain well.
2. In a medium saucepan, bring the water or chicken broth to a boil. Add the quinoa, reduce heat to low, cover, and let it simmer for 15-20 minutes or until the quinoa is tender and the liquid is absorbed.
3. While the quinoa is cooking, heat the olive oil in a large skillet over medium-high heat. Season the chicken breast with salt and pepper, and cook for 5-7 minutes on each side or until it's cooked through and no longer pink in the center.
4. Remove the chicken from the skillet and let it rest for a few minutes before slicing it into thin strips.
5. In the same skillet, add the fresh spinach and cook for 2-3 minutes or until it's wilted.
6. Fluff the cooked quinoa with a fork and divide it into bowls. Top with the sliced chicken breast and wilted spinach.
7. If desired, drizzle with lemon juice, sprinkle with garlic powder, and top with crumbled feta cheese.

Enjoy your healthy and delicious Chicken and Spinach Quinoa Bowl!

Result from mistral_mistral-large-latest (319 words):
**Spinach and Quinoa Stuffed Chicken Breast**

**Ingredients:**
- 2 boneless, skinless chicken breasts
- 1 cup cooked quinoa
- 2 cups fresh spinach
- 2 cloves garlic, minced
- 1 tbsp olive oil
- 1/2 cup crumbled feta cheese (optional, for added flavor)
- Salt and pepper to taste
- 1 tsp lemon zest (optional, for extra freshness)

**Instructions:**

1. **Preheat** your oven to 400°F (200°C) and line a baking sheet with parchment paper.

2. **Cook quinoa** according to package instructions if you haven't already. Set aside.

3. **Heat** olive oil in a pan over medium heat. Add minced garlic and sauté for 1 minute until fragrant.

4. **Add** spinach to the pan and cook until wilted, about 2-3 minutes. Season with salt and pepper.

5. **In a bowl**, combine cooked quinoa, wilted spinach, feta cheese (if using), and lemon zest (if using). Mix well.

6. **Butterfly** the chicken breasts by slicing them horizontally, almost but not all the way through. Open them up like a book.

7. **Place** the chicken breasts between two pieces of plastic wrap and pound them with a meat mallet until they're about 1/4 inch thick.

8. **Spoon** the quinoa and spinach mixture onto one half of each chicken breast, then fold the other half over to close, pressing gently to seal. Use toothpicks to secure if needed.

9. **Place** the stuffed chicken breasts on the prepared baking sheet. Season the outside of the chicken with salt and pepper.

10. **Bake** for 25-30 minutes, or until the chicken is cooked through and the internal temperature reaches 165°F (74°C).

11. **Let** the chicken rest for a few minutes before slicing and serving. Enjoy your healthy and delicious meal!

**Nutritional Information** (per serving, without feta):
- Calories: 350
- Total Fat: 12g
- Saturated Fat: 1.5g
- Cholesterol: 75mg
- Sodium: 300mg
- Total Carbohydrate: 27g
- Dietary Fiber: 4g
- Sugars: 1g
- Protein: 35g