Blame view

app.py 21.6 KB
e7f2b240   tangwang   first commit
1
  """
bad17b15   tangwang   调通baseline
2
  ShopAgent - Streamlit UI
e7f2b240   tangwang   first commit
3
4
5
6
7
8
9
10
11
12
13
14
15
  Multi-modal fashion shopping assistant with conversational AI
  """
  
  import logging
  import re
  import uuid
  from pathlib import Path
  from typing import Optional
  
  import streamlit as st
  from PIL import Image, ImageOps
  
  from app.agents.shopping_agent import ShoppingAgent
66442668   tangwang   feat: 搜索结果引用与并行搜索...
16
17
18
19
20
  from app.search_registry import ProductItem, SearchResult, global_registry
  
  # Matches [SEARCH_REF:sr_xxxxxxxx] tokens embedded in AI responses.
  # Case-insensitive, optional spaces around the id.
  SEARCH_REF_PATTERN = re.compile(r"\[SEARCH_REF:\s*([a-zA-Z0-9_]+)\s*\]", re.IGNORECASE)
e7f2b240   tangwang   first commit
21
22
23
24
25
26
27
28
29
30
  
  # Configure logging
  logging.basicConfig(
      level=logging.INFO,
      format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  )
  logger = logging.getLogger(__name__)
  
  # Page config
  st.set_page_config(
bad17b15   tangwang   调通baseline
31
      page_title="ShopAgent",
e7f2b240   tangwang   first commit
32
33
34
35
36
37
38
39
40
      page_icon="👗",
      layout="centered",
      initial_sidebar_state="collapsed",
  )
  
  # Custom CSS - ChatGPT-like style
  st.markdown(
      """
      <style>
9ad88986   tangwang   up`
41
42
      /* Show default Streamlit elements (sidebar toggle, etc.) */
      /* #MainMenu, footer, header no longer hidden */
e7f2b240   tangwang   first commit
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
      
      /* Body and root container */
      .main .block-container {
          padding-bottom: 180px !important;
          padding-top: 2rem;
          max-width: 900px;
          margin: 0 auto;
      }
      
      /* Fixed input container at bottom */
      .fixed-input-container {
          position: fixed;
          bottom: 0;
          left: 0;
          right: 0;
          background: white;
          border-top: 1px solid #e5e5e5;
          padding: 1rem 0;
          z-index: 1000;
          box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
      }
      
      .fixed-input-container .block-container {
          max-width: 900px;
          margin: 0 auto;
          padding: 0 1rem !important;
      }
      
      /* Message bubbles */
      .message {
          margin: 1rem 0;
          padding: 1rem 1.5rem;
          border-radius: 1rem;
          animation: fadeIn 0.3s ease-in;
      }
      
      @keyframes fadeIn {
          from { opacity: 0; transform: translateY(10px); }
          to { opacity: 1; transform: translateY(0); }
      }
      
      .user-message {
          background: transparent;
          margin: 0 0 1rem 0;
          padding: 0;
          border-radius: 0;
      }
      
      .assistant-message {
          background: white;
          border: 1px solid #e5e5e5;
          margin-right: 3rem;
      }
      
      /* Product cards - simplified */
      .stImage {
          border-radius: 0px;
          overflow: hidden;
      }
      
      .stImage img {
          transition: transform 0.2s;
      }
      
      .stImage:hover img {
          transform: scale(1.05);
      }
      
      /* Scroll to bottom behavior */
      html {
          scroll-behavior: smooth;
      }
      
      /* Header */
      .app-header {
          text-align: center;
          padding: 2rem 1rem;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          border-radius: 1rem;
          margin-bottom: 2rem;
      }
      
      .app-title {
          font-size: 2rem;
          font-weight: 700;
          margin: 0;
      }
      
      .app-subtitle {
          font-size: 1rem;
          opacity: 0.9;
          margin-top: 0.5rem;
      }
      
      /* Welcome screen */
      .welcome-container {
          text-align: center;
          padding: 4rem 2rem;
          color: #666;
      }
      
      .welcome-title {
          font-size: 2rem;
          font-weight: 600;
          color: #1a1a1a;
          margin-bottom: 1rem;
      }
      
      .welcome-features {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 1.5rem;
          margin: 2rem 0;
      }
      
      .feature-card {
          background: #f7f7f8;
          padding: 1.5rem;
          border-radius: 12px;
          transition: all 0.2s;
      }
      
      .feature-card:hover {
          background: #efefef;
          transform: translateY(-2px);
      }
      
      .feature-icon {
          font-size: 2rem;
          margin-bottom: 0.5rem;
      }
      
      .feature-title {
          font-weight: 600;
          margin-bottom: 0.25rem;
      }
      
      /* Image preview */
      .image-preview {
          position: relative;
          display: inline-block;
          margin: 0.5rem 0;
      }
      
      .image-preview img {
          max-width: 200px;
          border-radius: 8px;
          border: 2px solid #e5e5e5;
      }
      
      .remove-image-btn {
          position: absolute;
          top: 5px;
          right: 5px;
          background: rgba(0,0,0,0.6);
          color: white;
          border: none;
          border-radius: 50%;
          width: 24px;
          height: 24px;
          cursor: pointer;
          font-size: 14px;
      }
      
      /* Buttons */
      .stButton>button {
          border-radius: 8px;
          border: 1px solid #e5e5e5;
          padding: 0.5rem 1rem;
          transition: all 0.2s;
      }
      
      .stButton>button:hover {
          background: #f0f0f0;
          border-color: #d0d0d0;
      }
      
      /* Hide upload button label */
      .uploadedFile {
          display: none;
      }
      </style>
      """,
      unsafe_allow_html=True,
  )
  
  
  # Initialize session state
  def initialize_session():
      """Initialize session state variables"""
      if "session_id" not in st.session_state:
          st.session_state.session_id = str(uuid.uuid4())
  
      if "shopping_agent" not in st.session_state:
          st.session_state.shopping_agent = ShoppingAgent(
              session_id=st.session_state.session_id
          )
  
      if "messages" not in st.session_state:
          st.session_state.messages = []
  
      if "uploaded_image" not in st.session_state:
          st.session_state.uploaded_image = None
  
      if "show_image_upload" not in st.session_state:
          st.session_state.show_image_upload = False
  
