PermissionDenied: 403 You do not have permission to access tuned model

Hello,
I have being trying with no success to use a tuned model with Gemini API. I have followed all guides to:

  • set up the OAuth 2.0 Client ID
  • Consent screen with scopes ( for example …/auth/generative-language.tuning )
  • Storing the credential for use

Unfotunately I keep getting the message : “exc
google.api_core.exceptions.PermissionDenied: 403 You do not have permission to access tuned model tunedModels/mymodel”

Bellows is the code

import os
import google.generativeai as genai
from dotenv import load_dotenv

load_dotenv()

load_dotenv(dotenv_path=r"C:\Users\REPRO SANDRO\Documents\AI PROJECTS\GEN AI\.env")  # Use the correct path to your .env file
credentials_path = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")

# Configure the API key for the Google Generative AI
genai.configure(api_key="mykey", transport="grpc")
# Configuration for text generation 
generation_config = {
    "temperature": 0.9, 
    "top_p": 0.95,
    "top_k": 64,
    "max_output_tokens": 1024,
    "response_mime_type": "text/plain",
}

# Create a GenerativeModel instance
model = genai.GenerativeModel(
    model_name="tunedModels/custom-interact-sentiment-analysis-zn037",
    generation_config=generation_config,
)

# Start a chat session
chat_session = model.start_chat(enable_automatic_function_calling=True)

# Send a message to the chat session including the file URI
response = chat_session.send_message(f"Fazer análise de sentimento no seguinte texto: 'Visita relacionamento, Jaque ainda não quebrou parceria com seu laboratório parceiro do RS Precision'. Apenas classifique positivo, neutro, ou negativo, nenhuma explicação é necessária.")

# Print the response
print(response.text)

Would be the scopes a problem ? What am i missing ?

Thanks in advance

The issue is that although you set a credentials_path attribute, you don’t use it anywhere.

Instead, you’re still setting the api_key when you configure the model:

You need to use the path to load in the credentials from a file then convert this to a credentials object to pass in. See this quickstart for all of the details, but you may do something like this to load the credentials:

def load_creds():
    """Converts `client_secret.json` to a credential object.

    This function caches the generated tokens to minimize the use of the
    consent screen.
    """
    creds = None
    if os.path.exists(credentials_path):
        creds = Credentials.from_authorized_user_file(credentials_path, SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secret.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(credentials_path, 'w') as token:
            token.write(creds.to_json())
    return creds

and then calling it with something like

creds = load_creds()
genai.configure(credentials=creds)
1 Like

Thank you. You guidance got me out of this problem i have been on days !

1 Like