Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Text-bison and http 400 error

This powershell script gets :

Error sending API request:
The remote server returned an error: (400) Bad Request.

what could be the root cause ? bad url ?


apiUrl = "https://${location}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/publishers/google/models/${modelVersion}:predict"
# Get Access Token Correctly
$serviceAccountKey="C:\temp\e97314fdbd4.json"
gcloud auth activate-service-account --key-file=$serviceAccountKey 2>$null

$accessToken = gcloud auth print-access-token
if (-not $accessToken) {
Write-Host "Failed to obtain access token. Ensure your service account is authenticated."
exit 1
}


# Create the request payload
$body = @{
instances = @(
@{ content = "Summarize this text: Artificial Intelligence is transforming industries by automating processes and improving efficiency." }
)
parameters = @{
temperature = 0.7
maxOutputTokens = 100
}
} | ConvertTo-Json -Depth 5

# Define headers correctly as a hash table
$headers = @{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
}

# Send API request using Invoke-WebRequest
try {
$response = Invoke-WebRequest -Uri $apiUrl -Method Post -Headers $headers -Body $body -ContentType "application/json" -UseBasicParsing
Write-Host "Response:"
Write-Host $response.Content
} catch {
Write-Host "Error sending API request:"
Write-Host $_.Exception.Message
}

0 1 97
1 REPLY 1

Hi @faridn,

Welcome to the Google Cloud Community!

The (400) Bad Request error message you received indicates a problem with either the structure of the request or how the API endpoint is being used.

Here are possible causes and ways to troubleshoot the issue:

  • Bad URL - Double check that the URL is formatted correctly and that all variables have the correct values assigned.
  • Access token - Check if the access token is valid and has not expired.
  • Request Payload - Ensure your request payload aligns with the API's expected format. Verify that your $body (JSON) is structured correctly. The structure must align with the format required by the model you are using.
  • Model Version Compatibility - It's possible that the model version you're using has been deprecated. Google Cloud AI Platform has been transitioning to Vertex AI. You'll  need to migrate to the new Vertex AI platform to continue using the latest features and avoid disruptions. 

Was this helpful? If so, please accept this answer as “Solution”. If you need additional assistance, reply here within 2 business days and I’ll be happy to help.