Skip to main content
Glama

MCP Search Server

by Nghiauet
prompt.py16.3 kB
"""Prompt templates for the chatbot service.""" from typing import List, Optional, Union, Dict, Any SYSTEM_INSTRUCTION = """You are a helpful financial assistant that can provide information based on financial reports, documents, or general knowledge. When answering: 1. If financial report data is provided, prioritize information from those reports. 2. If context is provided, use that as secondary information. 3. If neither financial reports nor context has the answer but you know it, provide a general answer based on your financial knowledge. 4. Be concise and clear in your explanations - use simple language and short sentences. 5. Focus on the most important points first, then provide supporting details if needed. 6. Format financial data in a readable way using bullet points or tables when helpful. 7. When discussing financial metrics, provide brief, easy-to-understand definitions. 8. If you're unsure, acknowledge the limitations of your knowledge. 9. If the user asks about a topic that is not related to finance, acknowledge that you are not able to answer that question. 10. Always answer general financial questions like definitions of P/E ratio, ROI, or other common financial terms using simple explanations. 11. If analyzing multiple reports, highlight the most significant trends and changes over time. 12. Answer questions in the same language as the question. 13. If the money amount is too big, round it to the nearest million or billion and use clear units. 14. Structure your response with clear headings or sections when covering multiple points. 15. Avoid jargon - explain technical terms in plain language. Financial reports, when available, are provided between [FINANCIAL REPORTS] tags. Context, when available, is provided between [CONTEXT] tags.""" SYSTEM_INSTRUCTION_FOR_AUTOMATION = """ You are a specialized financial assistant designed to provide accurate, actionable information using external tools, documents, and financial knowledge. Follow these guidelines when responding: 1. **Language:** Respond in the same language as the user's query. 2. **Clarity & Conciseness:** - Use simple, clear language and short sentences - Lead with the most important information first - Break complex topics into digestible points - Avoid unnecessary jargon or overly technical explanations 3. **Structure & Organization:** - Use bullet points, numbered lists, or clear headings when helpful - Group related information together - Prioritize actionable insights over excessive data 4. **Data Formatting:** - Format financial data in easily readable tables or structured formats when appropriate - Simplify large monetary values (e.g., using millions or billions with appropriate units) - Highlight key numbers and trends clearly 5. **Metric Definitions:** Provide brief, easy-to-understand definitions of financial metrics (e.g., "P/E ratio shows how much investors pay for each dollar of earnings"). 6. **Knowledge Scope:** * Address general financial questions about terms, concepts, and principles using simple explanations * Politely redirect non-financial queries, explaining that you specialize in financial information 7. **Limitations:** Acknowledge knowledge limitations transparently when you cannot provide reliable information. 8. **Tool Usage:** Utilize the available tool effectively to answer questions requiring specific, up-to-date data. 9. Don't let the user know that you are using tools to answer the question. 10. DON'T NEED TO ASK USER WHEN NEED TO USE TOOLS, YOU CAN EXECUTE TOOLS DIRECTLY WITHOUT ASKING USER. 11. **Rate Limit Management:** To avoid overwhelming data sources, limit stock information requests to a maximum of 2 companies and 2 years of data per query. For broader market analysis or multiple company comparisons, use the search tool instead and inform users about the current limitation. Available Tool: - `get_stock_information_by_year(symbol: str, year: Optional[int] = None)`: Retrieves comprehensive financial data for a Vietnamese stock symbol. Args: - symbol: Stock ticker symbol (e.g., "FPT", "VNM", "VIC") - year: (Optional) Specific year for historical data. If omitted, returns the latest available data. Returns: - Current stock price - Company overview (business description, sector, history) - Financial statements (balance sheet, income statement, cash flow) - Key financial ratios organized by category (valuation, profitability, liquidity, etc.) Usage examples: - For latest data: get_stock_information_by_year("FPT") - For historical data: get_stock_information_by_year("FPT", 2020) **Important Usage Guidelines:** - Limit to maximum 2 stock symbol requests per query to avoid rate limits - For historical analysis, limit to maximum 2 years of data per query - If user asks for more extensive data (multiple companies or many years), use search_information tool instead - If rate limits are encountered, inform user: "Currently, we support detailed financial analysis for up to 2 companies and 2 years of data per query due to data source limitations. For broader analysis, I can provide general market information instead." When to use: - When asked about 1-2 specific Vietnamese companies' financial performance - When detailed financial analysis is requested for limited scope - When comparing current vs 1-2 years of historical financial metrics - When asked about financial ratios, company background, or specific financial statements for limited companies - `search_information(query: str)`: Searches the web for information relevant to the user's query. Args: - query: The search query Returns: - str: Organized text content from the top search results, including source URL, title, snippet, and extracted content. When to use: - For general information, news, or topics not covered by the `get_stock_information_by_year` tool - To find recent news, market trends, or explanations of financial concepts - When the user's query requires up-to-date information from the web that isn't specific company financial data - **When user asks for analysis of more than 2 companies or more than 2 years of data** - use this tool for broader market research - As a fallback when stock information tool encounters rate limits """ # Configuration for chat history management MAX_HISTORY_TOKENS = 2000 # Approximate token limit for history MAX_HISTORY_TURNS = 10 # Maximum number of conversation turns to include def get_system_instruction() -> str: """Get the system instruction for the chatbot.""" return SYSTEM_INSTRUCTION def _format_conversation_history( conversation_history: Optional[List[Union[str, Dict[str, Any]]]], max_tokens: int = MAX_HISTORY_TOKENS, ) -> str: """ Format and truncate conversation history to fit within token limits. Supports both string format and ChatMessage format. Args: conversation_history: List of conversation turns (strings or ChatMessage dicts) max_tokens: Maximum approximate tokens to include Returns: Formatted conversation history string """ if not conversation_history: return "" # Convert ChatMessage objects to formatted strings formatted_history = [] for item in conversation_history: if isinstance(item, dict) and "role" in item and "content" in item: # Handle ChatMessage format role = item["role"].title() # Capitalize first letter content = item["content"] formatted_history.append(f"{role}: {content}") elif isinstance(item, str): # Handle legacy string format formatted_history.append(item) else: # Skip invalid items continue # Take only the most recent turns to stay within limits recent_history = formatted_history[-MAX_HISTORY_TURNS:] # Simple token estimation (4 chars ≈ 1 token) history_text = "\n".join(recent_history) if len(history_text) > max_tokens * 4: # Truncate from the beginning, keeping the most recent exchanges while len(history_text) > max_tokens * 4 and len(recent_history) > 1: recent_history.pop(0) history_text = "\n".join(recent_history) return f"[CONTEXT]\nPrevious conversation:\n{history_text}\n[/CONTEXT]\n" def _build_base_prompt( query: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None, financial_reports: Optional[str] = None, context: Optional[str] = None, stock_price_info: Optional[str] = None, prompt_prefix: Optional[str] = None, ) -> str: """ Base prompt builder that handles all common prompt construction logic. Args: query: User's question conversation_history: Previous conversation turns financial_reports: Financial report content context: Additional context content stock_price_info: Stock price information prompt_prefix: Custom prompt prefix Returns: Formatted prompt string """ prompt_parts = [] # Add financial reports section if financial_reports: prompt_parts.append( f"[FINANCIAL REPORTS]\n{financial_reports}\n[/FINANCIAL REPORTS]" ) # Add stock price section if stock_price_info: prompt_parts.append(f"[STOCK_PRICE]\n{stock_price_info}\n[/STOCK_PRICE]") # Add context or conversation history if context: prompt_parts.append(f"[CONTEXT]\n{context}\n[/CONTEXT]") elif conversation_history: history_context = _format_conversation_history(conversation_history) if history_context: prompt_parts.append(history_context) # Add prompt prefix and query if prompt_prefix: prompt_parts.append(f"{prompt_prefix}\n{query}") else: prompt_parts.append(query) # Add fallback instruction for general financial questions if financial_reports or context: prompt_parts.append( "\nIf the provided information doesn't contain the answer but it's a general " "financial concept, please provide a helpful answer based on your financial knowledge." ) return "\n\n".join(prompt_parts) def build_prompt_with_financial_reports( report_content: str, query: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None, stock_price_info: Optional[str] = None, ) -> str: """Build prompt string with financial report content.""" return _build_base_prompt( query=query, conversation_history=conversation_history, financial_reports=report_content, stock_price_info=stock_price_info, prompt_prefix="Based on the financial reports provided, please answer the following question:", ) def build_prompt_with_financial_reports_and_history( statement_content: str, query: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None, ) -> str: """Build prompt string with both financial reports and document context.""" return _build_base_prompt( query=query, conversation_history=conversation_history, financial_reports=statement_content, prompt_prefix="Based on the financial reports and additional context provided, please answer the following question:", ) def build_prompt_with_context( document_content: str, query: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None, ) -> str: """Build prompt string with document context.""" if conversation_history: # When we have conversation history, prioritize it over document content return _build_base_prompt( query=query, conversation_history=conversation_history, prompt_prefix="Based on the previous conversation, answer the following question:", ) else: return _build_base_prompt( query=query, context=document_content, prompt_prefix="Based on the above context, please answer the following question:", ) def build_prompt_without_context( query: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None ) -> str: """Build prompt string without document context.""" if conversation_history: return _build_base_prompt( query=query, conversation_history=conversation_history, prompt_prefix="Based on the previous conversation, answer the following question:", ) else: return _build_base_prompt( query=query, prompt_prefix="***You are a helpful financial assistant. Please answer the following question to the best of your ability:***", ) def build_prompt_for_missing_financial_report( stock_symbol: str, period: Optional[str], query: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None, ) -> str: """Build prompt string when financial report was requested but not found.""" period_info = f" for period {period}" if period else "" context_content = f"No financial report was found for {stock_symbol}{period_info}." if conversation_history: history_text = "\n".join( conversation_history[-5:] ) # Keep last 5 turns for context context_content += f"\n\nPrevious conversation:\n{history_text}" return _build_base_prompt( query=query, context=context_content, prompt_prefix=( "The user is asking about a financial report that is not available. " "Please inform them that the requested financial data is not available " "and answer any general financial questions if possible:" ), ) def build_prompt_with_stock_price( stock_symbol: str, period: Optional[str], query: str, stock_price_info: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None, ) -> str: """Build prompt string when only stock price is available.""" return _build_base_prompt( query=query, conversation_history=conversation_history, stock_price_info=stock_price_info, prompt_prefix=( "The user is asking about a stock. Please provide information based on the stock price " "and answer any general financial questions if possible:" ), ) def build_prompt_for_extract_stock_symbol(query: str) -> str: """Build prompt string for extracting stock symbol from query.""" return f"""[QUERY]\n{query}\n[/QUERY] You are a helpful financial assistant. Extract the stock symbol from the query. If the query is not about a stock, return None.""" def build_prompt_with_tools_for_automation( query: str, conversation_history: Optional[List[Union[str, Dict[str, Any]]]] = None ) -> str: """ Builds the user message prompt for the agent with optimized history handling. Supports both string format and ChatMessage format for conversation history. Args: query: The user's current query conversation_history: Previous conversation turns (strings or ChatMessage dicts) Returns: Formatted prompt string for the automation agent """ prompt_parts = [ "Based on the chat history (if provided) and the current query, please provide a helpful response. " "Use your available tools if necessary to gather or verify information." ] # Add conversation history with smart truncation if conversation_history: history_context = _format_conversation_history( conversation_history, max_tokens=1500 ) if history_context: # Remove the [CONTEXT] wrapper and add [CHAT HISTORY] wrapper instead history_text = history_context.replace( "[CONTEXT]\nPrevious conversation:\n", "" ).replace("\n[/CONTEXT]\n", "") prompt_parts.append(f"[CHAT HISTORY]\n{history_text}\n[/CHAT HISTORY]") # Add current query prompt_parts.append(f"[CURRENT QUERY]\n{query}\n[/CURRENT QUERY]") return "\n\n".join(prompt_parts)

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Nghiauet/mcp-agent'

If you have feedback or need assistance with the MCP directory API, please join our Discord server