825828c4   tangwang   fix: search image...
251
      # Debug panel toggle (default True so 显示调试过程 is checked by default)
01b46131   tangwang   流程跑通
252
      if "show_debug" not in st.session_state:
825828c4   tangwang   fix: search image...
253
          st.session_state.show_debug = True
01b46131   tangwang   流程跑通
254
  
e7f2b240   tangwang   first commit
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
  
  def save_uploaded_image(uploaded_file) -> Optional[str]:
      """Save uploaded image to temp directory"""
      if uploaded_file is None:
          return None
  
      try:
          temp_dir = Path("temp_uploads")
          temp_dir.mkdir(exist_ok=True)
  
          image_path = temp_dir / f"{st.session_state.session_id}_{uploaded_file.name}"
          with open(image_path, "wb") as f:
              f.write(uploaded_file.getbuffer())
  
          logger.info(f"Saved uploaded image to {image_path}")
          return str(image_path)
  
      except Exception as e:
          logger.error(f"Error saving uploaded image: {e}")
          st.error(f"Failed to save image: {str(e)}")
          return None
  
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
278
  def _load_product_image(product: ProductItem) -> Optional[Image.Image]:
825828c4   tangwang   fix: search image...
279
      """Try to load a product image: image_url from API (normalized when stored) → local data/images → None."""
66442668   tangwang   feat: 搜索结果引用与并行搜索...
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
      if product.image_url:
          try:
              import requests
              resp = requests.get(product.image_url, timeout=10)
              if resp.status_code == 200:
                  import io
                  return Image.open(io.BytesIO(resp.content))
          except Exception as e:
              logger.debug(f"Remote image fetch failed for {product.spu_id}: {e}")
  
      local = Path(f"data/images/{product.spu_id}.jpg")
      if local.exists():
          try:
              return Image.open(local)
          except Exception as e:
              logger.debug(f"Local image load failed {local}: {e}")
      return None
  
  
  def display_product_card_from_item(product: ProductItem) -> None:
      """Render a single product card from a ProductItem (registry entry)."""
      img = _load_product_image(product)
  
      if img:
          target = (220, 220)
          try:
              img = ImageOps.fit(img, target, method=Image.Resampling.LANCZOS)
          except AttributeError:
              img = ImageOps.fit(img, target, method=Image.LANCZOS)
