zenivan commited on
Commit
4bc5e51
·
1 Parent(s): 98b7a0f

корректно добавляются ссылки на файлы при file search

Browse files
app/main_WS_FS_pure_test.py CHANGED
@@ -247,96 +247,92 @@ def generate_lesson_plan_interface(
247
 
248
  # plan_cut = cut_to_plan(full_text, marker="ПЛАН-КОНСПЕКТ")
249
 
250
- return full_text
251
 
252
- #### АННОТАЦИИ БЕЗ REASONING
253
- # 2. Получаем аннотации если есть
254
- # try:
255
- # annotations = response.output[1].content[0].annotations
256
- # except (AttributeError, IndexError):
257
- # annotations = []
258
- # logging.warning("Не найдены аннотации в ответе")
259
- #
260
- #### АННОТАЦИИ С REASONING
261
- # try:
262
- # # Ищем сообщение ассистента с аннотациями в response.output
263
- # annotations = []
264
- # for item in response.output:
265
- # if isinstance(item, ResponseOutputMessage) and item.role == "assistant":
266
- # for content_item in item.content:
267
- # if hasattr(content_item, 'annotations'):
268
- # annotations.extend(content_item.annotations)
269
- # break # Прерываем после первого найденного сообщения
270
- # except (AttributeError, IndexError, TypeError) as e:
271
- # annotations = []
272
- # logging.warning(f"Ошибка извлечения аннотаций: {str(e)}")
273
- #
274
- # # 3. Если есть аннотации - обрабатываем их
275
- # if annotations:
276
- # # Получаем список файлов из S3 (аналог file_references из первого проекта)
277
- # s3 = boto3.client(
278
- # 's3',
279
- # endpoint_url='https://s3.timeweb.cloud',
280
- # aws_access_key_id=os.getenv('S3_ACCESS_KEY'),
281
- # aws_secret_access_key=os.getenv('S3_SECRET_KEY'),
282
- # )
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  #
284
- # bucket_name = os.getenv('S3_BUCKET_NAME')
285
- # prefix = "KB_Logoped" # Измените на ваш префикс
 
 
 
 
 
 
 
 
286
  #
287
- # try:
288
- # response_s3 = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
289
- # file_references = {
290
- # obj['Key'].split('/')[-1]: obj['Key']
291
- # for obj in response_s3.get('Contents', [])
292
- # if obj['Key'].endswith('.pdf') or obj['Key'].endswith('.doc')
293
- # }
294
- # except ClientError as e:
295
- # logging.error(f"Ошибка доступа к S3: {str(e)}")
296
- # file_references = {}
297
- # БЕЗ REASONING
298
- # # Вставляем ссылки в текст (обратный порядок для сохранения позиций)
299
- # for ann in reversed(annotations):
300
- # filename = ann.filename
301
- # insert_pos = ann.index
302
- #
303
- # if filename in file_references:
304
- # url = generate_presigned_url(
305
- # bucket_name=bucket_name,
306
- # object_key=file_references[filename]
307
- # )
308
- # if url:
309
- # link_text = f" [📚 {filename}]({url})"
310
- # full_text = f"{full_text[:insert_pos]}{link_text}{full_text[insert_pos:]}"
311
- # else:
312
- # logging.warning(f"Файл {filename} не найден в S3")
313
- #
314
- # for ann in reversed(sorted(annotations, key=lambda x: x.index)):
315
- # filename = ann.filename
316
- # insert_pos = ann.index
317
- #
318
- # if filename in file_references:
319
- # url = generate_presigned_url(
320
- # bucket_name=bucket_name,
321
- # object_key=file_references[filename]
322
- # )
323
- # if url:
324
- # link_text = f" [📚 {filename}]({url})"
325
- # full_text = f"{full_text[:insert_pos]}{link_text}{full_text[insert_pos:]}"
326
-
327
- # # АННОТАЦИИ В ЛОГ
328
- # if annotations:
329
- # try:
330
- # content_block = response.output[1].content[0]
331
- # logging.info(f"=== ПОЛНЫЙ КОНТЕНТ БЛОКА ===")
332
- # logging.info(f"Тип: {content_block.type}")
333
- # logging.info(f"Текст: {content_block.text[:200]}...") # Первые 200 символов текста
334
- # logging.info(f"Аннотации: {content_block.annotations}")
335
- # logging.info(f"Сырые данные: {vars(content_block)}") # Вся техническая информация
336
- # except (IndexError, AttributeError) as e:
337
- # logging.warning(f"Не удалось получить аннотации: {str(e)}")
338
-
339
 
 
340
  ####### СТРИМИНГ
341
  # try:
342
  # for event in response:
 
247
 
248
  # plan_cut = cut_to_plan(full_text, marker="ПЛАН-КОНСПЕКТ")
249
 
 
250
 
251
+ # === ЛОГИКА ДОБАВЛЕНИЯ ССЫЛОК ===
252
+ if file_search and supports_reasoning:
253
+ #### Извлекаем аннотации (reasoning)
254
+ try:
255
+ # Ищем сообщение ассистента с аннотациями в response.output
256
+ annotations = []
257
+ for item in response.output:
258
+ if isinstance(item, ResponseOutputMessage) and item.role == "assistant":
259
+ for content_item in item.content:
260
+ if hasattr(content_item, 'annotations'):
261
+ annotations.extend(content_item.annotations)
262
+ break # Прерываем после первого найденного сообщения
263
+ except (AttributeError, IndexError, TypeError) as e:
264
+ annotations = []
265
+ logging.warning(f"Ошибка извлечения аннотаций: {str(e)}")
266
+
267
+ # 3. Если есть аннотации - обрабатываем их
268
+ if annotations:
269
+ # Получаем список файлов из S3 (аналог file_references из первого проекта)
270
+ s3 = boto3.client(
271
+ 's3',
272
+ endpoint_url='https://s3.timeweb.cloud',
273
+ aws_access_key_id=os.getenv('S3_ACCESS_KEY'),
274
+ aws_secret_access_key=os.getenv('S3_SECRET_KEY'),
275
+ )
276
+
277
+ bucket_name = os.getenv('S3_BUCKET_NAME')
278
+ prefix = "KB_Logoped"
279
+
280
+ try:
281
+ response_s3 = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
282
+ file_references = {
283
+ obj['Key'].split('/')[-1]: obj['Key']
284
+ for obj in response_s3.get('Contents', [])
285
+ if obj['Key'].endswith('.pdf') or obj['Key'].endswith('.doc')
286
+ }
287
+ except ClientError as e:
288
+ logging.error(f"Ошибка доступа к S3: {str(e)}")
289
+ file_references = {}
290
+ # БЕЗ REASONING
291
+ # # Вставляем ссылки в текст (обратный порядок для сохранения позиций)
292
+ # for ann in reversed(annotations):
293
+ # filename = ann.filename
294
+ # insert_pos = ann.index
295
  #
296
+ # if filename in file_references:
297
+ # url = generate_presigned_url(
298
+ # bucket_name=bucket_name,
299
+ # object_key=file_references[filename]
300
+ # )
301
+ # if url:
302
+ # link_text = f" [📚 {filename}]({url})"
303
+ # full_text = f"{full_text[:insert_pos]}{link_text}{full_text[insert_pos:]}"
304
+ # else:
305
+ # logging.warning(f"Файл {filename} не найден в S3")
306
  #
307
+ # Вставляем ссылки в текст
308
+ for ann in reversed(sorted(annotations, key=lambda x: x.index)):
309
+ filename = ann.filename
310
+ insert_pos = ann.index
311
+
312
+ if filename in file_references:
313
+ url = generate_presigned_url(
314
+ bucket_name=bucket_name,
315
+ object_key=file_references[filename]
316
+ )
317
+ if url:
318
+ link_text = f" [📚 {filename}]({url})"
319
+ full_text = f"{full_text[:insert_pos]}{link_text}{full_text[insert_pos:]}"
320
+ else:
321
+ logging.warning(f"Файл {filename} не найден в S3")
322
+
323
+ # # АННОТАЦИИ В ЛОГ
324
+ # if annotations:
325
+ # try:
326
+ # content_block = response.output[1].content[0]
327
+ # logging.info(f"=== ПОЛНЫЙ КОНТЕНТ БЛОКА ===")
328
+ # logging.info(f"Тип: {content_block.type}")
329
+ # logging.info(f"Текст: {content_block.text[:200]}...") # Первые 200 символов текста
330
+ # logging.info(f"Аннотации: {content_block.annotations}")
331
+ # logging.info(f"Сырые данные: {vars(content_block)}") # Вся техническая информация
332
+ # except (IndexError, AttributeError) as e:
333
+ # logging.warning(f"Не удалось получить аннотации: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
 
335
+ return full_text
336
  ####### СТРИМИНГ
337
  # try:
338
  # for event in response:
app/main_gradio_test_FS_test.py CHANGED
@@ -186,7 +186,7 @@ def generate_lesson_plan_interface(
186
 
187
  # 3. Если есть аннотации - обрабатываем их
188
  if annotations:
189
- # Получаем список файлов из S3 (аналог file_references из первого проекта)
190
  s3 = boto3.client(
191
  's3',
192
  endpoint_url='https://s3.timeweb.cloud',
 
186
 
187
  # 3. Если есть аннотации - обрабатываем их
188
  if annotations:
189
+ # Получаем список файлов из S3
190
  s3 = boto3.client(
191
  's3',
192
  endpoint_url='https://s3.timeweb.cloud',
log.md CHANGED
@@ -47,4 +47,12 @@ Reasoning-модель (o4-mini или gpt-4-turbo) умеет планиров
47
  платные подписки за web search / file search
48
  Но прежде они должны быть надежно-качественными
49
 
50
- Платные за web search / file search
 
 
 
 
 
 
 
 
 
47
  платные подписки за web search / file search
48
  Но прежде они должны быть надежно-качественными
49
 
50
+ Платные за web search / file search
51
+
52
+
53
+ 14.05
54
+
55
+ 4.1 - web search - no reasoning - ориентирована на точное следование инструкциям. Альтернатива - GPT-4o? o4?
56
+ o3-mini - file search - reasoning
57
+ 03-mino - no search - reasoning
58
+