Skip to main content

Design Document - Part II API

Purpose

This Design Document gives the complete design of the software implementation. This information should be in structured comments (e.g. Javadoc) in the source files. We encourage the use of a documentation generation tool to generate a draft of your API that you can augment to include the following details.

Requirements

In addition to the general documentation requirements the Design Document - Part II API will contain:

General review of the software architecture for each module specified in Design Document - Part I Architecture. Please include your class diagram as an important reference.

For each class define the data fields, methods.

RAGPipeline

Purpose: Orchestrates the complete Retrieval-Augmented Generation flow from query to response.

Data Fields:

  • retriever: DocumentRetriever - Document retrieval component
  • contextManager: ContextManager - Conversation context handler
  • promptBuilder: PromptBuilder - Prompt construction component
  • llmConnector: LLMConnector - LLM interface
  • chain: Chain - LangChain Chain object coordinating components
  • pipelineConfig: Map<String, Any> - Configuration settings
  • executionMetrics: ExecutionMetrics - Performance tracking

Methods:

MethodPurposeParametersReturn TypePre-conditionsPost-conditionsExceptions
process(userQuery: String, userId: String): RAGResponseExecutes full RAG pipelineuserQuery: user question, userId: user identifierRAGResponse object with answerAll components initialized, userId validResponse generated, logged, metrics updatedRAGException, PipelineException
retrieveContext(query: String): List<Document>Retrieves relevant documents for queryquery: search query stringList of retrieved Document objectsretriever initializedContext docs selected and rankedRetrievalException, VectorStoreException
generateResponse(query: String, documents: List<Document>, context: ConversationContext): StringGenerates response using LLMquery: user query, documents: context docs, context: historyResponse stringLLM ready, documents provided, context validResponse generated with citationsLLMException, GenerationException
validateResponse(response: String, sourceDocuments: List<Document>): BooleanValidates response quality and relevanceresponse: generated response, sourceDocuments: used docsBoolean indicating validation resultresponse not empty, documents providedValidation score computed and loggedValidationException
handleFallback(originalQuery: String, error: Exception): StringHandles pipeline failures with fallbackoriginalQuery: original user query, error: exception thrownFallback response stringoriginal error caught, fallback readyFallback response returned, error loggedFallbackException

ContextManager

Purpose: Maintains conversation history and manages context windows for multi-turn conversations.

Data Fields:

  • conversationHistory: List<Message> - Ordered list of messages
  • contextWindow: int - Maximum number of previous messages to keep
  • userId: String - User ID for this conversation
  • sessionStartTime: LocalDateTime - When conversation started
  • lastMessageTime: LocalDateTime - Timestamp of last message
  • contextSummary: String - Summary of earlier conversation

Methods:

MethodPurposeParametersReturn TypePre-conditionsPost-conditionsExceptions
addMessage(role: Role, content: String): voidAdds user or assistant message to historyrole: USER or ASSISTANT, content: message textvoidcontent not emptyMessage appended, timestamp recordedInvalidMessageException
getContext(): ConversationContextRetrieves current conversation contextnoneConversationContext objecthistory not emptyContext object returned with full historynone
trimHistory(): voidRemoves oldest messages if exceeding context windownonevoidhistory populatedExcess messages removed, summary updatednone
getSummary(maxLength: int): StringGets concise summary of conversationmaxLength: max chars for summarySummary stringhistory not emptySummary generated and cachedSummaryException
getRelevantContext(query: String, maxMessages: int): List<Message>Filters history for query-relevant messagesquery: current query, maxMessages: limitFiltered list of Message objectshistory not empty, query providedMost relevant messages selectedContextFilterException
clearHistory(): voidClears conversation historynonevoidnoneHistory cleared, session endednone
exportConversation(): List<Message>Exports full conversation for loggingnoneList of all Message objectshistory not emptyConversation exported, formattedExportException

LLMConnector

Purpose: Abstracts LLM interactions using LangChain, supporting multiple providers (OpenAI, Claude, etc.).

Data Fields:

  • llmProvider: String - Provider name (OPENAI, ANTHROPIC, etc.)
  • apiKey: String - API authentication key
  • modelName: String - Specific model identifier
  • temperature: Float - Response randomness (0-1)
  • maxTokens: int - Maximum output length
  • retryPolicy: RetryPolicy - Retry configuration
  • requestCache: Map<String, String> - Cache of responses

Methods:

MethodPurposeParametersReturn TypePre-conditionsPost-conditionsExceptions
generate(prompt: String): StringGenerates single response from promptprompt: full prompt textGenerated response stringLLM initialized, API key valid, prompt providedResponse returned and cachedLLMException, APIException, RateLimitException
streamResponse(prompt: String, callback: StreamCallback): voidStreams response token-by-token for real-time UIprompt: full prompt, callback: token handlervoidLLM ready, streaming supportedTokens streamed to callback as generatedStreamingException, LLMException
validateResponse(response: String, constraints: List<Constraint>): BooleanValidates response meets quality constraintsresponse: generated text, constraints: validation rulesBoolean validation resultresponse not empty, constraints definedValidation result computedValidationException
setTemperature(temperature: Float): voidConfigures response randomnesstemperature: value 0.0-1.0void0 <= temperature <= 1Temperature parameter updatedInvalidParameterException
setMaxTokens(maxTokens: int): voidSets maximum response lengthmaxTokens: token limitvoidmaxTokens > 0Token limit updatedInvalidParameterException
testConnection(): BooleanVerifies LLM API connectivitynonetrue if connected, false otherwiseAPI key configuredConnection status determinedConnectionException
getUsageStats(): UsageStatsRetrieves API usage and cost informationnoneUsageStats object with metricsrequests madeUsage stats returnedStatsException

PromptBuilder

Purpose: Constructs optimized prompts for LLM by combining retrieved documents, context, and instructions.

Data Fields:

  • systemPromptTemplate: String - System role instruction template
  • userPromptTemplate: String - User query template
  • documentTemplate: String - Template for formatting documents
  • examplePrompts: Map<Intent, String> - Few-shot examples by intent
  • promptConfig: Map<String, Any> - Configuration parameters
  • citationFormat: CitationFormat - Format for citations

Methods:

MethodPurposeParametersReturn TypePre-conditionsPost-conditionsExceptions
buildSystemPrompt(context: SystemContext): StringBuilds system role and guidelines promptcontext: SystemContext with company infoSystem prompt stringcontext populatedSystem prompt formatted and readyPromptException
buildUserPrompt(query: String, documents: List<Document>, context: ConversationContext): StringAssembles full user prompt with contextquery: user question, documents: retrieved docs, context: historyComplete user prompt stringquery not empty, documents providedPrompt assembled with formattingPromptBuildException
formatDocuments(documents: List<Document>): StringFormats documents for inclusion in promptdocuments: list of Document objectsFormatted document stringdocuments not emptyDocuments formatted with metadataFormattingException
addCitations(documents: List<Document>): StringAdds source citations for documentsdocuments: source documentsCitation formatted stringdocuments have source URLsCitations formatted according to styleCitationException
getExamplePrompt(intent: Intent): StringRetrieves few-shot example for intent typeintent: detected intentExample prompt stringexamplePrompts loaded, intent validExample fetched for use in promptPromptNotFoundException
optimizePromptLength(prompt: String, maxLength: int): StringTruncates prompt while preserving qualityprompt: full prompt, maxLength: char limitOptimized prompt stringprompt not empty, maxLength > 0Prompt trimmed intelligentlyOptimizationException
validatePrompt(prompt: String): PromptValidationValidates prompt structure and contentprompt: assembled promptPromptValidation with score and issuesprompt not emptyValidation result computedValidationException

ChatbotOrchestrator

Purpose: Main controller orchestrating all RAG pipeline components and managing conversation flow.

Data Fields:

  • ragPipeline: RAGPipeline - RAG pipeline instance
  • queryProcessor: QueryProcessor - Query processing component
  • slackHandler: SlackBotHandler - Slack integration
  • userProfileManager: UserProfileManager - User management
  • expertMatcher: ExpertMatcher - Expert matching
  • fallbackSearchHandler: FallbackSearchHandler - Fallback search
  • conversationManagers: Map<String, ContextManager> - Per-user conversation contexts
  • orchestrationMetrics: Metrics - Performance and usage metrics

Methods:

MethodPurposeParametersReturn TypePre-conditionsPost-conditionsExceptions
handleQuery(query: String, userId: String, channelId: String): voidMain entry point handling user queryquery: user question, userId: user ID, channelId: Slack channelvoidquery not empty, userId/channelId validResponse sent to user, interaction loggedOrchestrationException
manageConversation(userId: String): ConversationContextGets or creates conversation context for useruserId: user identifierConversationContext objectuserId not emptyConversation context retrieved/createdConversationException
processUserQuery(query: String, userId: String): ProcessedQueryProcesses query through pipelinequery: user input, userId: userProcessedQuery with parsed intentquery not emptyQuery fully processedProcessingException
generateContextualResponse(query: String, context: ConversationContext): StringCreates response with context awarenessquery: current query, context: conversation historyResponse stringquery and context providedResponse generated with contextResponseException
routeToExpert(query: String, userId: String): UserProfileRoutes complex queries to expertsquery: user question, userId: requesting userExpert UserProfilequery valid, user existsExpert identified and notifiedExpertRoutingException
handleSpecialCommands(command: String, userId: String): StringProcesses special bot commandscommand: command string, userId: userCommand responsecommand recognizedCommand executed, response returnedCommandException
getMetrics(): MetricsRetrieves performance and usage metricsnoneMetrics objectorchestrator activeCurrent metrics returnednone
shutdown(): voidGracefully shuts down all componentsnonevoidorchestrator runningAll components stopped, connections closedShutdownException
initialize(): voidInitializes all components in dependency ordernonevoidconfiguration loadedAll components ready to useInitializationException

FallbackSearchHandler

Purpose: Implements fallback search strategies when internal documentation is insufficient.

