Problem with migation from API asistant v1 to v2

I have this code that runs perfectly with API assistant v.1 I have created a new assistant in v.2 but I don’t know why this code doesn’t run and I get the error that:

"BadRequestError: Error code: 400 - {‘error’: {‘message’: “The requested model ‘gpt-4o’ cannot be used with the Assistants API in v1. Follow the migration guide to upgrade to v2: https://platform.openai.com/docs/assistants/migration.”, ‘type’: ‘invalid_request_error’, ‘param’: ‘model’, ‘code’: ‘unsupported_model’}}
"

I didn’t select any tool here because already when I was creating the assistant on the platform I have activated all the tools and uploaded the required files for file search.

import os
import pandas as pd
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables from api.env
load_dotenv('api.env')

# Retrieve the API key from environment variables
api_key = os.getenv('api_key')

# Initialize the OpenAI client with the API key
client = OpenAI(api_key=api_key)

# Load the Questions and Treatments data from Excel files
questions_df = pd.read_excel('....xlsx')
treatments_df = pd.read_excel('....xlsx')

# Extract the questions and treatments into dictionaries
questions = dict(zip(questions_df['Q_id'], questions_df['Question']))
treatments = dict(zip(treatments_df['Group'], zip(treatments_df['Title'], treatments_df['Information'])))

# Load the Persona data from the Excel file
persona_df = pd.read_excel('....xlsx')

# Specify the number of personas to select
num_personas = 6

# Randomly select the specified number of personas
selected_personas = persona_df.sample(n=num_personas, random_state=42)

# Define the run number
Run = 1

# Assistant IDs
assistants = {
    f"Assistant_N_Run{Run}": "...."
}

# Define the number of runs for each treatment group
group_runs = {
    'T_1': 5,
    'T_2': 5,
    'T_3': 5,
    'T_4': 5,
    'T_5': 5,
    'T_6': 5
}

# Assign the selected personas to treatment groups
selected_personas['Group'] = pd.qcut(selected_personas.index, q=len(group_runs), labels=list(group_runs.keys()))

# Iterate over each assistant
for assistant_name, assistant_id in assistants.items():
    # Store results for the current assistant
    results = []
    
    # Iterate over each treatment group
    for treatment_group, num_runs in group_runs.items():
        # Filter the selected personas for the current treatment group
        group_personas = selected_personas[selected_personas['Group'] == treatment_group]
        
        # Iterate over the runs for the current treatment group
        for run, (_, persona) in enumerate(group_personas.iterrows()):
            # Get the treatment information
            treatment_title, treatment_info = treatments[treatment_group]
            
            # Initialize the result row
            result_row = [run, treatment_group, persona['Age'], persona['Gender'], persona['Education'], persona['Marital'], persona['Income']]
            
            # Iterate over the initial questions (Q1_I to Q5_I)
            for question_id in [q for q in questions.keys() if q.endswith('_I')]:
                # Get the question
                question = questions[question_id]
                
                # Create a Thread
                my_thread = client.beta.threads.create()
                
                # Add a Message to a Thread with the question
                my_thread_message = client.beta.threads.messages.create(
                    thread_id=my_thread.id,
                    role="user",
                    content=question
                )
                
                # Run the Assistant
                my_run = client.beta.threads.runs.create(
                    thread_id=my_thread.id,
                    assistant_id=assistant_id,
                    instructions=f"You are a {persona['Age']} year old {persona['Gender']} .....ets."
                )
                
                # Wait for the Run to complete and retrieve the result
                while True:
                    keep_retrieving_run = client.beta.threads.runs.retrieve(
                        thread_id=my_thread.id,
                        run_id=my_run.id
                    )
                    if keep_retrieving_run.status == "completed":
                        all_messages = client.beta.threads.messages.list(
                            thread_id=my_thread.id
                        )
                        response = all_messages.data[0].content[0].text.value
                        result_row.append(response)
                        break
            
            # Iterate over the follow-up questions (Q1_F to Q2_F)
            for question_id in [q for q in questions.keys() if q.endswith('_F')]:
                # If not in the control group (T_1), provide additional context and ask the follow-up question
                if treatment_group != 'T_1111':
                    # Get the question
                    question = questions[question_id]
                    
                    # Add a Message to the Thread with the additional context and follow-up question
                    my_thread_message = client.beta.threads.messages.create(
                        thread_id=my_thread.id,
                        role="user",
                        content=f"{treatment_info}\n\n{question}"
                    )
                    
                    # Run the Assistant for the follow-up question
                    my_run = client.beta.threads.runs.create(
                        thread_id=my_thread.id,
                        assistant_id=assistant_id,
                    instructions=f"You are a {persona['Age']} year old {persona['Gender']} .....ets."
                    )
                    
                    # Wait for the Run to complete and retrieve the result for the follow-up question
                    while True:
                        keep_retrieving_run = client.beta.threads.runs.retrieve(
                            thread_id=my_thread.id,
                            run_id=my_run.id
                        )
                        if keep_retrieving_run.status == "completed":
                            all_messages = client.beta.threads.messages.list(
                                thread_id=my_thread.id
                            )
                            follow_up_response = all_messages.data[0].content[0].text.value
                            result_row.append(follow_up_response)
                            break
                else:
                    # If in the control group (T_1), append empty responses for the follow-up questions
                    result_row.append('')
            
            # Append the result row to the results list
            results.append(result_row)
            
            # Print the result row for the current run
            print(f"Assistant: {assistant_name}, Group: {treatment_group}, Run {run + 1}: {result_row}")
    
    # Define the column names for the DataFrame
    columns = ['Run', 'Group', 'Age', 'Gender', 'Education', 'Marital', 'Income'] + [f"{q}" for q in questions.keys() if q.endswith('_I')] + [f"{q}" for q in questions.keys() if q.endswith('_F')]
    
    # Convert results to DataFrame
    df = pd.DataFrame(results, columns=columns)
    
    # Print the results for the current assistant
    print(f"\nFinal Results for {assistant_name}:")
    print(df)
    
    # Save to Excel
    df.to_excel(f'results_{assistant_name}.xlsx', index=False)
    print(f"Results for {assistant_name} saved to results_{assistant_name}.xlsx")

Many thanks for any help.

1 Like

I followed the solution in this post and it worked for me

1 Like