825828c4   tangwang   fix: search image...
309
          st.image(img, width="stretch")
66442668   tangwang   feat: 搜索结果引用与并行搜索...
310
311
312
313
314
315
316
317
318
319
320
321
322
323
      else:
          st.markdown(
              '<div style="height:120px;background:#f5f5f5;border-radius:6px;'
              'display:flex;align-items:center;justify-content:center;'
              'color:#bbb;font-size:2rem;">🛍️</div>',
              unsafe_allow_html=True,
          )
  
      title = product.title or "未知商品"
      st.markdown(f"**{title[:40]}**" + ("…" if len(title) > 40 else ""))
  
      if product.price is not None:
          st.caption(f"¥{product.price:.2f}")
  
621b6925   tangwang   up
324
      label_style = "⭐" if product.match_label == "Relevant" else "✦"
66442668   tangwang   feat: 搜索结果引用与并行搜索...
325
      st.caption(f"{label_style} {product.match_label}")
e7f2b240   tangwang   first commit
326
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
327
328
  
  def render_search_result_block(result: SearchResult) -> None:
e7f2b240   tangwang   first commit
329
      """
66442668   tangwang   feat: 搜索结果引用与并行搜索...
330
331
332
      Render a full search result block in place of a [SEARCH_REF:xxx] token.
  
      Shows:
5e3d6d3a   tangwang   refactor(search):...
333
      - A styled header with query + match counts + quality_summary (if any)
621b6925   tangwang   up
334
      - A grid of product cards (Relevant first, then Partially Relevant; max 6)
66442668   tangwang   feat: 搜索结果引用与并行搜索...
335
      """
5e3d6d3a   tangwang   refactor(search):...
336
      summary_line = f' &nbsp;·&nbsp;{result.quality_summary}' if result.quality_summary else ''
66442668   tangwang   feat: 搜索结果引用与并行搜索...
337
338
339
340
341
      header_html = (
          f'<div style="border:1px solid #e0e0e0;border-radius:8px;padding:10px 14px;'
          f'margin:8px 0 4px 0;background:#fafafa;">'
          f'<span style="font-size:0.8rem;color:#555;">'
          f'🔍 <b>{result.query}</b>'
621b6925   tangwang   up
342
          f'&nbsp;·&nbsp;Relevant&nbsp;{result.perfect_count}&nbsp;件'
5e3d6d3a   tangwang   refactor(search):...
343
344
          f'&nbsp;·&nbsp;Partially Relevant&nbsp;{result.partial_count}&nbsp;件'
          f'{summary_line}'
66442668   tangwang   feat: 搜索结果引用与并行搜索...
345
346
347
348
349
          f'</span></div>'
      )
      st.markdown(header_html, unsafe_allow_html=True)
  
      # Perfect matches first, fall back to partials if none
621b6925   tangwang   up
350
      perfect = [p for p in result.products if p.match_label == "Relevant"]
5e3d6d3a   tangwang   refactor(search):...
351
      partial = [p for p in result.products if p.match_label == "Partially Relevant"]
66442668   tangwang   feat: 搜索结果引用与并行搜索...
352
353
354
355
356
357
358
359
360
361
362
363
      to_show = (perfect + partial)[:6] if perfect else partial[:6]
  
      if not to_show:
          st.caption("(本次搜索未找到可展示的商品)")
          return
  
      cols = st.columns(min(len(to_show), 3))
      for i, product in enumerate(to_show):
          with cols[i % 3]:
              display_product_card_from_item(product)
  
  
621b6925   tangwang   up
364
365
366
367
368
  def render_message_with_refs(
      content: str,
      session_id: str,
      fallback_refs: Optional[dict] = None,
  ) -> None:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
369
370
371
372
373
      """
      Render an assistant message that may contain [SEARCH_REF:xxx] tokens.
  
      Text segments are rendered as markdown.
      [SEARCH_REF:xxx] tokens are replaced with full product card blocks
621b6925   tangwang   up
374
375
      loaded from the global registry, or from fallback_refs (e.g. refs stored
      with the message so they survive reruns / different workers).
66442668   tangwang   feat: 搜索结果引用与并行搜索...
376
      """
621b6925   tangwang   up
377
      fallback_refs = fallback_refs or {}
66442668   tangwang   feat: 搜索结果引用与并行搜索...
378
379
380
381
382
383
384
385
386
      # re.split with a capture group alternates: [text, ref_id, text, ref_id, ...]
      parts = SEARCH_REF_PATTERN.split(content)
  
      for i, segment in enumerate(parts):
          if i % 2 == 0:
              # Text segment
              text = segment.strip()
              if text:
                  st.markdown(text)
e7f2b240   tangwang   first commit
387
          else:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
388
389
              # ref_id segment
              ref_id = segment.strip()
621b6925   tangwang   up
390
              result = global_registry.get(session_id, ref_id) or fallback_refs.get(ref_id)
66442668   tangwang   feat: 搜索结果引用与并行搜索...
391
392
393
394
395
              if result:
                  render_search_result_block(result)
              else:
                  # ref not found (e.g. old session after restart)
                  st.caption(f"[搜索结果 {ref_id} 不可用]")
e7f2b240   tangwang   first commit
396
397
398
399
400
401
402
403
  
  
  def display_message(message: dict):
      """Display a chat message"""
      role = message["role"]
      content = message["content"]
      image_path = message.get("image_path")
      tool_calls = message.get("tool_calls", [])
01b46131   tangwang   流程跑通
404
      debug_steps = message.get("debug_steps", [])
e7f2b240   tangwang   first commit
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
  
      if role == "user":
          st.markdown('<div class="message user-message">', unsafe_allow_html=True)
  
          if image_path and Path(image_path).exists():
              try:
                  img = Image.open(image_path)
                  st.image(img, width=200)
              except Exception:
                  logger.warning(f"Failed to load user uploaded image: {image_path}")
  
          st.markdown(content)
          st.markdown("</div>", unsafe_allow_html=True)
  
      else:  # assistant
66442668   tangwang   feat: 搜索结果引用与并行搜索...
420
          # Tool call breadcrumb
e7f2b240   tangwang   first commit
421
          if tool_calls:
01b46131   tangwang   流程跑通
422
              tool_names = [tc["name"] for tc in tool_calls]
e7f2b240   tangwang   first commit
423
424
              st.caption(" → ".join(tool_names))
              st.markdown("")
01b46131   tangwang   流程跑通
425
  
66442668   tangwang   feat: 搜索结果引用与并行搜索...
426
          # Debug panel
01b46131   tangwang   流程跑通
427
428
429
430
431
432
433
434
435
436
437
          if debug_steps and st.session_state.get("show_debug"):
              with st.expander("思考 & 工具调用详细过程", expanded=False):
                  for idx, step in enumerate(debug_steps, 1):
                      node = step.get("node", "unknown")
                      st.markdown(f"**Step {idx} – {node}**")
  
                      if node == "agent":
                          msgs = step.get("messages", [])
                          if msgs:
                              st.markdown("**Agent Messages**")
                              for m in msgs:
66442668   tangwang   feat: 搜索结果引用与并行搜索...
438
                                  st.markdown(f"- `{m.get('type', 'assistant')}`: {m.get('content', '')}")
01b46131   tangwang   流程跑通
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
  
                          tcs = step.get("tool_calls", [])
                          if tcs:
                              st.markdown("**Planned Tool Calls**")
                              for j, tc in enumerate(tcs, 1):
                                  st.markdown(f"- **{j}. {tc.get('name')}**")
                                  st.code(tc.get("args", {}), language="json")
  
                      elif node == "tools":
                          results = step.get("results", [])
                          if results:
                              st.markdown("**Tool Results**")
                              for j, r in enumerate(results, 1):
                                  st.markdown(f"- **Result {j}:**")
                                  st.code(r.get("content", ""), language="text")
  
                      st.markdown("---")
66442668   tangwang   feat: 搜索结果引用与并行搜索...
456
457
458
  
          # Render message: expand [SEARCH_REF:xxx] tokens into product card blocks
          session_id = st.session_state.get("session_id", "")
621b6925   tangwang   up
459
460
461
          render_message_with_refs(
              content, session_id, fallback_refs=message.get("search_refs")
          )
