Skip to content

Commit f1ad448

Browse files
committed
added logs temporarily to see where the error comes
1 parent 8264110 commit f1ad448

File tree

3 files changed

+46
-6
lines changed

3 files changed

+46
-6
lines changed

api/llm/agent.py

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ def chat_with_agent(message: str, user_id: str = "default", selected_images: Opt
8282
Returns:
8383
Tuple of (agent_response, generated_image_data)
8484
"""
85+
print(f"[AGENT] Starting chat_with_agent - user_id: {user_id}, message: {message[:100]}...")
8586
agent = get_agent()
8687

8788
# Prepare the message with context
@@ -101,26 +102,35 @@ def chat_with_agent(message: str, user_id: str = "default", selected_images: Opt
101102
config = {"configurable": {"thread_id": user_id}}
102103

103104
# Get response from agent
105+
print(f"[AGENT] Invoking agent with config: {config}")
104106
response = agent.invoke({"messages": [{"role": "user", "content": full_message}]}, config=config)
107+
print(f"[AGENT] Agent response received: {type(response)}")
105108

106109
# Extract the last message from the agent
107110
agent_response = "I'm sorry, I couldn't process your request. Please try again."
108111
generated_image_data = None
109112

110113
if response and "messages" in response and len(response["messages"]) > 0:
114+
print(f"[AGENT] Found {len(response['messages'])} messages in response")
111115
last_message = response["messages"][-1]
116+
print(f"[AGENT] Last message type: {type(last_message)}")
112117
# Handle both AIMessage objects and dictionaries
113118
if hasattr(last_message, "content"):
114119
agent_response = last_message.content
115120
elif isinstance(last_message, dict) and "content" in last_message:
116121
agent_response = last_message["content"]
122+
print(f"[AGENT] Extracted agent response: {agent_response[:100]}...")
117123

118124
# Check if any tools were used (image generation)
125+
print(f"[AGENT] Checking intermediate steps: {response.get('intermediate_steps', [])}")
119126
if "intermediate_steps" in response and response["intermediate_steps"]:
120-
for step in response["intermediate_steps"]:
127+
print(f"[AGENT] Found {len(response['intermediate_steps'])} intermediate steps")
128+
for i, step in enumerate(response["intermediate_steps"]):
129+
print(f"[AGENT] Step {i}: {step}")
121130
if len(step) >= 2 and "generate_image" in str(step[0]):
122131
# Extract image data from the tool result
123132
tool_result = step[1]
133+
print(f"[AGENT] Found generate_image tool result: {tool_result}")
124134

125135
# Try multiple patterns to find the image ID
126136
image_id = None
@@ -143,6 +153,7 @@ def chat_with_agent(message: str, user_id: str = "default", selected_images: Opt
143153
title = title_match.group(1)
144154

145155
if image_id:
156+
print(f"[AGENT] Found image_id: {image_id}, attempting to get S3 metadata")
146157
# Get metadata from S3
147158
import boto3
148159

@@ -154,18 +165,23 @@ def chat_with_agent(message: str, user_id: str = "default", selected_images: Opt
154165
)
155166

156167
bucket_name = os.environ.get("AWS_S3_BUCKET_NAME")
168+
print(f"[AGENT] Using bucket: {bucket_name}")
157169
if bucket_name:
158170
try:
159171
# Get metadata from S3
160-
metadata_response = s3_client.head_object(Bucket=bucket_name, Key=f"users/{user_id}/images/{image_id}")
172+
s3_key = f"users/{user_id}/images/{image_id}"
173+
print(f"[AGENT] Getting metadata for S3 key: {s3_key}")
174+
metadata_response = s3_client.head_object(Bucket=bucket_name, Key=s3_key)
161175
metadata = metadata_response.get("Metadata", {})
176+
print(f"[AGENT] Retrieved metadata: {metadata}")
162177

163178
# Generate presigned URL
164179
presigned_url = s3_client.generate_presigned_url(
165180
"get_object",
166181
Params={"Bucket": bucket_name, "Key": f"users/{user_id}/images/{image_id}"},
167182
ExpiresIn=7200, # 2 hours
168183
)
184+
print(f"[AGENT] Generated presigned URL: {presigned_url[:50]}...")
169185

170186
generated_image_data = {
171187
"id": image_id,
@@ -175,15 +191,17 @@ def chat_with_agent(message: str, user_id: str = "default", selected_images: Opt
175191
"timestamp": metadata.get("uploadedAt", datetime.now().isoformat()),
176192
"type": "generated",
177193
}
194+
print(f"[AGENT] Created generated_image_data: {generated_image_data}")
178195

179196
except Exception as e:
180-
print(f"Error getting S3 metadata: {e}")
197+
print(f"[AGENT] Error getting S3 metadata: {e}")
181198
# Don't return image data if we can't get a valid URL
182199
generated_image_data = None
183200
# Add error message to agent response
184201
agent_response += "\n\n⚠️ Note: I generated the image successfully, \
185202
but there was an issue retrieving it from the database. Please try again."
186203

204+
print(f"[AGENT] Returning response - agent_response length: {len(agent_response)}, generated_image_data: {generated_image_data is not None}")
187205
return agent_response, generated_image_data
188206

189207

api/llm/prompt.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,18 @@
44
You are a helpful AI image editing assistant. You help users with image editing
55
tasks and provide guidance on how to modify their images.
66
7+
IMPORTANT: When a user asks you to generate, create, or modify an image, you MUST use the generate_image tool.
8+
Do NOT try to generate images directly - always use the generate_image tool.
9+
710
You can generate images using the generate_image tool. However, remember that
811
you are only allowed to generate one image per user's request. You are NOT allowed
912
to generate more than one image per user's request, no matter how many images the user
1013
wants to generate per request (e.g. generate 10 images for me based on this one image).
1114
15+
When using the generate_image tool, you need to provide:
16+
- prompt: A description of what you want to generate
17+
- user_id: The user's ID
18+
- image_url: The URL of the source image (if provided by the user)
19+
- title: A descriptive title for the generated image
20+
1221
"""

api/llm/tools.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ def generate_image(
2626
"""
2727
Generate an image based on a prompt.
2828
"""
29+
print(f"[TOOL] generate_image called with prompt: {prompt[:50]}..., user_id: {user_id}, image_url: {image_url[:50]}...")
2930
input = {
3031
"width": 768,
3132
"height": 768,
@@ -38,17 +39,21 @@ def generate_image(
3839
}
3940

4041
# Generate image using Replicate
42+
print(f"[TOOL] Calling Replicate with input: {input}")
4143
version = "stability-ai/sdxl:" "7762fd07cf82c948538e41f63f77d685e02b063e37e496e96eefd46c929f9bdc"
4244
output = replicate.run(
4345
version,
4446
input=input,
4547
)
48+
print(f"[TOOL] Replicate output: {output}")
4649

4750
# Check if generation was successful
4851
if not output or len(output) == 0:
52+
print("[TOOL] Replicate generation failed - no output")
4953
return "Failed to generate image. Please try again."
5054

5155
generated_image_url = output[0] if isinstance(output, list) else output
56+
print(f"[TOOL] Generated image URL: {generated_image_url}")
5257

5358
# Download the generated image
5459
image_data: Optional[bytes] = None
@@ -65,6 +70,7 @@ def generate_image(
6570
image_id = str(uuid.uuid4())
6671

6772
# Upload to S3
73+
print(f"[TOOL] Uploading to S3 with image_id: {image_id}")
6874
try:
6975
s3_result = upload_generated_image_to_s3(
7076
image_data=image_data,
@@ -73,15 +79,22 @@ def generate_image(
7379
prompt=prompt,
7480
title=title,
7581
)
82+
print(f"[TOOL] S3 upload result: {s3_result}")
7683

7784
if s3_result["success"]:
78-
return f"Image generated successfully! User can find it his/her gallery. \
85+
result_msg = f"Image generated successfully! User can find it his/her gallery. \
7986
Image ID: {image_id}, Title: {title}"
87+
print(f"[TOOL] Returning success: {result_msg}")
88+
return result_msg
8089
else:
81-
return f"Image generated but failed to save: {s3_result.get('error', 'Unknown error')}"
90+
error_msg = f"Image generated but failed to save: {s3_result.get('error', 'Unknown error')}"
91+
print(f"[TOOL] Returning error: {error_msg}")
92+
return error_msg
8293

8394
except Exception as e:
84-
return f"Image generated but failed to save to storage: {str(e)}"
95+
error_msg = f"Image generated but failed to save to storage: {str(e)}"
96+
print(f"[TOOL] Exception during S3 upload: {error_msg}")
97+
return error_msg
8598

8699
finally:
87100
if image_data:

0 commit comments

Comments
 (0)