Spaces:
Running
Running
File size: 18,417 Bytes
0289fc8 7a827cb 0289fc8 285b61b f162cbe 285b61b 0eba575 285b61b 0eba575 285b61b f162cbe 285b61b 0289fc8 db1b7b5 0289fc8 457ce08 f2ac68d 0289fc8 db1b7b5 0289fc8 e81c7e9 f2ac68d 0289fc8 db1b7b5 0289fc8 db1b7b5 0289fc8 f2ac68d 0289fc8 ff71d34 0289fc8 6ef6156 0289fc8 db1b7b5 0289fc8 db1b7b5 0289fc8 db1b7b5 0289fc8 285b61b 0289fc8 285b61b 0289fc8 db1b7b5 0289fc8 285b61b 0289fc8 285b61b 0289fc8 db1b7b5 0289fc8 6ef6156 bf1f3eb 285b61b bbc3205 28370e2 0289fc8 28370e2 6ef6156 285b61b 6ef6156 60c3069 285b61b db1b7b5 f2ac68d db1b7b5 285b61b db1b7b5 285b61b db1b7b5 285b61b db1b7b5 60c3069 61925fa db1b7b5 60c3069 db1b7b5 285b61b db1b7b5 60c3069 61925fa db1b7b5 60c3069 db1b7b5 60c3069 61925fa 60c3069 bb1bb0e f2ac68d 3c03878 60c3069 443d394 28370e2 6ef6156 0289fc8 6ef6156 0289fc8 285b61b 6ef6156 28370e2 db1b7b5 28370e2 6ef6156 db1b7b5 5e2ed5c 285b61b db1b7b5 5e2ed5c 60c3069 61925fa 60c3069 db1b7b5 60c3069 5e2ed5c db1b7b5 e3cfbf6 6ef6156 a4040f1 6ef6156 a4040f1 e3cfbf6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
# File: prompts.py
DOCUMENT_OUTLINE_PROMPT_SYSTEM = """You are a document generator. Provide the outline of the document requested in <prompt></prompt> in JSON format.
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.
make sure the Sections follow a logical flow and each prompt's content does not overlap with other sections.
OUTPUT IN FOLLOWING JSON FORMAT enclosed in <output> tags
<output>
{
"Document": {
"Title": "Document Title",
"Author": "Author Name",
"Date": "YYYY-MM-DD",
"Version": "1.0",
"Sections": [
{
"SectionNumber": "1",
"Title": "Section Title",
"Content": "Specific prompt or instruction for generating content for this section",
"Subsections": [
{
"SectionNumber": "1.1",
"Title": "Subsection Title",
"Content": "Specific prompt or instruction for generating content for this subsection"
}
]
}
]
}
}
</output>"""
DOCUMENT_OUTLINE_PROMPT_USER = """<prompt>{query}</prompt>"""
DOCUMENT_SECTION_PROMPT_SYSTEM = """You are a document generator, You need to output only the content requested in the section in the prompt.
FORMAT YOUR OUTPUT AS MARKDOWN ENCLOSED IN <response></response> tags
<overall_objective>{overall_objective}</overall_objective>
<document_layout>{document_layout}</document_layout>"""
DOCUMENT_SECTION_PROMPT_USER = """<prompt>Output the content for the section "{section_or_subsection_title}" formatted as markdown. Follow this instruction: {content_instruction}</prompt>"""
##########################################
DOCUMENT_TEMPLATE_OUTLINE_PROMPT_SYSTEM = """You are a document template generator. Provide the outline of the document requested in <prompt></prompt> in JSON format.
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 use either placeholder text/example
make sure the Sections follow a logical flow and each prompt's content does not overlap with other sections.
OUTPUT IN FOLLOWING JSON FORMAT enclosed in <output> tags
<output>
{
"Document": {
"Title": "Document Title",
"Author": "Author Name",
"Date": "YYYY-MM-DD",
"Version": "1.0",
"Sections": [
{
"SectionNumber": "1",
"Title": "Section Title",
"Content": "Specific prompt or instruction for generating template for this section",
"Subsections": [
{
"SectionNumber": "1.1",
"Title": "Subsection Title",
"Content": "Specific prompt or instruction for generating template for this subsection"
}
]
}
]
}
}
</output>"""
DOCUMENT_TEMPLATE_PROMPT_USER = """<prompt>{query}</prompt>"""
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 wherever required.
FORMAT YOUR OUTPUT AS MARKDOWN ENCLOSED IN <response></response> tags
<overall_objective>{overall_objective}</overall_objective>
<document_layout>{document_layout}</document_layout>"""
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>"""
# File: app.py
import os
import json
import re
import asyncio
import time
from typing import List, Dict, Optional, Any, Callable
from openai import OpenAI
import logging
import functools
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from fastapi_cache.decorator import cache
import psycopg2
from datetime import datetime
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def log_execution(func: Callable) -> Callable:
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
logger.info(f"Executing {func.__name__}")
try:
result = func(*args, **kwargs)
logger.info(f"{func.__name__} completed successfully")
return result
except Exception as e:
logger.error(f"Error in {func.__name__}: {e}")
raise
return wrapper
class DatabaseManager:
"""Manages database operations."""
def __init__(self):
self.db_params = {
"dbname": "postgres",
"user": os.environ['SUPABASE_USER'],
"password": os.environ['SUPABASE_PASSWORD'],
"host": "aws-0-us-west-1.pooler.supabase.com",
"port": "5432"
}
@log_execution
def update_database(self, user_id: str, user_query: str, response: str) -> None:
with psycopg2.connect(**self.db_params) as conn:
with conn.cursor() as cur:
insert_query = """
INSERT INTO ai_document_generator (user_id, user_query, response)
VALUES (%s, %s, %s);
"""
cur.execute(insert_query, (user_id, user_query, response))
class AIClient:
def __init__(self):
self.client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key="sk-or-v1-"+os.environ['OPENROUTER_API_KEY']
)
@log_execution
def generate_response(
self,
messages: List[Dict[str, str]],
model: str = "openai/gpt-4o-mini",
max_tokens: int = 32000
) -> Optional[str]:
if not messages:
return None
response = self.client.chat.completions.create(
model=model,
messages=messages,
max_tokens=max_tokens,
stream=False
)
return response.choices[0].message.content
class DocumentGenerator:
def __init__(self, ai_client: AIClient):
self.ai_client = ai_client
self.document_outline = None
self.content_messages = []
@staticmethod
def extract_between_tags(text: str, tag: str) -> str:
pattern = f"<{tag}>(.*?)</{tag}>"
match = re.search(pattern, text, re.DOTALL)
return match.group(1).strip() if match else ""
@staticmethod
def remove_duplicate_title(content: str, title: str, section_number: str) -> str:
patterns = [
rf"^#+\s*{re.escape(section_number)}(?:\s+|\s*:\s*|\.\s*){re.escape(title)}",
rf"^#+\s*{re.escape(title)}",
rf"^{re.escape(section_number)}(?:\s+|\s*:\s*|\.\s*){re.escape(title)}",
rf"^{re.escape(title)}",
]
for pattern in patterns:
content = re.sub(pattern, "", content, flags=re.MULTILINE | re.IGNORECASE)
return content.lstrip()
@log_execution
def generate_document_outline(self, query: str, template: bool = False, max_retries: int = 3) -> Optional[Dict]:
messages = [
{"role": "system", "content": DOCUMENT_OUTLINE_PROMPT_SYSTEM if not template else DOCUMENT_TEMPLATE_OUTLINE_PROMPT_SYSTEM},
{"role": "user", "content": DOCUMENT_OUTLINE_PROMPT_USER.format(query=query) if not template else DOCUMENT_TEMPLATE_PROMPT_USER.format(query=query)}
]
for attempt in range(max_retries):
outline_response = self.ai_client.generate_response(messages, model="openai/gpt-4o")
outline_json_text = self.extract_between_tags(outline_response, "output")
try:
self.document_outline = json.loads(outline_json_text)
return self.document_outline
except json.JSONDecodeError as e:
if attempt < max_retries - 1:
logger.warning(f"Failed to parse JSON (attempt {attempt + 1}): {e}")
logger.info("Retrying...")
else:
logger.error(f"Failed to parse JSON after {max_retries} attempts: {e}")
return None
@log_execution
def generate_content(self, title: str, content_instruction: str, section_number: str, template: bool = False) -> str:
SECTION_PROMPT_USER = DOCUMENT_SECTION_PROMPT_USER if not template else DOCUMENT_TEMPLATE_SECTION_PROMPT_USER
self.content_messages.append({
"role": "user",
"content": SECTION_PROMPT_USER.format(
section_or_subsection_title=title,
content_instruction=content_instruction
)
})
section_response = self.ai_client.generate_response(self.content_messages)
content = self.extract_between_tags(section_response, "response")
content = self.remove_duplicate_title(content, title, section_number)
self.content_messages.append({
"role": "assistant",
"content": section_response
})
return content
class MarkdownConverter:
@staticmethod
def slugify(text: str) -> str:
return re.sub(r'\W+', '-', text.lower())
@classmethod
def generate_toc(cls, sections: List[Dict]) -> str:
toc = "<div style='page-break-before: always;'></div>\n\n"
toc += "<h2 style='color: #2c3e50; text-align: center;'>Table of Contents</h2>\n\n"
toc += "<nav style='background-color: #f8f9fa; padding: 20px; border-radius: 5px; line-height: 1.6;'>\n\n"
for section in sections:
section_number = section['SectionNumber']
section_title = section['Title']
toc += f"<p><a href='#{cls.slugify(section_title)}' style='color: #3498db; text-decoration: none;'>{section_number}. {section_title}</a></p>\n\n"
for subsection in section.get('Subsections', []):
subsection_number = subsection['SectionNumber']
subsection_title = subsection['Title']
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"
toc += "</nav>\n\n"
return toc
@classmethod
def convert_to_markdown(cls, document: Dict) -> str:
markdown = "<div style='text-align: center; padding-top: 33vh;'>\n\n"
markdown += f"<h1 style='color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; display: inline-block;'>{document['Title']}</h1>\n\n"
markdown += f"<p style='color: #7f8c8d;'><em>By {document['Author']}</em></p>\n\n"
markdown += f"<p style='color: #95a5a6;'>Version {document['Version']} | {document['Date']}</p>\n\n"
markdown += "</div>\n\n"
markdown += cls.generate_toc(document['Sections'])
markdown += "<div style='max-width: 800px; margin: 0 auto; font-family: \"Segoe UI\", Arial, sans-serif; line-height: 1.6;'>\n\n"
for section in document['Sections']:
markdown += "<div style='page-break-before: always;'></div>\n\n"
section_number = section['SectionNumber']
section_title = section['Title']
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"
markdown += f"<div style='color: #34495e; margin-bottom: 20px;'>\n\n{section['Content']}\n\n</div>\n\n"
for subsection in section.get('Subsections', []):
subsection_number = subsection['SectionNumber']
subsection_title = subsection['Title']
markdown += f"<h3 id='{cls.slugify(subsection_title)}' style='color: #34495e;'>{subsection_number} {subsection_title}</h3>\n\n"
markdown += f"<div style='color: #34495e; margin-bottom: 20px;'>\n\n{subsection['Content']}\n\n</div>\n\n"
markdown += "</div>"
return markdown
router = APIRouter()
class DocumentRequest(BaseModel):
query: str
template: bool = False
class JsonDocumentResponse(BaseModel):
json_document: Dict
class MarkdownDocumentRequest(BaseModel):
json_document: Dict
query: str
template: bool = False
MESSAGE_DELIMITER = b"\n---DELIMITER---\n"
def yield_message(message):
message_json = json.dumps(message, ensure_ascii=False).encode('utf-8')
return message_json + MESSAGE_DELIMITER
async def generate_document_stream(document_generator: DocumentGenerator, document_outline: Dict, query: str, template: bool = False):
document_generator.document_outline = document_outline
db_manager = DatabaseManager()
overall_objective = query
document_layout = json.dumps(document_generator.document_outline, indent=2)
SECTION_PROMPT_SYSTEM = DOCUMENT_SECTION_PROMPT_SYSTEM if not template else DOCUMENT_TEMPLATE_SECTION_PROMPT_SYSTEM
document_generator.content_messages = [
{
"role": "system",
"content": SECTION_PROMPT_SYSTEM.format(
overall_objective=overall_objective,
document_layout=document_layout
)
}
]
for section in document_generator.document_outline["Document"].get("Sections", []):
section_title = section.get("Title", "")
section_number = section.get("SectionNumber", "")
content_instruction = section.get("Content", "")
logging.info(f"Generating content for section: {section_title}")
content = document_generator.generate_content(section_title, content_instruction, section_number, template)
section["Content"] = content
yield yield_message({
"type": "document_section",
"content": {
"section_number": section_number,
"section_title": section_title,
"content": content
}
})
for subsection in section.get("Subsections", []):
subsection_title = subsection.get("Title", "")
subsection_number = subsection.get("SectionNumber", "")
subsection_content_instruction = subsection.get("Content", "")
logging.info(f"Generating content for subsection: {subsection_title}")
content = document_generator.generate_content(subsection_title, subsection_content_instruction, subsection_number, template)
subsection["Content"] = content
yield yield_message({
"type": "document_section",
"content": {
"section_number": subsection_number,
"section_title": subsection_title,
"content": content
}
})
markdown_document = MarkdownConverter.convert_to_markdown(document_generator.document_outline["Document"])
yield yield_message({
"type": "complete_document",
"content": {
"markdown": markdown_document,
"json": document_generator.document_outline
},
});
db_manager.update_database("elevatics", query, markdown_document)
@cache(expire=600*24*7)
@router.post("/generate-document/json", response_model=JsonDocumentResponse)
async def generate_document_outline_endpoint(request: DocumentRequest):
ai_client = AIClient()
document_generator = DocumentGenerator(ai_client)
try:
json_document = document_generator.generate_document_outline(request.query, request.template)
if json_document is None:
raise HTTPException(status_code=500, detail="Failed to generate a valid document outline")
return JsonDocumentResponse(json_document=json_document)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/generate-document/markdown-stream")
async def generate_markdown_document_stream_endpoint(request: MarkdownDocumentRequest):
ai_client = AIClient()
document_generator = DocumentGenerator(ai_client)
async def stream_generator():
try:
async for chunk in generate_document_stream(document_generator, request.json_document, request.query, request.template):
yield chunk
except Exception as e:
yield yield_message({
"type": "error",
"content": str(e)
})
return StreamingResponse(stream_generator(), media_type="application/octet-stream")
###########################################
class MarkdownDocumentResponse(BaseModel):
markdown_document: str
@router.post("/generate-document-test", response_model=MarkdownDocumentResponse)
async def test_generate_document_endpoint(request: DocumentRequest):
try:
# Load JSON document from file
json_path = os.path.join("output/document_generator", "ai-chatbot-prd.json")
with open(json_path, "r") as json_file:
json_document = json.load(json_file)
# Load Markdown document from file
md_path = os.path.join("output/document_generator", "ai-chatbot-prd.md")
with open(md_path, "r") as md_file:
markdown_document = md_file.read()
return MarkdownDocumentResponse(markdown_document=markdown_document)
except FileNotFoundError:
raise HTTPException(status_code=404, detail="Test files not found")
except json.JSONDecodeError:
raise HTTPException(status_code=500, detail="Error parsing JSON file")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
class CacheTestResponse(BaseModel):
result: str
execution_time: float
@router.get("/test-cache/{test_id}", response_model=CacheTestResponse)
@cache(expire=60) # Cache for 1 minute
async def test_cache(test_id: int):
start_time = time.time()
# Simulate some time-consuming operation
await asyncio.sleep(2)
result = f"Test result for ID: {test_id}"
end_time = time.time()
execution_time = end_time - start_time
return CacheTestResponse(
result=result,
execution_time=execution_time
) |