@@ -134,6 +134,17 @@ def render_prompt_template(request, user_id, course_run_id, unit_usage_key, cour
134134 # error due to using too many tokens.
135135 UNIT_CONTENT_MAX_CHAR_LENGTH = getattr (settings , 'CHAT_COMPLETION_UNIT_CONTENT_MAX_CHAR_LENGTH' , 11750 )
136136
137+ # Calculate static content size by rendering template with empty unit_content
138+ course_data = get_cache_course_data (course_id , ['skill_names' , 'title' ])
139+ skill_names = course_data ['skill_names' ]
140+ title = course_data ['title' ]
141+
142+ template = Environment (loader = BaseLoader ).from_string (template_string )
143+ static_content = template .render (unit_content = "" , skill_names = skill_names , title = title )
144+ static_content_length = len (static_content )
145+
146+ adjusted_unit_limit = min (UNIT_CONTENT_MAX_CHAR_LENGTH , max (0 , 15000 - static_content_length ))
147+
137148 # --- Proportional trimming logic ---
138149 if isinstance (unit_content , list ):
139150 # Create a new list of dictionaries to hold trimmed content
@@ -156,7 +167,7 @@ def render_prompt_template(request, user_id, course_run_id, unit_usage_key, cour
156167 trimmed_unit_content .append ({"content_type" : ctype , "content_text" : "" })
157168 continue
158169
159- allowed_chars = max (1 , int ((len (text ) / total_chars ) * UNIT_CONTENT_MAX_CHAR_LENGTH ))
170+ allowed_chars = max (1 , int ((len (text ) / total_chars ) * adjusted_unit_limit ))
160171 trimmed_text = text [:allowed_chars ]
161172 trimmed_unit_content .append ({"content_type" : ctype , "content_text" : trimmed_text })
162173 current_length += len (trimmed_text )
@@ -166,13 +177,8 @@ def render_prompt_template(request, user_id, course_run_id, unit_usage_key, cour
166177
167178 else :
168179 # For non-list content, keep as string trimmed
169- unit_content = unit_content [0 :UNIT_CONTENT_MAX_CHAR_LENGTH ]
180+ unit_content = unit_content [0 :adjusted_unit_limit ]
170181
171- course_data = get_cache_course_data (course_id , ['skill_names' , 'title' ])
172- skill_names = course_data ['skill_names' ]
173- title = course_data ['title' ]
174-
175- template = Environment (loader = BaseLoader ).from_string (template_string )
176182 data = template .render (unit_content = unit_content , skill_names = skill_names , title = title )
177183
178184 return data
0 commit comments