e7f2b240   tangwang   first commit
462
463
464
465
466
467
468
469
470
471
472
473
474
  
          st.markdown("</div>", unsafe_allow_html=True)
  
  
  def display_welcome():
      """Display welcome screen"""
  
      col1, col2, col3, col4 = st.columns(4)
  
      with col1:
          st.markdown(
              """
              <div class="feature-card">
01b46131   tangwang   流程跑通
475
476
477
                  <div class="feature-icon">💗</div>
                  <div class="feature-title">懂你</div>
                  <div>能记住你的偏好,给你推荐适合的</div>
e7f2b240   tangwang   first commit
478
479
480
481
482
483
484
485
486
              </div>
              """,
              unsafe_allow_html=True,
          )
  
      with col2:
          st.markdown(
              """
              <div class="feature-card">
01b46131   tangwang   流程跑通
487
488
489
                  <div class="feature-icon">🛍️</div>
                  <div class="feature-title">懂商品</div>
                  <div>深度理解店铺内所有商品,智能匹配你的需求</div>
e7f2b240   tangwang   first commit
490
491
492
493
494
495
496
497
498
              </div>
              """,
              unsafe_allow_html=True,
          )
  
      with col3:
          st.markdown(
              """
              <div class="feature-card">
01b46131   tangwang   流程跑通
499
500
501
                  <div class="feature-icon">💭</div>
                  <div class="feature-title">贴心</div>
                  <div>任意聊</div>
e7f2b240   tangwang   first commit
502
503
504
505
506
507
508
509
510
              </div>
              """,
              unsafe_allow_html=True,
          )
  
      with col4:
          st.markdown(
              """
              <div class="feature-card">
01b46131   tangwang   流程跑通
511
512
513
                  <div class="feature-icon">👗</div>
                  <div class="feature-title">懂时尚</div>
                  <div>穿搭顾问 + 轻松对比</div>
e7f2b240   tangwang   first commit
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
              </div>
              """,
              unsafe_allow_html=True,
          )
  
      st.markdown("<br><br>", unsafe_allow_html=True)
  
  
  def main():
      """Main Streamlit app"""
      initialize_session()
  
      # Header
      st.markdown(
          """
          <div class="app-header">
bad17b15   tangwang   调通baseline
530
              <div class="app-title">👗 ShopAgent</div>
e7f2b240   tangwang   first commit
531
532
533
534
535
536
537
538
539
540
              <div class="app-subtitle">AI Fashion Shopping Assistant</div>
          </div>
          """,
          unsafe_allow_html=True,
      )
  
      # Sidebar (collapsed by default, but accessible)
      with st.sidebar:
          st.markdown("### ⚙️ Settings")
  
825828c4   tangwang   fix: search image...
541
          if st.button("🗑️ Clear Chat", width="stretch"):
e7f2b240   tangwang   first commit
542
543
              if "shopping_agent" in st.session_state:
                  st.session_state.shopping_agent.clear_history()
66442668   tangwang   feat: 搜索结果引用与并行搜索...
544
545
546
547
              # Clear search result registry for this session
              session_id = st.session_state.get("session_id", "")
              if session_id:
                  global_registry.clear_session(session_id)
e7f2b240   tangwang   first commit
548
549
550
551
              st.session_state.messages = []
              st.session_state.uploaded_image = None
              st.rerun()
  
01b46131   tangwang   流程跑通
552
553
554
555
556
          # Debug toggle
          st.markdown("---")
          st.checkbox(
              "显示调试过程 (debug)",
              key="show_debug",
66442668   tangwang   feat: 搜索结果引用与并行搜索...
557
              value=True,
01b46131   tangwang   流程跑通
558
559
560
              help="展开后可查看中间思考过程及工具调用详情",
          )
  
e7f2b240   tangwang   first commit
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
          st.markdown("---")
          st.caption(f"Session: `{st.session_state.session_id[:8]}...`")
  
      # Chat messages container
      messages_container = st.container()
  
      with messages_container:
          if not st.session_state.messages:
              display_welcome()
          else:
              for message in st.session_state.messages:
                  display_message(message)
  
      # Fixed input area at bottom (using container to simulate fixed position)
      st.markdown('<div class="fixed-input-container">', unsafe_allow_html=True)
  
      input_container = st.container()
  
      with input_container:
          # Image upload area (shown when + is clicked)
          if st.session_state.show_image_upload:
              uploaded_file = st.file_uploader(
                  "Choose an image",
                  type=["jpg", "jpeg", "png"],
                  key="file_uploader",
              )
  
              if uploaded_file:
                  st.session_state.uploaded_image = uploaded_file
                  # Show preview
                  col1, col2 = st.columns([1, 4])
                  with col1:
                      img = Image.open(uploaded_file)
                      st.image(img, width=100)
                  with col2:
                      if st.button("❌ Remove"):
                          st.session_state.uploaded_image = None
                          st.session_state.show_image_upload = False
                          st.rerun()
  
          # Input row
          col1, col2 = st.columns([1, 12])
  
          with col1:
              # Image upload toggle button
