mtyrrell commited on
Commit
3f4db57
·
1 Parent(s): bca8684

ts convo history

Browse files
Files changed (1) hide show
  1. app/utils.py +13 -12
app/utils.py CHANGED
@@ -178,7 +178,7 @@ def build_conversation_context(messages, max_turns: int = 3, max_chars: int = 80
178
  current_turn_messages = []
179
 
180
  # Process messages in reverse to get the most recent turns
181
- for msg in reversed(messages):
182
  # Skip if this is one of the first messages we already included
183
  if (first_user_msg and msg == first_user_msg) or (first_assistant_msg and msg == first_assistant_msg):
184
  continue
@@ -200,17 +200,18 @@ def build_conversation_context(messages, max_turns: int = 3, max_chars: int = 80
200
  char_count += msg_chars
201
  msgs_included += 1
202
 
203
- # Check if we've completed a turn (user message followed by assistant)
204
- if msg.role == 'user':
205
- # Look ahead to see if there's a corresponding assistant message
206
- # We need to check if the next message in the original order is an assistant
207
- msg_index = messages.index(msg)
208
- if msg_index + 1 < len(messages) and messages[msg_index + 1].role == 'assistant':
209
- # This is a complete turn, increment counter
210
- turn_count += 1
211
- if turn_count > max_turns:
212
- logger.info(f"Stopping context build: reached max_turns ({max_turns})")
213
- break
 
214
 
215
  logger.debug(f"Added {role_label} message ({msg_chars} chars, {msgs_included} total messages)")
216
 
 
178
  current_turn_messages = []
179
 
180
  # Process messages in reverse to get the most recent turns
181
+ for i, msg in enumerate(reversed(messages)):
182
  # Skip if this is one of the first messages we already included
183
  if (first_user_msg and msg == first_user_msg) or (first_assistant_msg and msg == first_assistant_msg):
184
  continue
 
200
  char_count += msg_chars
201
  msgs_included += 1
202
 
203
+ # Check if we've completed a turn (assistant message followed by user in reverse order)
204
+ if msg.role == 'assistant':
205
+ # Look ahead to see if there's a corresponding user message
206
+ # In reverse order, we expect: assistant, user, assistant, user...
207
+ if i + 1 < len(messages):
208
+ next_msg = list(reversed(messages))[i + 1]
209
+ if next_msg.role == 'user':
210
+ # This is a complete turn, increment counter
211
+ turn_count += 1
212
+ if turn_count >= max_turns:
213
+ logger.info(f"Stopping context build: reached max_turns ({max_turns})")
214
+ break
215
 
216
  logger.debug(f"Added {role_label} message ({msg_chars} chars, {msgs_included} total messages)")
217