Data Fields:

  • searchEngines: Map<String, SearchProvider> - External search providers
  • sourceValidator: SourceValidator - Validates search results
  • fallbackConfig: Map<String, Any> - Fallback configuration
  • resultCache: Map<String, List<SearchResult>> - Cache of search results
  • allowedDomains: List<String> - Whitelisted domains for fallback

Methods:

MethodPurposeParametersReturn TypePre-conditionsPost-conditionsExceptions
searchExternal(query: String, engines: List<String>): List<SearchResult>Searches external sourcesquery: search query, engines: search providersList of SearchResult objectsquery not empty, engines validResults retrieved from enginesSearchException, ExternalServiceException
validateSource(result: SearchResult): BooleanValidates search result source credibilityresult: SearchResult to validatetrue if valid sourceresult has URL and contentSource validation completedValidationException
rankResults(results: List<SearchResult>, originalQuery: String): List<SearchResult>Ranks search results by relevanceresults: unranked results, originalQuery: reference queryRanked list of SearchResult objectsresults not emptyResults sorted by relevance scoreRankingException
filterByDomain(results: List<SearchResult>): List<SearchResult>Filters results to allowed domainsresults: results to filterFiltered SearchResult listallowedDomains configuredResults filtered by domain whitelistnone
summarizeExternalContent(content: String): StringCreates summary of external sourcecontent: full textSummary stringcontent not emptySummary generated and returnedSummarizationException
determineFallbackNeed(internalResults: List<Document>): BooleanChecks if fallback search neededinternalResults: retrieved documentstrue if fallback neededinternalResults evaluatedFallback decision madenone
addToWhitelist(domain: String, category: String): voidAdds domain to approved sourcesdomain: domain name, category: categoryvoiddomain valid formatDomain added to whitelistValidationException
removeFromWhitelist(domain: String): voidRemoves domain from approved sourcesdomain: domain to removevoiddomain in whitelistDomain removed from whitelistDomainNotFoundException

ErrorHandler

Purpose: Manages error handling, logging, and graceful fallbacks for various failure scenarios.

Data Fields:

  • errorStrategies: Map<ErrorType, ErrorStrategy> - Error type handlers
  • fallbackResponses: Map<ErrorType, String> - Fallback response messages
  • notificationManager: NotificationManager - Admin error notifications
  • errorLogger: Logger - Error logging instance
  • recoveryStrategies: Map<ErrorType, RecoveryStrategy> - Recovery procedures
  • errorThresholds: Map<ErrorType, int> - Error rate thresholds

Methods:

MethodPurposeParametersReturn TypePre-conditionsPost-conditionsExceptions
handleTimeout(requestId: String, operation: String): StringHandles operation timeoutsrequestId: operation ID, operation: operation nameFallback response stringtimeout loggedTimeout handled, error wrappedTimeoutException
handleNoResults(query: String, context: ConversationContext): StringHandles queries with no resultsquery: user query, context: conversation contextResponse stringquery not emptyNo results handled gracefullynone
handleRateLimiting(userId: String, service: String): voidHandles rate limit errorsuserId: user ID, service: service namevoidnoneRate limit logged, user notifiedRateLimitException
alertAdmin(error: Exception, severity: Severity): voidNotifies admin of critical errorserror: exception, severity: error levelvoiderror not null, admin configuredAdmin notified via configured channelNotificationException
handleDatabaseError(error: SQLException): StringHandles database errorserror: SQL exceptionFallback responseerror not nullError logged, offline mode activated if neededDatabaseException
handleLLMError(error: LLMException): StringHandles LLM API errorserror: LLM exceptionFallback responseerror not nullError logged, alternative LLM tried if availableLLMException
logDetailedError(error: Exception, context: Map<String, Any>): voidLogs detailed error with full contexterror: exception, context: contextual infovoiderror not nullError with full stack trace loggedLoggingException
getErrorMetrics(): ErrorMetricsRetrieves error rate and metricsnoneErrorMetrics objecterror tracking activeError metrics computedMetricsException
registerErrorStrategy(errorType: ErrorType, strategy: ErrorStrategy): voidRegisters custom error handlererrorType: error type, strategy: handlervoiderrorType validStrategy registered for error typenone
shouldRetry(error: Exception): BooleanDetermines if operation should be retriederror: exception raisedtrue if retryable, false otherwiseerror type recognizedRetry decision madenone

The purpose of the class.

The purpose of each data field.

The purpose of each method

Pre-conditions if any.

Post-conditions if any.

Parameters and data types

Return value and output variables

Exceptions thrown* (PLEASE see note below for details).

An example of an auto-generated and then augmented API specification is here (Fiscal Design Document 2_API.docx )

This group developed their API documentation by hand (Design Document Part 2 API-1_MovieMatch.docx )

*At the top level, or where appropriate, all exceptions should be caught and an error message that is meaningful to the user generated. It is not OK to say ("xxxx has encountered a problem and will now close (OK?)". Error messages and recovery procedures should be documented in the User’s Manual.