825828c4   tangwang   fix: search image...
606
              if st.button("➕", help="Add image", width="stretch"):
e7f2b240   tangwang   first commit
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
                  st.session_state.show_image_upload = (
                      not st.session_state.show_image_upload
                  )
                  st.rerun()
  
          with col2:
              # Text input
              user_query = st.chat_input(
                  "Ask about fashion products...",
                  key="chat_input",
              )
  
      st.markdown("</div>", unsafe_allow_html=True)
  
      # Process user input
      if user_query:
          # Ensure shopping agent is initialized
          if "shopping_agent" not in st.session_state:
              st.error("Session not initialized. Please refresh the page.")
              st.stop()
  
          # Save uploaded image if present, or get from recent history
          image_path = None
          if st.session_state.uploaded_image:
              # User explicitly uploaded an image for this query
              image_path = save_uploaded_image(st.session_state.uploaded_image)
          else:
              # Check if query refers to a previous image
              query_lower = user_query.lower()
              if any(
                  ref in query_lower
                  for ref in [
                      "this",
                      "that",
                      "the image",
                      "the shirt",
                      "the product",
                      "it",
                  ]
              ):
                  # Find the most recent message with an image
                  for msg in reversed(st.session_state.messages):
                      if msg.get("role") == "user" and msg.get("image_path"):
                          image_path = msg["image_path"]
                          logger.info(f"Using image from previous message: {image_path}")
                          break
  
          # Add user message
          st.session_state.messages.append(
              {
                  "role": "user",
                  "content": user_query,
                  "image_path": image_path,
              }
          )
  
          # Display user message immediately
          with messages_container:
              display_message(st.session_state.messages[-1])
  
          # Process with shopping agent
          try:
              shopping_agent = st.session_state.shopping_agent
              
66442668   tangwang   feat: 搜索结果引用与并行搜索...
671
              # Handle greetings without invoking the agent
e7f2b240   tangwang   first commit
672
              query_lower = user_query.lower().strip()
66442668   tangwang   feat: 搜索结果引用与并行搜索...
673
674
675
676
677
678
679
680
              # Process with agent
              result = shopping_agent.chat(
                  query=user_query,
                  image_path=image_path,
              )
              response = result["response"]
              tool_calls = result.get("tool_calls", [])
              debug_steps = result.get("debug_steps", [])
e7f2b240   tangwang   first commit
681
  
621b6925   tangwang   up
682
              # Add assistant message (store search_refs so refs resolve after rerun)
e7f2b240   tangwang   first commit
683
684
685
686
687
              st.session_state.messages.append(
                  {
                      "role": "assistant",
                      "content": response,
                      "tool_calls": tool_calls,
66442668   tangwang   feat: 搜索结果引用与并行搜索...
688
                      "debug_steps": debug_steps,
621b6925   tangwang   up
689
                      "search_refs": result.get("search_refs", {}),
e7f2b240   tangwang   first commit
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
                  }
              )
  
              # Clear uploaded image and hide upload area after sending
              st.session_state.uploaded_image = None
              st.session_state.show_image_upload = False
  
              # Auto-scroll to bottom with JavaScript
              st.markdown(
                  """
                  <script>
                  window.scrollTo(0, document.body.scrollHeight);
                  </script>
                  """,
                  unsafe_allow_html=True,
              )
  
          except Exception as e:
              logger.error(f"Error processing query: {e}", exc_info=True)
              error_msg = f"I apologize, I encountered an error: {str(e)}"
  
              st.session_state.messages.append(
                  {
                      "role": "assistant",
                      "content": error_msg,
                  }
              )
  
          # Rerun to update UI
          st.rerun()
  
  
  if __name__ == "__main__":
      main()