tahamajs's picture
download
raw
33.5 kB
#!/usr/bin/env python3 """ Advanced Documentation and Help System with Gemini API This module provides sophisticated documentation and help capabilities for AI reasoning systems """ import os import asyncio import logging from typing import List, Dict, Any, Optional, Union, Callable from dataclasses import dataclass, field from abc import ABC, abstractmethod import json import time import markdown from enum import Enum from collections import defaultdict, deque import numpy as np from pathlib import Path import re from datetime import datetime import webbrowser import tempfile # LangChain imports from langchain_core.prompts import PromptTemplate from langchain_google_genai import ChatGoogleGenerativeAI # Google Generative AI import google.generativeai as genai # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class DocumentationType(Enum): """Types of documentation""" API_REFERENCE = "api_reference" USER_GUIDE = "user_guide" TUTORIAL = "tutorial" FAQ = "faq" TROUBLESHOOTING = "troubleshooting" EXAMPLES = "examples" CHANGELOG = "changelog" class HelpCategory(Enum): """Help categories""" GETTING_STARTED = "getting_started" BASIC_USAGE = "basic_usage" ADVANCED_FEATURES = "advanced_features" CONFIGURATION = "configuration" TROUBLESHOOTING = "troubleshooting" API_REFERENCE = "api_reference" EXAMPLES = "examples" @dataclass class DocumentationEntry: """Documentation entry structure""" entry_id: str title: str content: str doc_type: DocumentationType category: HelpCategory tags: List[str] = field(default_factory=list) created_at: float = field(default_factory=time.time) updated_at: float = field(default_factory=time.time) author: str = "system" version: str = "1.0.0" metadata: Dict[str, Any] = field(default_factory=dict) def to_dict(self) -> Dict[str, Any]: """Convert to dictionary""" return { "entry_id": self.entry_id, "title": self.title, "content": self.content, "doc_type": self.doc_type.value, "category": self.category.value, "tags": self.tags, "created_at": self.created_at, "updated_at": self.updated_at, "author": self.author, "version": self.version, "metadata": self.metadata, } @dataclass class HelpRequest: """Help request structure""" request_id: str user_query: str context: Dict[str, Any] = field(default_factory=dict) timestamp: float = field(default_factory=time.time) resolved: bool = False resolution: str = "" def to_dict(self) -> Dict[str, Any]: """Convert to dictionary""" return { "request_id": self.request_id, "user_query": self.user_query, "context": self.context, "timestamp": self.timestamp, "resolved": self.resolved, "resolution": self.resolution, } class DocumentationGenerator: """Generates documentation from code and specifications""" def __init__(self, config: Dict[str, Any] = None): self.config = config or {} self.api_key = os.getenv("GEMINI_API_KEY", "") self.llm = None if self.api_key: self.llm = ChatGoogleGenerativeAI( model="gemini-1.5-flash", google_api_key=self.api_key, temperature=0.3, max_output_tokens=2048, ) logger.info("Documentation Generator initialized") async def generate_api_documentation( self, code_content: str, class_name: str = None ) -> str: """Generate API documentation from code""" try: if not self.llm: return self._generate_basic_documentation(code_content) prompt = f""" Generate comprehensive API documentation for the following code: {code_content} Please provide: 1. Class/Function overview 2. Parameters and return types 3. Usage examples 4. Notes and warnings 5. Related functions/classes Format the output in Markdown. """ response = await asyncio.to_thread(self.llm.invoke, prompt) return response.content except Exception as e: logger.error(f"API documentation generation failed: {e}") return self._generate_basic_documentation(code_content) def _generate_basic_documentation(self, code_content: str) -> str: """Generate basic documentation without LLM""" lines = code_content.split("\n") doc_lines = [] # Extract class definitions classes = [] functions = [] for line in lines: if line.strip().startswith("class "): class_name = line.split("class ")[1].split("(")[0].split(":")[0].strip() classes.append(class_name) elif line.strip().startswith("def "): func_name = line.split("def ")[1].split("(")[0].strip() functions.append(func_name) doc_lines.append("# API Documentation") doc_lines.append("") if classes: doc_lines.append("## Classes") doc_lines.append("") for class_name in classes: doc_lines.append(f"### {class_name}") doc_lines.append("") doc_lines.append("A class for handling related functionality.") doc_lines.append("") if functions: doc_lines.append("## Functions") doc_lines.append("") for func_name in functions: doc_lines.append(f"### {func_name}()") doc_lines.append("") doc_lines.append("A function for performing specific operations.") doc_lines.append("") return "\n".join(doc_lines) async def generate_user_guide( self, topic: str, content_outline: List[str] = None ) -> str: """Generate user guide for a topic""" try: if not self.llm: return self._generate_basic_user_guide(topic) outline_text = "" if content_outline: outline_text = "\n".join([f"- {item}" for item in content_outline]) prompt = f""" Generate a comprehensive user guide for: {topic} Content outline: {outline_text} Please provide: 1. Introduction and overview 2. Prerequisites 3. Step-by-step instructions 4. Examples and use cases 5. Best practices 6. Troubleshooting tips Format the output in Markdown with clear headings and examples. """ response = await asyncio.to_thread(self.llm.invoke, prompt) return response.content except Exception as e: logger.error(f"User guide generation failed: {e}") return self._generate_basic_user_guide(topic) def _generate_basic_user_guide(self, topic: str) -> str: """Generate basic user guide without LLM""" return f"""# {topic} User Guide ## Introduction This guide provides instructions for using {topic}. ## Prerequisites - Basic understanding of the system - Required dependencies installed ## Getting Started 1. Initialize the system 2. Configure settings 3. Run basic operations ## Examples ```python # Basic usage example system = {topic}() result = system.process() ``` ## Troubleshooting - Check system requirements - Verify configuration - Review error messages ## Best Practices - Follow naming conventions - Handle errors gracefully - Use appropriate logging """ class HelpSystem: """Intelligent help system""" def __init__(self, config: Dict[str, Any] = None): self.config = config or {} self.api_key = os.getenv("GEMINI_API_KEY", "") self.llm = None if self.api_key: self.llm = ChatGoogleGenerativeAI( model="gemini-1.5-flash", google_api_key=self.api_key, temperature=0.3, max_output_tokens=2048, ) self.documentation_entries = {} self.help_requests = {} self.search_index = {} logger.info("Help System initialized") def add_documentation_entry(self, entry: DocumentationEntry): """Add documentation entry""" self.documentation_entries[entry.entry_id] = entry # Update search index self._update_search_index(entry) logger.info(f"Documentation entry '{entry.title}' added") def _update_search_index(self, entry: DocumentationEntry): """Update search index for documentation entry""" # Simple keyword extraction text = f"{entry.title} {entry.content}".lower() words = re.findall(r"\b\w+\b", text) for word in words: if len(word) > 2: # Skip short words if word not in self.search_index: self.search_index[word] = [] if entry.entry_id not in self.search_index[word]: self.search_index[word].append(entry.entry_id) async def search_documentation( self, query: str, limit: int = 5 ) -> List[DocumentationEntry]: """Search documentation""" try: query_words = re.findall(r"\b\w+\b", query.lower()) # Find matching entries matching_entries = set() for word in query_words: if word in self.search_index: matching_entries.update(self.search_index[word]) # Score and rank entries scored_entries = [] for entry_id in matching_entries: entry = self.documentation_entries[entry_id] score = self._calculate_relevance_score(entry, query) scored_entries.append((entry, score)) # Sort by score and return top results scored_entries.sort(key=lambda x: x[1], reverse=True) return [entry for entry, score in scored_entries[:limit]] except Exception as e: logger.error(f"Documentation search failed: {e}") return [] def _calculate_relevance_score( self, entry: DocumentationEntry, query: str ) -> float: """Calculate relevance score for documentation entry""" try: query_words = set(re.findall(r"\b\w+\b", query.lower())) entry_words = set( re.findall(r"\b\w+\b", f"{entry.title} {entry.content}".lower()) ) # Calculate word overlap overlap = len(query_words.intersection(entry_words)) total_query_words = len(query_words) if total_query_words == 0: return 0.0 # Base score from word overlap base_score = overlap / total_query_words # Boost score for title matches title_words = set(re.findall(r"\b\w+\b", entry.title.lower())) title_overlap = len(query_words.intersection(title_words)) if title_overlap > 0: base_score += 0.2 # Boost score for tag matches tag_words = set(re.findall(r"\b\w+\b", " ".join(entry.tags).lower())) tag_overlap = len(query_words.intersection(tag_words)) if tag_overlap > 0: base_score += 0.1 return min(1.0, base_score) except Exception as e: logger.error(f"Relevance score calculation failed: {e}") return 0.0 async def get_help_response( self, user_query: str, context: Dict[str, Any] = None ) -> Dict[str, Any]: """Get help response for user query""" try: # Search documentation relevant_entries = await self.search_documentation(user_query) # Generate response using LLM if available if self.llm and relevant_entries: response = await self._generate_llm_response( user_query, relevant_entries, context ) else: response = self._generate_basic_response(user_query, relevant_entries) # Log help request request_id = f"help_{int(time.time())}" help_request = HelpRequest( request_id=request_id, user_query=user_query, context=context or {}, resolved=bool(relevant_entries), ) self.help_requests[request_id] = help_request return { "request_id": request_id, "response": response, "relevant_docs": [entry.to_dict() for entry in relevant_entries], "success": True, } except Exception as e: logger.error(f"Help response generation failed: {e}") return { "response": "Sorry, I couldn't process your request. Please try again.", "success": False, "error": str(e), } async def _generate_llm_response( self, user_query: str, relevant_entries: List[DocumentationEntry], context: Dict[str, Any] = None, ) -> str: """Generate response using LLM""" try: # Prepare context context_text = "" if context: context_text = f"\nContext: {json.dumps(context, indent=2)}" # Prepare relevant documentation docs_text = "" for entry in relevant_entries: docs_text += f"\n## {entry.title}\n{entry.content}\n" prompt = f""" User Query: {user_query} {context_text} Relevant Documentation: {docs_text} Please provide a helpful response that: 1. Directly addresses the user's question 2. References relevant documentation 3. Provides clear examples if applicable 4. Suggests next steps if appropriate Keep the response concise and helpful. """ response = await asyncio.to_thread(self.llm.invoke, prompt) return response.content except Exception as e: logger.error(f"LLM response generation failed: {e}") return self._generate_basic_response(user_query, relevant_entries) def _generate_basic_response( self, user_query: str, relevant_entries: List[DocumentationEntry] ) -> str: """Generate basic response without LLM""" if not relevant_entries: return "I couldn't find relevant documentation for your query. Please try rephrasing your question or check the available documentation." response_parts = [] response_parts.append("Here's what I found:") for entry in relevant_entries: response_parts.append(f"\n## {entry.title}") response_parts.append( entry.content[:200] + "..." if len(entry.content) > 200 else entry.content ) return "\n".join(response_parts) def get_help_statistics(self) -> Dict[str, Any]: """Get help system statistics""" return { "total_documentation_entries": len(self.documentation_entries), "total_help_requests": len(self.help_requests), "resolved_requests": sum( 1 for req in self.help_requests.values() if req.resolved ), "documentation_categories": list( set( entry.category.value for entry in self.documentation_entries.values() ) ), "search_index_size": len(self.search_index), } class DocumentationRenderer: """Renders documentation in various formats""" def __init__(self): self.templates = {} self._load_default_templates() logger.info("Documentation Renderer initialized") def _load_default_templates(self): """Load default templates""" # HTML template self.templates[ "html" ] = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{title}</title> <style> body {{ font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; line-height: 1.6; }} h1, h2, h3 {{ color: #333; }} code {{ background-color: #f4f4f4; padding: 2px 4px; border-radius: 3px; }} pre {{ background-color: #f4f4f4; padding: 15px; border-radius: 5px; overflow-x: auto; }} .toc {{ background-color: #f9f9f9; padding: 15px; border-radius: 5px; margin-bottom: 20px; }} .metadata {{ color: #666; font-size: 0.9em; margin-bottom: 20px; }} </style> </head> <body> <h1>{title}</h1> <div class="metadata"> <p>Author: {author} | Version: {version} | Last Updated: {updated_at}</p> </div> <div class="toc"> <h3>Table of Contents</h3> {toc} </div> <div class="content"> {content} </div> </body> </html> """ def render_to_html(self, entry: DocumentationEntry) -> str: """Render documentation entry to HTML""" try: # Convert Markdown to HTML html_content = markdown.markdown(entry.content) # Generate table of contents toc = self._generate_toc(entry.content) # Format timestamp updated_at = datetime.fromtimestamp(entry.updated_at).strftime( "%Y-%m-%d %H:%M:%S" ) # Render template html = self.templates["html"].format( title=entry.title, author=entry.author, version=entry.version, updated_at=updated_at, toc=toc, content=html_content, ) return html except Exception as e: logger.error(f"HTML rendering failed: {e}") return f"<h1>{entry.title}</h1><p>Error rendering content: {str(e)}</p>" def _generate_toc(self, content: str) -> str: """Generate table of contents from content""" try: toc_items = [] lines = content.split("\n") for line in lines: if line.startswith("#"): level = len(line) - len(line.lstrip("#")) title = line.lstrip("#").strip() if title: toc_items.append( f"<li style='margin-left: {(level-1)*20}px'><a href='#{title.replace(' ', '-').lower()}'>{title}</a></li>" ) if toc_items: return f"<ul>{''.join(toc_items)}</ul>" else: return "<p>No headings found</p>" except Exception as e: logger.error(f"TOC generation failed: {e}") return "<p>Error generating table of contents</p>" def render_to_markdown(self, entry: DocumentationEntry) -> str: """Render documentation entry to Markdown""" try: markdown_content = f"""# {entry.title} **Author:** {entry.author} **Version:** {entry.version} **Last Updated:** {datetime.fromtimestamp(entry.updated_at).strftime("%Y-%m-%d %H:%M:%S")} **Category:** {entry.category.value} **Type:** {entry.doc_type.value} ## Content {entry.content} ## Tags {', '.join(entry.tags) if entry.tags else 'No tags'} ## Metadata ```json {json.dumps(entry.metadata, indent=2)} ``` """ return markdown_content except Exception as e: logger.error(f"Markdown rendering failed: {e}") return f"# {entry.title}\n\nError rendering content: {str(e)}" def save_to_file( self, entry: DocumentationEntry, file_path: str, format: str = "html" ): """Save documentation entry to file""" try: file_path = Path(file_path) file_path.parent.mkdir(parents=True, exist_ok=True) if format == "html": content = self.render_to_html(entry) with open(file_path, "w", encoding="utf-8") as f: f.write(content) elif format == "markdown": content = self.render_to_markdown(entry) with open(file_path, "w", encoding="utf-8") as f: f.write(content) else: raise ValueError(f"Unsupported format: {format}") logger.info(f"Documentation saved to {file_path}") return True except Exception as e: logger.error(f"File saving failed: {e}") return False def open_in_browser(self, entry: DocumentationEntry, format: str = "html"): """Open documentation in browser""" try: # Create temporary file with tempfile.NamedTemporaryFile( mode="w", suffix=f".{format}", delete=False ) as f: if format == "html": content = self.render_to_html(entry) elif format == "markdown": content = self.render_to_markdown(entry) else: raise ValueError(f"Unsupported format: {format}") f.write(content) temp_file = f.name # Open in browser webbrowser.open(f"file://{temp_file}") logger.info(f"Documentation opened in browser: {temp_file}") return temp_file except Exception as e: logger.error(f"Browser opening failed: {e}") return None class AdvancedDocumentationSystem: """Advanced documentation and help system""" def __init__(self, config: Dict[str, Any] = None): self.config = config or {} self.documentation_generator = DocumentationGenerator(config) self.help_system = HelpSystem(config) self.documentation_renderer = DocumentationRenderer() # Load default documentation self._load_default_documentation() logger.info("Advanced Documentation System initialized") def _load_default_documentation(self): """Load default documentation entries""" # Getting Started getting_started = DocumentationEntry( entry_id="getting_started", title="Getting Started", content="""# Getting Started Welcome to the Advanced AI Reasoning System! This guide will help you get up and running quickly. ## Prerequisites - Python 3.8 or higher - Gemini API key - Required dependencies installed ## Installation 1. Install the required packages: ```bash pip install -r requirements.txt ``` 2. Set your Gemini API key: ```bash export GEMINI_API_KEY="your-api-key-here" ``` ## Quick Start 1. Import the system: ```python from src.gemini_rag_system import GeminiRAGSystem, RAGConfig ``` 2. Configure the system: ```python config = RAGConfig( gemini_api_key="your-api-key", gemini_model="gemini-1.5-flash" ) ``` 3. Initialize and use: ```python rag_system = GeminiRAGSystem(config) result = rag_system.query("Your question here") ``` ## Next Steps - Explore the [API Reference](api_reference.md) - Check out [Examples](examples.md) - Read the [User Guide](user_guide.md) """, doc_type=DocumentationType.USER_GUIDE, category=HelpCategory.GETTING_STARTED, tags=["getting-started", "installation", "quick-start"], ) # API Reference api_reference = DocumentationEntry( entry_id="api_reference", title="API Reference", content="""# API Reference This document provides detailed information about the API components. ## Core Classes ### GeminiRAGSystem The main RAG system class. **Methods:** - `query(question: str)`: Query the RAG system - `build_knowledge_base(source)`: Build knowledge base from documents - `get_system_stats()`: Get system statistics ### RAGConfig Configuration class for the RAG system. **Parameters:** - `gemini_api_key`: Your Gemini API key - `gemini_model`: Model to use (default: "gemini-1.5-flash") - `temperature`: Temperature for generation (default: 0.7) - `vector_store_type`: Type of vector store (default: "faiss") - `embedding_model`: Embedding model to use (default: "google") ## Usage Examples ### Basic RAG Query ```python from src.gemini_rag_system import GeminiRAGSystem, RAGConfig config = RAGConfig(gemini_api_key="your-key") rag_system = GeminiRAGSystem(config) # Build knowledge base rag_system.build_knowledge_base("path/to/documents") # Query the system result = rag_system.query("What is artificial intelligence?") print(result["answer"]) ``` ### Advanced Configuration ```python config = RAGConfig( gemini_api_key="your-key", gemini_model="gemini-1.5-flash", temperature=0.5, vector_store_type="chroma", embedding_model="google", chunk_size=1000, top_k=5, enable_query_expansion=True ) ``` """, doc_type=DocumentationType.API_REFERENCE, category=HelpCategory.API_REFERENCE, tags=["api", "reference", "classes", "methods"], ) # FAQ faq = DocumentationEntry( entry_id="faq", title="Frequently Asked Questions", content="""# Frequently Asked Questions ## General Questions ### Q: What is this system? A: This is an advanced AI reasoning system that combines RAG (Retrieval-Augmented Generation) with Google's Gemini API for intelligent question answering and document processing. ### Q: What models are supported? A: The system supports various Gemini models including gemini-1.5-flash, gemini-1.5-pro, and others. ### Q: How do I get a Gemini API key? A: Visit the Google AI Studio (https://aistudio.google.com/) to get your API key. ## Technical Questions ### Q: What vector stores are supported? A: The system supports FAISS, Chroma, Pinecone, Weaviate, and Qdrant. ### Q: Can I use my own documents? A: Yes, the system supports various document formats including PDF, TXT, CSV, and JSON. ### Q: How do I improve performance? A: You can adjust parameters like chunk_size, top_k, and enable query expansion for better performance. ## Troubleshooting ### Q: I'm getting API key errors A: Make sure your GEMINI_API_KEY environment variable is set correctly. ### Q: The system is slow A: Try reducing chunk_size, using a faster model, or enabling caching. ### Q: I'm getting memory errors A: Reduce the number of documents or use a more efficient vector store. """, doc_type=DocumentationType.FAQ, category=HelpCategory.TROUBLESHOOTING, tags=["faq", "questions", "troubleshooting"], ) # Add entries to help system self.help_system.add_documentation_entry(getting_started) self.help_system.add_documentation_entry(api_reference) self.help_system.add_documentation_entry(faq) async def generate_documentation( self, topic: str, doc_type: DocumentationType, content_outline: List[str] = None ) -> DocumentationEntry: """Generate documentation for a topic""" try: # Generate content if doc_type == DocumentationType.API_REFERENCE: content = await self.documentation_generator.generate_api_documentation( topic ) else: content = await self.documentation_generator.generate_user_guide( topic, content_outline ) # Create documentation entry entry = DocumentationEntry( entry_id=f"doc_{int(time.time())}", title=topic, content=content, doc_type=doc_type, category=( HelpCategory.API_REFERENCE if doc_type == DocumentationType.API_REFERENCE else HelpCategory.USER_GUIDE ), tags=[topic.lower().replace(" ", "-")], ) # Add to help system self.help_system.add_documentation_entry(entry) return entry except Exception as e: logger.error(f"Documentation generation failed: {e}") return None async def get_help( self, user_query: str, context: Dict[str, Any] = None ) -> Dict[str, Any]: """Get help for user query""" return await self.help_system.get_help_response(user_query, context) def render_documentation(self, entry_id: str, format: str = "html") -> str: """Render documentation entry""" entry = self.help_system.documentation_entries.get(entry_id) if not entry: return f"Documentation entry '{entry_id}' not found" if format == "html": return self.documentation_renderer.render_to_html(entry) elif format == "markdown": return self.documentation_renderer.render_to_markdown(entry) else: return f"Unsupported format: {format}" def save_documentation( self, entry_id: str, file_path: str, format: str = "html" ) -> bool: """Save documentation to file""" entry = self.help_system.documentation_entries.get(entry_id) if not entry: return False return self.documentation_renderer.save_to_file(entry, file_path, format) def open_documentation(self, entry_id: str, format: str = "html") -> str: """Open documentation in browser""" entry = self.help_system.documentation_entries.get(entry_id) if not entry: return None return self.documentation_renderer.open_in_browser(entry, format) def get_system_stats(self) -> Dict[str, Any]: """Get system statistics""" return { "help_system_stats": self.help_system.get_help_statistics(), "total_documentation_entries": len(self.help_system.documentation_entries), "documentation_types": list( set( entry.doc_type.value for entry in self.help_system.documentation_entries.values() ) ), "help_categories": list( set( entry.category.value for entry in self.help_system.documentation_entries.values() ) ), } # Example usage and testing functions async def test_documentation_system(): """Test the documentation and help system""" print("🧪 Testing Documentation and Help System") print("=" * 50) # Test documentation system print("\n1. Testing Documentation System:") doc_system = AdvancedDocumentationSystem() # Test help system print("\n2. Testing Help System:") help_queries = [ "How do I get started?", "What is the API reference?", "How do I configure the system?", "What are the supported models?", ] for query in help_queries: print(f"\nQuery: {query}") help_response = await doc_system.get_help(query) print(f"Response: {help_response['response'][:100]}...") print(f"Relevant docs: {len(help_response.get('relevant_docs', []))}") # Test documentation generation print("\n3. Testing Documentation Generation:") if doc_system.documentation_generator.llm: generated_doc = await doc_system.generate_documentation( "Advanced Configuration", DocumentationType.USER_GUIDE, ["Introduction", "Configuration Options", "Examples", "Best Practices"], ) if generated_doc: print(f"Generated documentation: {generated_doc.title}") print(f"Content length: {len(generated_doc.content)} characters") # Test documentation rendering print("\n4. Testing Documentation Rendering:") entry_id = "getting_started" # Render to HTML html_content = doc_system.render_documentation(entry_id, "html") print(f"HTML content length: {len(html_content)} characters") # Render to Markdown markdown_content = doc_system.render_documentation(entry_id, "markdown") print(f"Markdown content length: {len(markdown_content)} characters") # Test documentation saving print("\n5. Testing Documentation Saving:") html_saved = doc_system.save_documentation(entry_id, "test_doc.html", "html") markdown_saved = doc_system.save_documentation(entry_id, "test_doc.md", "markdown") print(f"HTML saved: {html_saved}") print(f"Markdown saved: {markdown_saved}") # Test system stats print("\n6. Testing System Statistics:") stats = doc_system.get_system_stats() print(f"Total documentation entries: {stats['total_documentation_entries']}") print(f"Documentation types: {stats['documentation_types']}") print(f"Help categories: {stats['help_categories']}") print(f"Help system stats: {stats['help_system_stats']}") print("\n✅ Documentation and help system test completed!") if __name__ == "__main__": asyncio.run(test_documentation_system())
#!/usr/bin/env python3
"""
Advanced Documentation and Help System with Gemini API
This module provides sophisticated documentation and help capabilities for AI reasoning systems
"""
import os
import asyncio
import logging
from typing import List, Dict, Any, Optional, Union, Callable
from dataclasses import dataclass, field
from abc import ABC, abstractmethod
import json
import time
import markdown
from enum import Enum
from collections import defaultdict, deque
import numpy as np
from pathlib import Path
import re
from datetime import datetime
import webbrowser
import tempfile
# LangChain imports
from langchain_core.prompts import PromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
# Google Generative AI
import google.generativeai as genai
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DocumentationType(Enum):
"""Types of documentation"""
API_REFERENCE = "api_reference"
USER_GUIDE = "user_guide"
TUTORIAL = "tutorial"
FAQ = "faq"
TROUBLESHOOTING = "troubleshooting"
EXAMPLES = "examples"
CHANGELOG = "changelog"
class HelpCategory(Enum):
"""Help categories"""
GETTING_STARTED = "getting_started"
BASIC_USAGE = "basic_usage"
ADVANCED_FEATURES = "advanced_features"
CONFIGURATION = "configuration"
TROUBLESHOOTING = "troubleshooting"
API_REFERENCE = "api_reference"
EXAMPLES = "examples"
@dataclass
class DocumentationEntry:
"""Documentation entry structure"""
entry_id: str
title: str
content: str
doc_type: DocumentationType
category: HelpCategory
tags: List[str] = field(default_factory=list)
created_at: float = field(default_factory=time.time)
updated_at: float = field(default_factory=time.time)
author: str = "system"
version: str = "1.0.0"
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary"""
return {
"entry_id": self.entry_id,
"title": self.title,
"content": self.content,
"doc_type": self.doc_type.value,
"category": self.category.value,
"tags": self.tags,
"created_at": self.created_at,
"updated_at": self.updated_at,
"author": self.author,
"version": self.version,
"metadata": self.metadata,
}
@dataclass
class HelpRequest:
"""Help request structure"""
request_id: str
user_query: str
context: Dict[str, Any] = field(default_factory=dict)

Xet Storage Details

Size:
33.5 kB
·
Xet hash:
9696b1dd4bac205188685683d6ce3fdcfdd0e39168460568f04d2cda1c5580b2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.