|
| 1 | +# Copyright 2024 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import os |
| 15 | + |
| 16 | +PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT") |
| 17 | + |
| 18 | + |
| 19 | +def generate_text() -> object: |
| 20 | + # [START generativeaionvertexai_gemini_chat_completions_non_streaming_image] |
| 21 | + import vertexai |
| 22 | + import openai |
| 23 | + |
| 24 | + from google.auth import default, transport |
| 25 | + |
| 26 | + # TODO(developer): Update and un-comment below lines |
| 27 | + # PROJECT_ID = "your-project-id" |
| 28 | + location = "us-central1" |
| 29 | + |
| 30 | + vertexai.init(project=PROJECT_ID, location=location) |
| 31 | + |
| 32 | + # Programmatically get an access token |
| 33 | + credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) |
| 34 | + auth_request = transport.requests.Request() |
| 35 | + credentials.refresh(auth_request) |
| 36 | + |
| 37 | + # OpenAI Client |
| 38 | + client = openai.OpenAI( |
| 39 | + base_url=f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{location}/endpoints/openapi", |
| 40 | + api_key=credentials.token, |
| 41 | + ) |
| 42 | + |
| 43 | + response = client.chat.completions.create( |
| 44 | + model="google/gemini-1.5-flash-002", |
| 45 | + messages=[ |
| 46 | + { |
| 47 | + "role": "user", |
| 48 | + "content": [ |
| 49 | + {"type": "text", "text": "Describe the following image:"}, |
| 50 | + { |
| 51 | + "type": "image_url", |
| 52 | + "image_url": "gs://cloud-samples-data/generative-ai/image/scones.jpg", |
| 53 | + }, |
| 54 | + ], |
| 55 | + } |
| 56 | + ], |
| 57 | + ) |
| 58 | + |
| 59 | + print(response.choices[0].message.content) |
| 60 | + # Example response: |
| 61 | + # Here's a description of the image: |
| 62 | + # High-angle, close-up view of a rustic arrangement featuring several blueberry scones |
| 63 | + # on a piece of parchment paper. The scones are golden-brown... |
| 64 | + |
| 65 | + # [END generativeaionvertexai_gemini_chat_completions_non_streaming_image] |
| 66 | + return response |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + generate_text() |
0 commit comments