pvanand commited on
Commit
190894a
1 Parent(s): 2927f33

Create document_generator_v2.py

Browse files
Files changed (1) hide show
  1. document_generator_v2.py +639 -0
document_generator_v2.py ADDED
@@ -0,0 +1,639 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File: prompts.py
2
+
3
+ DOCUMENT_OUTLINE_PROMPT_SYSTEM = """You are a document generator. Provide the outline of the document requested in <prompt></prompt> in JSON format.
4
+ Include sections and subsections if required. Use the "Content" field to provide a specific prompt or instruction for generating content for that particular section or subsection.
5
+ make sure the Sections follow a logical flow and each prompt's content does not overlap with other sections.
6
+ OUTPUT IN FOLLOWING JSON FORMAT enclosed in <output> tags
7
+ <output>
8
+ {
9
+ "Document": {
10
+ "Title": "Document Title",
11
+ "Author": "Author Name",
12
+ "Date": "YYYY-MM-DD",
13
+ "Version": "1.0",
14
+
15
+ "Sections": [
16
+ {
17
+ "SectionNumber": "1",
18
+ "Title": "Section Title",
19
+ "Content": "Specific prompt or instruction for generating content for this section",
20
+ "Subsections": [
21
+ {
22
+ "SectionNumber": "1.1",
23
+ "Title": "Subsection Title",
24
+ "Content": "Specific prompt or instruction for generating content for this subsection"
25
+ }
26
+ ]
27
+ }
28
+ ]
29
+ }
30
+ }
31
+ </output>"""
32
+
33
+ DOCUMENT_OUTLINE_PROMPT_USER = """<prompt>{query}</prompt>"""
34
+
35
+ DOCUMENT_SECTION_PROMPT_SYSTEM = """You are a document generator, You need to output only the content requested in the section in the prompt.
36
+ FORMAT YOUR OUTPUT AS MARKDOWN ENCLOSED IN <response></response> tags
37
+ <overall_objective>{overall_objective}</overall_objective>
38
+ <document_layout>{document_layout}</document_layout>"""
39
+
40
+ DOCUMENT_SECTION_PROMPT_USER = """<prompt>Output the content for the section "{section_or_subsection_title}" formatted as markdown. Follow this instruction: {content_instruction}</prompt>"""
41
+
42
+ ##########################################
43
+
44
+ DOCUMENT_TEMPLATE_OUTLINE_PROMPT_SYSTEM = """You are a document template generator. Provide the outline of the document requested in <prompt></prompt> in JSON format.
45
+ Include sections and subsections if required. Use the "Content" field to provide a specific prompt or instruction for generating template with placeholder text /example content for that particular section or subsection. Specify in each prompt to output as a template and use placeholder text/ tables as necessory.
46
+ make sure the Sections follow a logical flow and each prompt's content does not overlap with other sections.
47
+ OUTPUT IN FOLLOWING JSON FORMAT enclosed in <output> tags
48
+ <output>
49
+ {
50
+ "Document": {
51
+ "Title": "Document Title",
52
+ "Author": "Author Name",
53
+ "Date": "YYYY-MM-DD",
54
+ "Version": "1.0",
55
+
56
+ "Sections": [
57
+ {
58
+ "SectionNumber": "1",
59
+ "Title": "Section Title",
60
+ "Content": "Specific prompt or instruction for generating template for this section",
61
+ "Subsections": [
62
+ {
63
+ "SectionNumber": "1.1",
64
+ "Title": "Subsection Title",
65
+ "Content": "Specific prompt or instruction for generating template for this subsection"
66
+ }
67
+ ]
68
+ }
69
+ ]
70
+ }
71
+ }
72
+ </output>"""
73
+
74
+ DOCUMENT_TEMPLATE_PROMPT_USER = """<prompt>{query}</prompt>"""
75
+
76
+ DOCUMENT_TEMPLATE_SECTION_PROMPT_SYSTEM = """You are a document template generator,You need to output only the content requested in the section in the prompt, Use placeholder text/examples/tables wherever required.
77
+ FORMAT YOUR OUTPUT AS A TEMPLATE ENCLOSED IN <response></response> tags
78
+ <overall_objective>{overall_objective}</overall_objective>
79
+ <document_layout>{document_layout}</document_layout>"""
80
+
81
+ DOCUMENT_TEMPLATE_SECTION_PROMPT_USER = """<prompt>Output the content for the section "{section_or_subsection_title}" formatted as markdown. Follow this instruction: {content_instruction}</prompt>"""
82
+
83
+
84
+ # File: llm_observability.py
85
+
86
+ import sqlite3
87
+ import json
88
+ from datetime import datetime
89
+ from typing import Dict, Any, List, Optional
90
+
91
+ class LLMObservabilityManager:
92
+ def __init__(self, db_path: str = "llm_observability.db"):
93
+ self.db_path = db_path
94
+ self.create_table()
95
+
96
+ def create_table(self):
97
+ with sqlite3.connect(self.db_path) as conn:
98
+ cursor = conn.cursor()
99
+ cursor.execute('''
100
+ CREATE TABLE IF NOT EXISTS llm_observations (
101
+ id TEXT PRIMARY KEY,
102
+ conversation_id TEXT,
103
+ created_at DATETIME,
104
+ status TEXT,
105
+ request TEXT,
106
+ response TEXT,
107
+ model TEXT,
108
+ total_tokens INTEGER,
109
+ prompt_tokens INTEGER,
110
+ completion_tokens INTEGER,
111
+ latency FLOAT,
112
+ user TEXT
113
+ )
114
+ ''')
115
+
116
+ def insert_observation(self, response: Dict[str, Any], conversation_id: str, status: str, request: str, latency: float, user: str):
117
+ created_at = datetime.fromtimestamp(response['created'])
118
+
119
+ with sqlite3.connect(self.db_path) as conn:
120
+ cursor = conn.cursor()
121
+ cursor.execute('''
122
+ INSERT INTO llm_observations
123
+ (id, conversation_id, created_at, status, request, response, model, total_tokens, prompt_tokens, completion_tokens, latency, user)
124
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
125
+ ''', (
126
+ response['id'],
127
+ conversation_id,
128
+ created_at,
129
+ status,
130
+ request,
131
+ json.dumps(response['choices'][0]['message']),
132
+ response['model'],
133
+ response['usage']['total_tokens'],
134
+ response['usage']['prompt_tokens'],
135
+ response['usage']['completion_tokens'],
136
+ latency,
137
+ user
138
+ ))
139
+
140
+ def get_observations(self, conversation_id: Optional[str] = None) -> List[Dict[str, Any]]:
141
+ with sqlite3.connect(self.db_path) as conn:
142
+ cursor = conn.cursor()
143
+ if conversation_id:
144
+ cursor.execute('SELECT * FROM llm_observations WHERE conversation_id = ? ORDER BY created_at', (conversation_id,))
145
+ else:
146
+ cursor.execute('SELECT * FROM llm_observations ORDER BY created_at')
147
+ rows = cursor.fetchall()
148
+
149
+ column_names = [description[0] for description in cursor.description]
150
+ return [dict(zip(column_names, row)) for row in rows]
151
+
152
+ def get_all_observations(self) -> List[Dict[str, Any]]:
153
+ return self.get_observations()
154
+
155
+
156
+ # File: app.py
157
+ import os
158
+ import json
159
+ import re
160
+ import asyncio
161
+ import time
162
+ from typing import List, Dict, Optional, Any, Callable, Union
163
+ from openai import OpenAI
164
+ import logging
165
+ import functools
166
+ from fastapi import APIRouter, HTTPException, Request, UploadFile, File, Depends
167
+ from fastapi.responses import StreamingResponse
168
+ from pydantic import BaseModel
169
+ from fastapi_cache.decorator import cache
170
+ import psycopg2
171
+ from datetime import datetime
172
+ import base64
173
+ from fastapi import Form
174
+
175
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
176
+ logger = logging.getLogger(__name__)
177
+
178
+ def log_execution(func: Callable) -> Callable:
179
+ @functools.wraps(func)
180
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
181
+ logger.info(f"Executing {func.__name__}")
182
+ try:
183
+ result = func(*args, **kwargs)
184
+ logger.info(f"{func.__name__} completed successfully")
185
+ return result
186
+ except Exception as e:
187
+ logger.error(f"Error in {func.__name__}: {e}")
188
+ raise
189
+ return wrapper
190
+
191
+ # aiclient.py
192
+
193
+ class AIClient:
194
+ def __init__(self):
195
+ self.client = OpenAI(
196
+ base_url="https://openrouter.ai/api/v1",
197
+ api_key="sk-or-v1-" + os.environ['OPENROUTER_API_KEY']
198
+ )
199
+ self.observability_manager = LLMObservabilityManager()
200
+
201
+ @log_execution
202
+ def generate_response(
203
+ self,
204
+ messages: List[Dict[str, str]],
205
+ model: str = "openai/gpt-4o-mini",
206
+ max_tokens: int = 32000,
207
+ conversation_id: str = None,
208
+ user: str = "anonymous"
209
+ ) -> Optional[str]:
210
+ if not messages:
211
+ return None
212
+
213
+ start_time = time.time()
214
+ response = self.client.chat.completions.create(
215
+ model=model,
216
+ messages=messages,
217
+ max_tokens=max_tokens,
218
+ stream=False
219
+ )
220
+ end_time = time.time()
221
+ latency = end_time - start_time
222
+
223
+ # Log the observation
224
+ self.observability_manager.insert_observation(
225
+ response=response.dict(),
226
+ conversation_id=conversation_id or "default",
227
+ status="success",
228
+ request=json.dumps(messages),
229
+ latency=latency,
230
+ user=user
231
+ )
232
+
233
+ return response.choices[0].message.content
234
+
235
+ @log_execution
236
+ def generate_vision_response(
237
+ self,
238
+ messages: List[Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, str]]]]]]],
239
+ model: str = "google/gemini-flash-1.5-8b",
240
+ max_tokens: int = 32000,
241
+ conversation_id: str = None,
242
+ user: str = "anonymous"
243
+ ) -> Optional[str]:
244
+ if not messages:
245
+ return None
246
+
247
+ start_time = time.time()
248
+ response = self.client.chat.completions.create(
249
+ model=model,
250
+ messages=messages,
251
+ max_tokens=max_tokens,
252
+ stream=False
253
+ )
254
+ end_time = time.time()
255
+ latency = end_time - start_time
256
+
257
+ # Log the observation
258
+ self.observability_manager.insert_observation(
259
+ response=response.dict(),
260
+ conversation_id=conversation_id or "default",
261
+ status="success",
262
+ request=json.dumps(messages),
263
+ latency=latency,
264
+ user=user
265
+ )
266
+
267
+ return response.choices[0].message.content
268
+
269
+
270
+ class VisionTools:
271
+ def __init__(self, ai_client):
272
+ self.ai_client = ai_client
273
+
274
+ async def extract_images_info(self, images: List[UploadFile]) -> str:
275
+ try:
276
+ image_contents = []
277
+ for image in images:
278
+ image_content = await image.read()
279
+ base64_image = base64.b64encode(image_content).decode('utf-8')
280
+ image_contents.append({
281
+ "type": "image_url",
282
+ "image_url": {
283
+ "url": f"data:image/jpeg;base64,{base64_image}"
284
+ }
285
+ })
286
+
287
+ messages = [
288
+ {
289
+ "role": "user",
290
+ "content": [
291
+ {
292
+ "type": "text",
293
+ "text": "Extract the contents of these images in detail in a structured format, focusing on any text, tables, diagrams, or visual elements that might be relevant for document generation."
294
+ },
295
+ *image_contents
296
+ ]
297
+ }
298
+ ]
299
+
300
+ image_context = self.ai_client.generate_vision_response(messages)
301
+ return image_context
302
+ except Exception as e:
303
+ print(f"Error processing images: {str(e)}")
304
+ return ""
305
+
306
+
307
+ class DatabaseManager:
308
+ """Manages database operations."""
309
+
310
+ def __init__(self):
311
+ self.db_params = {
312
+ "dbname": "postgres",
313
+ "user": os.environ['SUPABASE_USER'],
314
+ "password": os.environ['SUPABASE_PASSWORD'],
315
+ "host": "aws-0-us-west-1.pooler.supabase.com",
316
+ "port": "5432"
317
+ }
318
+
319
+ @log_execution
320
+ def update_database(self, user_id: str, user_query: str, response: str) -> None:
321
+ with psycopg2.connect(**self.db_params) as conn:
322
+ with conn.cursor() as cur:
323
+ insert_query = """
324
+ INSERT INTO ai_document_generator (user_id, user_query, response)
325
+ VALUES (%s, %s, %s);
326
+ """
327
+ cur.execute(insert_query, (user_id, user_query, response))
328
+
329
+ class DocumentGenerator:
330
+ def __init__(self, ai_client: AIClient):
331
+ self.ai_client = ai_client
332
+ self.document_outline = None
333
+ self.content_messages = []
334
+
335
+ @staticmethod
336
+ def extract_between_tags(text: str, tag: str) -> str:
337
+ pattern = f"<{tag}>(.*?)</{tag}>"
338
+ match = re.search(pattern, text, re.DOTALL)
339
+ return match.group(1).strip() if match else ""
340
+
341
+ @staticmethod
342
+ def remove_duplicate_title(content: str, title: str, section_number: str) -> str:
343
+ patterns = [
344
+ rf"^#+\s*{re.escape(section_number)}(?:\s+|\s*:\s*|\.\s*){re.escape(title)}",
345
+ rf"^#+\s*{re.escape(title)}",
346
+ rf"^{re.escape(section_number)}(?:\s+|\s*:\s*|\.\s*){re.escape(title)}",
347
+ rf"^{re.escape(title)}",
348
+ ]
349
+
350
+ for pattern in patterns:
351
+ content = re.sub(pattern, "", content, flags=re.MULTILINE | re.IGNORECASE)
352
+
353
+ return content.lstrip()
354
+
355
+ @log_execution
356
+ def generate_document_outline(self, query: str, template: bool = False, image_context: str = "", max_retries: int = 3) -> Optional[Dict]:
357
+ messages = [
358
+ {"role": "system", "content": DOCUMENT_OUTLINE_PROMPT_SYSTEM if not template else DOCUMENT_TEMPLATE_OUTLINE_PROMPT_SYSTEM},
359
+ {"role": "user", "content": DOCUMENT_OUTLINE_PROMPT_USER.format(query=query) if not template else DOCUMENT_TEMPLATE_PROMPT_USER.format(query=query, image_context=image_context)}
360
+ ]
361
+ # Update user content to include image context if provided
362
+ if image_context:
363
+ messages[1]["content"] += f"<attached_images>\n\n{image_context}\n\n</attached_images>"
364
+
365
+ for attempt in range(max_retries):
366
+ outline_response = self.ai_client.generate_response(messages, model="openai/gpt-4o")
367
+ outline_json_text = self.extract_between_tags(outline_response, "output")
368
+
369
+ try:
370
+ self.document_outline = json.loads(outline_json_text)
371
+ return self.document_outline
372
+ except json.JSONDecodeError as e:
373
+ if attempt < max_retries - 1:
374
+ logger.warning(f"Failed to parse JSON (attempt {attempt + 1}): {e}")
375
+ logger.info("Retrying...")
376
+ else:
377
+ logger.error(f"Failed to parse JSON after {max_retries} attempts: {e}")
378
+ return None
379
+
380
+ @log_execution
381
+ def generate_content(self, title: str, content_instruction: str, section_number: str, template: bool = False) -> str:
382
+ SECTION_PROMPT_USER = DOCUMENT_SECTION_PROMPT_USER if not template else DOCUMENT_TEMPLATE_SECTION_PROMPT_USER
383
+ self.content_messages.append({
384
+ "role": "user",
385
+ "content": SECTION_PROMPT_USER.format(
386
+ section_or_subsection_title=title,
387
+ content_instruction=content_instruction
388
+ )
389
+ })
390
+ section_response = self.ai_client.generate_response(self.content_messages)
391
+ content = self.extract_between_tags(section_response, "response")
392
+ content = self.remove_duplicate_title(content, title, section_number)
393
+ self.content_messages.append({
394
+ "role": "assistant",
395
+ "content": section_response
396
+ })
397
+ return content
398
+
399
+ class MarkdownConverter:
400
+ @staticmethod
401
+ def slugify(text: str) -> str:
402
+ return re.sub(r'\W+', '-', text.lower())
403
+
404
+ @classmethod
405
+ def generate_toc(cls, sections: List[Dict]) -> str:
406
+ toc = "<div style='page-break-before: always;'></div>\n\n"
407
+ toc += "<h2 style='color: #2c3e50; text-align: center;'>Table of Contents</h2>\n\n"
408
+ toc += "<nav style='background-color: #f8f9fa; padding: 20px; border-radius: 5px; line-height: 1.6;'>\n\n"
409
+ for section in sections:
410
+ section_number = section['SectionNumber']
411
+ section_title = section['Title']
412
+ toc += f"<p><a href='#{cls.slugify(section_title)}' style='color: #3498db; text-decoration: none;'>{section_number}. {section_title}</a></p>\n\n"
413
+
414
+ for subsection in section.get('Subsections', []):
415
+ subsection_number = subsection['SectionNumber']
416
+ subsection_title = subsection['Title']
417
+ toc += f"<p style='margin-left: 20px;'><a href='#{cls.slugify(subsection_title)}' style='color: #2980b9; text-decoration: none;'>{subsection_number} {subsection_title}</a></p>\n\n"
418
+
419
+ toc += "</nav>\n\n"
420
+ return toc
421
+
422
+ @classmethod
423
+ def convert_to_markdown(cls, document: Dict) -> str:
424
+ markdown = "<div style='text-align: center; padding-top: 33vh;'>\n\n"
425
+ markdown += f"<h1 style='color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; display: inline-block;'>{document['Title']}</h1>\n\n"
426
+ markdown += f"<p style='color: #7f8c8d;'><em>By {document['Author']}</em></p>\n\n"
427
+ markdown += f"<p style='color: #95a5a6;'>Version {document['Version']} | {document['Date']}</p>\n\n"
428
+ markdown += "</div>\n\n"
429
+
430
+ markdown += cls.generate_toc(document['Sections'])
431
+
432
+ markdown += "<div style='max-width: 800px; margin: 0 auto; font-family: \"Segoe UI\", Arial, sans-serif; line-height: 1.6;'>\n\n"
433
+
434
+ for section in document['Sections']:
435
+ markdown += "<div style='page-break-before: always;'></div>\n\n"
436
+ section_number = section['SectionNumber']
437
+ section_title = section['Title']
438
+ markdown += f"<h2 id='{cls.slugify(section_title)}' style='color: #2c3e50; border-bottom: 1px solid #bdc3c7; padding-bottom: 5px;'>{section_number}. {section_title}</h2>\n\n"
439
+ markdown += f"<div style='color: #34495e; margin-bottom: 20px;'>\n\n{section['Content']}\n\n</div>\n\n"
440
+
441
+ for subsection in section.get('Subsections', []):
442
+ subsection_number = subsection['SectionNumber']
443
+ subsection_title = subsection['Title']
444
+ markdown += f"<h3 id='{cls.slugify(subsection_title)}' style='color: #34495e;'>{subsection_number} {subsection_title}</h3>\n\n"
445
+ markdown += f"<div style='color: #34495e; margin-bottom: 20px;'>\n\n{subsection['Content']}\n\n</div>\n\n"
446
+
447
+ markdown += "</div>"
448
+ return markdown
449
+
450
+ router = APIRouter()
451
+
452
+ class JsonDocumentResponse(BaseModel):
453
+ json_document: Dict
454
+
455
+ # class JsonDocumentRequest(BaseModel):
456
+ # query: str
457
+ # template: bool = False
458
+ # images: Optional[List[UploadFile]] = File(None)
459
+ # documents: Optional[List[UploadFile]] = File(None)
460
+ # conversation_id: str = ""
461
+
462
+ class MarkdownDocumentRequest(BaseModel):
463
+ json_document: Dict
464
+ query: str
465
+
466
+ MESSAGE_DELIMITER = b"\n---DELIMITER---\n"
467
+
468
+ def yield_message(message):
469
+ message_json = json.dumps(message, ensure_ascii=False).encode('utf-8')
470
+ return message_json + MESSAGE_DELIMITER
471
+
472
+ async def generate_document_stream(document_generator: DocumentGenerator, document_outline: Dict, query: str, template: bool = False):
473
+ document_generator.document_outline = document_outline
474
+ db_manager = DatabaseManager()
475
+ overall_objective = query
476
+ document_layout = json.dumps(document_generator.document_outline, indent=2)
477
+
478
+ SECTION_PROMPT_SYSTEM = DOCUMENT_SECTION_PROMPT_SYSTEM if not template else DOCUMENT_TEMPLATE_SECTION_PROMPT_SYSTEM
479
+ document_generator.content_messages = [
480
+ {
481
+ "role": "system",
482
+ "content": SECTION_PROMPT_SYSTEM.format(
483
+ overall_objective=overall_objective,
484
+ document_layout=document_layout
485
+ )
486
+ }
487
+ ]
488
+
489
+ for section in document_generator.document_outline["Document"].get("Sections", []):
490
+ section_title = section.get("Title", "")
491
+ section_number = section.get("SectionNumber", "")
492
+ content_instruction = section.get("Content", "")
493
+ logging.info(f"Generating content for section: {section_title}")
494
+ content = document_generator.generate_content(section_title, content_instruction, section_number, template)
495
+ section["Content"] = content
496
+ yield yield_message({
497
+ "type": "document_section",
498
+ "content": {
499
+ "section_number": section_number,
500
+ "section_title": section_title,
501
+ "content": content
502
+ }
503
+ })
504
+
505
+ for subsection in section.get("Subsections", []):
506
+ subsection_title = subsection.get("Title", "")
507
+ subsection_number = subsection.get("SectionNumber", "")
508
+ subsection_content_instruction = subsection.get("Content", "")
509
+ logging.info(f"Generating content for subsection: {subsection_title}")
510
+ content = document_generator.generate_content(subsection_title, subsection_content_instruction, subsection_number, template)
511
+ subsection["Content"] = content
512
+ yield yield_message({
513
+ "type": "document_section",
514
+ "content": {
515
+ "section_number": subsection_number,
516
+ "section_title": subsection_title,
517
+ "content": content
518
+ }
519
+ })
520
+
521
+ markdown_document = MarkdownConverter.convert_to_markdown(document_generator.document_outline["Document"])
522
+
523
+ yield yield_message({
524
+ "type": "complete_document",
525
+ "content": {
526
+ "markdown": markdown_document,
527
+ "json": document_generator.document_outline
528
+ },
529
+ });
530
+
531
+ db_manager.update_database("elevatics", query, markdown_document)
532
+
533
+ @router.post("/generate-document/markdown-stream")
534
+ async def generate_markdown_document_stream_endpoint(request: MarkdownDocumentRequest):
535
+ ai_client = AIClient()
536
+ document_generator = DocumentGenerator(ai_client)
537
+
538
+ async def stream_generator():
539
+ try:
540
+ async for chunk in generate_document_stream(document_generator, request.json_document, request.query, request.template):
541
+ yield chunk
542
+ except Exception as e:
543
+ yield yield_message({
544
+ "type": "error",
545
+ "content": str(e)
546
+ })
547
+
548
+ return StreamingResponse(stream_generator(), media_type="application/octet-stream")
549
+
550
+
551
+ @cache(expire=600*24*7)
552
+ @router.post("/generate-document/json", response_model=JsonDocumentResponse)
553
+ async def generate_document_outline_endpoint(
554
+ query: str = Form(...),
555
+ template: bool = Form(False),
556
+ conversation_id: str = Form(...),
557
+ images: Optional[List[UploadFile]] = File(None),
558
+ documents: Optional[List[UploadFile]] = File(None)
559
+ ):
560
+ ai_client = AIClient()
561
+ document_generator = DocumentGenerator(ai_client)
562
+ vision_tools = VisionTools(ai_client)
563
+
564
+ try:
565
+ image_context = ""
566
+ if images:
567
+ image_context = await vision_tools.extract_images_info(images)
568
+
569
+ json_document = document_generator.generate_document_outline(
570
+ query,
571
+ template,
572
+ image_context=image_context
573
+ )
574
+
575
+ if json_document is None:
576
+ raise HTTPException(status_code=500, detail="Failed to generate a valid document outline")
577
+
578
+ return JsonDocumentResponse(json_document=json_document)
579
+ except Exception as e:
580
+ raise HTTPException(status_code=500, detail=str(e))
581
+
582
+
583
+
584
+ ## OBSERVABILITY
585
+ from uuid import uuid4
586
+ import csv
587
+ from io import StringIO
588
+
589
+ class ObservationResponse(BaseModel):
590
+ observations: List[Dict]
591
+
592
+ def create_csv_response(observations: List[Dict]) -> StreamingResponse:
593
+ def iter_csv(data):
594
+ output = StringIO()
595
+ writer = csv.DictWriter(output, fieldnames=data[0].keys() if data else [])
596
+ writer.writeheader()
597
+ for row in data:
598
+ writer.writerow(row)
599
+ output.seek(0)
600
+ yield output.read()
601
+
602
+ headers = {
603
+ 'Content-Disposition': 'attachment; filename="observations.csv"'
604
+ }
605
+ return StreamingResponse(iter_csv(observations), media_type="text/csv", headers=headers)
606
+
607
+
608
+ @router.get("/last-observations/{limit}")
609
+ async def get_last_observations(limit: int = 10, format: str = "json"):
610
+ observability_manager = LLMObservabilityManager()
611
+
612
+ try:
613
+ # Get all observations, sorted by created_at in descending order
614
+ all_observations = observability_manager.get_observations()
615
+ all_observations.sort(key=lambda x: x['created_at'], reverse=True)
616
+
617
+ # Get the last conversation_id
618
+ if all_observations:
619
+ last_conversation_id = all_observations[0]['conversation_id']
620
+
621
+ # Filter observations for the last conversation
622
+ last_conversation_observations = [
623
+ obs for obs in all_observations
624
+ if obs['conversation_id'] == last_conversation_id
625
+ ][:limit]
626
+
627
+ if format.lower() == "csv":
628
+ return create_csv_response(last_conversation_observations)
629
+ else:
630
+ return ObservationResponse(observations=last_conversation_observations)
631
+ else:
632
+ if format.lower() == "csv":
633
+ return create_csv_response([])
634
+ else:
635
+ return ObservationResponse(observations=[])
636
+ except Exception as e:
637
+ raise HTTPException(status_code=500, detail=f"Failed to retrieve observations: {str(e)}")
638
+
639
+