googleapis / nodejs-vertexai

Apache License 2.0
113 stars 37 forks source link

How to authenticate using API key? #197

Open adaboese opened 6 months ago

adaboese commented 6 months ago

I've already generated an API key through https://console.cloud.google.com/apis/credentials

How do I provide it to Vertex SDK?

iharkatkavets commented 5 months ago

It can be done via setting environment variable before executing authorised requests

process.env.GOOGLE_APPLICATION_CREDENTIALS = path_to_json_file

More info here

adaboese commented 5 months ago

That's path to JSON file. I just want to pass the API key.

matiasdaloia commented 5 months ago

I want to authenticate as well with API KEY but i don't know how...

flexchar commented 4 months ago

Majority of services including the Vertex AI platform requires OAuth, which means you MUST use Service Account.

If you do, however, want to use the token, you will have to generate one yourself. This token is short lived (1 hour only) and has to be requested using Service Account.

If you want the token in the CLI environment, you can use export VERTEX_API_KEY=$(gcloud auth print-access-token).

If you want the token inside your applications, you can write an API endpoint from your favorite langauge such as TypeScript and use Google's Auth library to generate one.

Unless you're trying to consume VertexAI from edge runtimes that use WinterCG, I would recommend to use JSON file.

Example using this library and Bun:

import serviceAccount from './service-account.json' assert { type: 'json' };
const vertex_ai = new VertexAI({
    project: project,
    location: location,
    // https://cloud.google.com/nodejs/docs/reference/google-auth-library/latest/google-auth-library/googleauthoptions#google_auth_library_GoogleAuthOptions_credentials_member
    googleAuthOptions: { credentials: serviceAccount },
});
qingfengmy commented 1 month ago

Where can I get the service-account.json file?

flexchar commented 1 month ago

Please see here https://cloud.google.com/iam/docs/service-accounts-create @chingor13