1313import sys
1414from io import BytesIO
1515import aiohttp
16- import PIL .Image
17- import base64
1816import uuid
1917from google .cloud import storage
2018
6765 model_name = "gemini-2.0-flash" ,
6866 project = google_project_id ,
6967 location = google_location ,
70- max_output_tokens = 2048 # Increased token limit for detailed image descriptions
68+ # Increased token limit for detailed image descriptions
69+ max_output_tokens = 2048
7170)
7271
7372
@@ -121,7 +120,9 @@ async def handle_callback(request: Request):
121120 msg = event .message .text
122121 user_id = event .source .user_id
123122 print (f"Received message: { msg } from user: { user_id } " )
124- response = generate_text_with_langchain (f'{ msg } , reply in zh-TW:' )
123+ response = generate_text_with_langchain (
124+ f'{ msg } , reply in zh-TW:'
125+ )
125126 reply_msg = TextSendMessage (text = response )
126127 await line_bot_api .reply_message (
127128 event .reply_token ,
@@ -131,21 +132,24 @@ async def handle_callback(request: Request):
131132 user_id = event .source .user_id
132133 print (f"Received image from user: { user_id } " )
133134
134- message_content = await line_bot_api .get_message_content (event .message .id )
135-
135+ message_content = await line_bot_api .get_message_content (
136+ event .message .id
137+ )
138+
136139 # Asynchronously read all content chunks into a byte string
137140 image_bytes = b''
138141 async for chunk in message_content .iter_content ():
139142 image_bytes += chunk
140-
143+
141144 # Create an in-memory binary stream from the bytes
142145 image_stream = BytesIO (image_bytes )
143- # Reset the stream's pointer to the beginning for the upload function
146+ # Reset the stream's pointer to the beginning for the upload
144147 image_stream .seek (0 )
145148
146149 file_name = f"{ uuid .uuid4 ()} .jpg"
147150 gcs_uri = None
148- response = "抱歉,處理您的圖片時發生錯誤。" # Default error message
151+ # Default error message
152+ response = "抱歉,處理您的圖片時發生錯誤。"
149153
150154 try :
151155 gcs_uri = upload_to_gcs (
@@ -176,7 +180,9 @@ def generate_text_with_langchain(prompt):
176180 # Create a chat prompt template with system instructions
177181 prompt_template = ChatPromptTemplate .from_messages ([
178182 SystemMessage (
179- content = "You are a helpful assistant that responds in Traditional Chinese (zh-TW)." ),
183+ content = "You are a helpful assistant that responds in "
184+ "Traditional Chinese (zh-TW)."
185+ ),
180186 HumanMessage (content = prompt )
181187 ])
182188
@@ -189,6 +195,7 @@ def generate_text_with_langchain(prompt):
189195
190196def generate_image_description (image_uri ):
191197 """
198+
192199 Generate a description for an image using LangChain with Vertex AI.
193200 """
194201 # The prompt is already defined globally as imgage_prompt
@@ -206,4 +213,4 @@ def generate_image_description(image_uri):
206213 )
207214
208215 response = model .invoke ([message ])
209- return response .content
216+ return response .content
0 commit comments