Skip to content

83. Fit Conversations into a Context Window

Difficulty: Hard · Topics: Data Prep for AI, Window Functions, Joins

Chat logs in messages (conv_id, turn, role, tokens) are turned into training examples for a model with a 1,000-token context window. Each conversation has one system message (turn 0); turn is unique within a conversation and larger is newer.

For every conversation keep the system message, then the newest messages that fit: walking back from the newest turn, keep a message while the system message plus every kept message add up to at most 1,000 tokens, and stop at the first one that does not fit (older turns are dropped even if they are small). Return the kept rows: conv_id, turn, role, tokens.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

messages

conv_idturnroletokens
10system200
11user300
12assistant400
13user150
14assistant220
20system100
21user50
22assistant60

Expected output

conv_idturnroletokens
12assistant400
13user150
14assistant220
21user50
22assistant60
10system200
20system100

Hints

Hint 1Order each conversation newest first and take a running sum of tokens: Window.partitionBy("conv_id").orderBy(F.col("turn").desc()) with rowsBetween(Window.unboundedPreceding, Window.currentRow).
Hint 2The system message counts toward the budget but is not part of the running sum: join each conversation's system tokens to its other messages first.
Hint 3Because tokens are positive, the running sum only grows, so "keep while it fits" is simply running + system <= 1000. Add the system rows back at the end with unionByName.

Learn the concepts

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance

Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice