|
| 1 | +import functions_framework |
| 2 | +import google.ai.generativelanguage as glm |
| 3 | +import google.generativeai as palm |
| 4 | +from google.oauth2 import credentials |
| 5 | +import json |
| 6 | +import requests |
| 7 | + |
| 8 | +SCOPES = [ |
| 9 | + 'https://www.googleapis.com/auth/cloud-platform', |
| 10 | + 'https://www.googleapis.com/auth/generative-language.tuning', |
| 11 | +] |
| 12 | + |
| 13 | +def get_credentials(): |
| 14 | + """Generate scoped OAuth2 credentials.""" |
| 15 | + token_full_url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token?scopes=' + ','.join(SCOPES) |
| 16 | + token_response = requests.get(token_full_url, headers={'Metadata-Flavor': 'Google'}) |
| 17 | + if token_response.status_code != 200: |
| 18 | + raise ValueError(f'Cant auth - {token_response.status_code}: {token_response.text}') |
| 19 | + |
| 20 | + token = json.loads(token_response.text) |
| 21 | + return credentials.Credentials(token=token['access_token']) |
| 22 | + |
| 23 | + |
| 24 | +@functions_framework.http |
| 25 | +def load_model(request): |
| 26 | + """Load a PaLM model using a service account.""" |
| 27 | + |
| 28 | + # Build a google.auth.credentials.Credentials object from the running service account's |
| 29 | + # authorisation, with the desired scopes defined above. |
| 30 | + o2_creds = get_credentials() |
| 31 | + # Each PaLM API uses a different client, e.g. ModelServiceClient, TextServiceClient, etc. |
| 32 | + # You will need to build the respective client for the API you are using. |
| 33 | + model_client = glm.ModelServiceClient(credentials=o2_creds) |
| 34 | + |
| 35 | + # Test tuning by passing name=tunedModels/your-model-id. You must ensure that the model is shared |
| 36 | + # with the running service account, or you will see a permission denied error (in the logs). |
| 37 | + model_name = request.args.get('name', 'models/text-bison-001') |
| 38 | + model = palm.get_model(model_name, client=model_client) |
| 39 | + return f'<pre>{model}</pre>' |
0 commit comments