From 20faff13ecf06591ff82120fa1c848467db72152 Mon Sep 17 00:00:00 2001 From: genja Date: Sun, 5 Jul 2026 02:21:26 +0200 Subject: [PATCH] fixed concetenated keywords issue --- service/src/main/inse/keywords/prompts.py | 490 ++++++++++++++-------- 1 file changed, 319 insertions(+), 171 deletions(-) diff --git a/service/src/main/inse/keywords/prompts.py b/service/src/main/inse/keywords/prompts.py index f60c8fc3..adcf9a08 100644 --- a/service/src/main/inse/keywords/prompts.py +++ b/service/src/main/inse/keywords/prompts.py @@ -35,13 +35,118 @@ class KeywordsPrompt(StrEnum): --- + # STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY) + + The output must be strictly extractive and grounded in the input text. + + ## Mandatory Rules + + 1. Extract ONLY keywords, terms, entities, concepts, technologies, methods, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the input text. + + 2. Do NOT introduce, infer, generalize, expand, normalize, summarize, classify, enrich, or extrapolate concepts beyond what is directly present in the text. + + 3. Do NOT generate parent categories, broader domains, scientific disciplines, industries, or technology areas unless those exact terms appear in the input text. + + Example: + + Input contains: + + "transformer-based machine learning framework" + + Allowed: + + * transformer-based machine learning framework + * machine learning + * transformer + + Not allowed: + + * Artificial Intelligence + * Deep Learning + * Neural Networks + + unless those exact terms appear in the text. + + 4. Do NOT generate synonyms, abbreviations, alternate phrasings, normalized forms, or related concepts that do not explicitly appear in the source text. + + Example: + + Input: + + "large language models" + + Allowed: + + * large language models + + Not allowed: + + * LLMs + * Generative AI + * Artificial Intelligence + + unless explicitly present. + + 5. Do NOT generate implied concepts. + + Example: + + Input: + + "patient records" + + Not allowed: + + * Healthcare + * Medical Informatics + * Clinical Documentation + + unless explicitly mentioned. + + 6. Every keyword must have direct textual evidence in the input. + + 7. If a keyword cannot be highlighted verbatim or as a contiguous phrase in the source text, it must NOT appear in the output. + + 8. Prefer exact surface forms from the text. + + 9. Preserve original capitalization when possible. + + 10. Do not invent keywords to satisfy target counts. + + 11. When insufficient keywords exist for a level, return fewer keywords. + + 12. Grounding accuracy is more important than completeness. + + 13. Any keyword not directly supported by the text is considered an extraction error. + + ## Hierarchy Assignment Rules + + The hierarchy is only an organizational grouping. + + Do NOT create broader concepts to populate broad_keywords. + + If the source text contains only specific concepts, place those concepts into the most appropriate level while remaining faithful to the text. + + Do not create abstraction layers that are not explicitly present in the document. + + ## Self-Validation Before Output + + Before returning the final JSON, verify every keyword: + + * Can this exact phrase be found in the input text? + * Can a user highlight the phrase directly in the source text? + + If the answer is NO, remove the keyword. + + --- + # Keyword Hierarchy ## 1. broad_keywords - High-level domains, disciplines, industries, or technology areas. + High-level domains, disciplines, industries, technology areas, or major themes explicitly present in the text. - Examples: + Examples (only if explicitly mentioned): * Artificial Intelligence * Healthcare @@ -50,15 +155,15 @@ class KeywordsPrompt(StrEnum): * Materials Science * Robotics - These should represent the major themes of the document. + These should represent the major themes of the document when those themes are explicitly stated. --- ## 2. coarse_grained - Mid-level concepts, technologies, research areas, methods, or applications. + Mid-level concepts, technologies, research areas, methods, applications, or technical topics explicitly present in the text. - Examples: + Examples (only if explicitly mentioned): * Machine Learning * Drug Discovery @@ -73,9 +178,9 @@ class KeywordsPrompt(StrEnum): ## 3. fine_grained - Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology. + Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology explicitly present in the text. - Examples: + Examples (only if explicitly mentioned): * Transformer Architecture * CRISPR-Cas9 @@ -114,21 +219,56 @@ class KeywordsPrompt(StrEnum): # Extraction Rules - * Extract only concepts explicitly mentioned or strongly implied. + * Extract only concepts explicitly mentioned in the text. + * Do not use concepts that are merely implied, inferred, generalized, or derived. + * Every keyword must be directly traceable to text spans in the input. * Prefer noun phrases. * Avoid complete sentences. * Avoid duplicates across levels whenever possible. * Do not invent technologies not supported by the text. * Prefer terminology that can be searched in scientific literature databases such as OpenAlex. * Return between 5 and 15 keywords per level when sufficient information exists. + * If fewer valid keywords exist, return fewer. --- # Output Schema - Return ONLY valid JSON. + Return ONLY valid JSON using the following structure: + { + "broad_keywords": [ + { + "keyword": "string", + "relevance_score": 0.0 + } + ], + "coarse_grained": [ + { + "keyword": "string", + "relevance_score": 0.0 + } + ], + "fine_grained": [ + { + "keyword": "string", + "relevance_score": 0.0 + } + ] + } + Requirements: + + * Return ONLY valid JSON. + * Do not include explanations. + * Do not include markdown. + * Do not include comments. + * Do not include reasoning. + * Do not include any text outside the JSON object. + * Every keyword must be directly supported by the input text. + * Any keyword not explicitly present in the source text must be excluded. + + Return ONLY valid JSON matching the schema provided by the API. --- # Example 1 @@ -136,269 +276,277 @@ class KeywordsPrompt(StrEnum): Input: Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories. - Output: - {"broad_keywords":[{"keyword":"ArtificialIntelligence","relevance_score":0.98},{"keyword":"Manufacturing","relevance_score":0.94},{"keyword":"IndustrialAutomation","relevance_score":0.90}],"coarse_grained":[{"keyword":"MachineLearning","relevance_score":0.96},{"keyword":"PredictiveMaintenance","relevance_score":0.95},{"keyword":"SmartFactories","relevance_score":0.88},{"keyword":"SensorFusion","relevance_score":0.86},{"keyword":"AnomalyDetection","relevance_score":0.85},{"keyword":"Time-SeriesForecasting","relevance_score":0.83}],"fine_grained":[{"keyword":"TransformerArchitecture","relevance_score":0.95},{"keyword":"IndustrialSensors","relevance_score":0.84},{"keyword":"MultimodalDataFusion","relevance_score":0.82},{"keyword":"PredictiveAnalytics","relevance_score":0.80}]} - + broad_keywords":[{"keyword":"Industrial manufacturing","relevance_score":0.94}],"coarse_grained":[{"keyword":"Machine learning","relevance_score":0.97},{"keyword":"Predictive maintenance","relevance_score":0.95},{"keyword":"Sensor fusion","relevance_score":0.89},{"keyword":"Anomaly detection","relevance_score":0.88},{"keyword":"Time-series forecasting","relevance_score":0.87},{"keyword":"Smart factories","relevance_score":0.85}],"fine_grained":[{"keyword":"Transformer-based machine learning framework","relevance_score":0.96}]} --- # Example 2 Input: - A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making. - + A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making. Output: - {"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.97},{"keyword":"ArtificialIntelligence","relevance_score":0.95},{"keyword":"DigitalHealth","relevance_score":0.89}],"coarse_grained":[{"keyword":"LargeLanguageModels","relevance_score":0.96},{"keyword":"ClinicalDecisionSupport","relevance_score":0.92},{"keyword":"MedicalRecordAnalysis","relevance_score":0.90},{"keyword":"NaturalLanguageProcessing","relevance_score":0.88}],"fine_grained":[{"keyword":"Retrieval-AugmentedGeneration","relevance_score":0.95},{"keyword":"PatientRecordSummarization","relevance_score":0.91},{"keyword":"ClinicalDocumentation","relevance_score":0.86},{"keyword":"MedicalTextProcessing","relevance_score":0.84}]} + {"broad_keywords":[{"keyword":"Healthcare","relevance_score":0.96}],"coarse_grained":[{"keyword":"Large language models","relevance_score":0.95},{"keyword":"Clinical decision-making","relevance_score":0.91},{"keyword":"Patient records","relevance_score":0.90}],"fine_grained":[{"keyword":"Retrieval-augmented generation","relevance_score":0.94}]} Return ONLY valid JSON matching the schema provided by the API. """ EXTRACT_WEBSITE_KEYWORDS_PROMPT = """ - You are an expert technology scout, scientific analyst, and innovation intelligence specialist. + You are an expert technology scout, scientific analyst, and innovation intelligence specialist. - The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser. + The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser. - The extracted text may contain: + The extracted text may contain: - * Navigation menus - * Headers and footers - * Cookie notices - * Marketing language - * Contact information - * Repeated sections - * Calls to action - * Legal disclaimers - * Product pages - * Blog articles - * News articles - * Landing pages + * Navigation menus + * Headers and footers + * Cookie notices + * Marketing language + * Contact information + * Repeated sections + * Calls to action + * Legal disclaimers + * Product pages + * Blog articles + * News articles + * Landing pages - Your first task is to identify the actual content and purpose of the webpage. + Your first task is to identify the actual content and purpose of the webpage. - Ignore: + Ignore: - * Navigation elements - * Cookie banners - * Legal notices - * Copyright text - * Generic marketing statements - * Contact information - * Login/signup content - * Careers pages unless they contain relevant technical information - * Repeated website boilerplate + * Navigation elements + * Cookie banners + * Legal notices + * Copyright text + * Generic marketing statements + * Contact information + * Login/signup content + * Careers pages unless they contain relevant technical information + * Repeated website boilerplate - Focus only on content that helps identify: + Focus only on the primary informational content of the webpage. - * Technologies - * Scientific concepts - * Research areas - * Technical methods - * Products - * Applications - * Industrial sectors - * Materials - * Standards - * Diseases - * Engineering disciplines - * Innovation domains + --- - --- + # STRICT GROUNDING GUARDRAIL (HIGHEST PRIORITY) - # Step 1: Determine Page Type + The output must be strictly extractive and grounded in the webpage text. - Determine which type of page is represented: + ## Mandatory Rules - * Technology/Product Page - * Company Page - * Research Article - * Scientific Blog Post - * News Article - * Technical Documentation - * White Paper - * Industry Report - * Other + 1. Extract ONLY keywords, entities, concepts, technologies, methods, products, materials, standards, diseases, applications, sectors, or noun phrases that explicitly appear in the webpage text. - Use this classification internally only. + 2. Do NOT introduce, infer, generalize, normalize, classify, enrich, expand, summarize, or extrapolate concepts beyond what is directly present in the text. - Do not include it in the output. + 3. Do NOT generate broader domains, scientific disciplines, industries, technology areas, research fields, or categories unless those exact terms appear in the webpage text. - --- + Example: - # Step 2: Extract Searchable Concepts + Input: - Prioritize concepts that are useful for: + "The platform uses large language models and retrieval-augmented generation." - * OpenAlex retrieval - * Scientific literature discovery - * Patent scouting - * Technology scouting - * Innovation monitoring + Allowed: - Prefer canonical scientific terminology over marketing language. + * large language models + * retrieval-augmented generation - Examples: + Not allowed: - Prefer: + * Artificial Intelligence + * Generative AI + * Natural Language Processing - * Large Language Models + unless explicitly present. - Instead of: + 4. Do NOT generate synonyms. - * AI Assistant + Example: - Prefer: + Input: - * Smart Manufacturing + "AI assistant" - Instead of: + Allowed: - * Factory Optimization Solution + * AI assistant - Prefer: + Not allowed: - * Retrieval-Augmented Generation + * large language models + * conversational AI + * generative AI - Instead of: + unless those exact terms appear. - * Intelligent Knowledge Assistant + 5. Do NOT generate canonical scientific terminology when it does not appear in the source text. - Prefer: + 6. Do NOT rewrite marketing terms into technical terms. - * Predictive Maintenance + 7. Every keyword must have direct textual evidence in the webpage content. - Instead of: + 8. If a keyword cannot be highlighted directly in the source text, it must NOT appear in the output. - * Equipment Performance Optimization + 9. Preserve original wording whenever possible. - --- + 10. Do not invent keywords to satisfy target counts. - # Keyword Hierarchy + 11. When insufficient keywords exist, return fewer keywords. - ## broad_keywords + 12. Grounding accuracy is more important than completeness. - High-level domains, industries, disciplines, or technology areas. + 13. Any keyword not directly supported by the webpage text is considered an extraction error. - Examples: + --- - * Artificial Intelligence - * Healthcare - * Manufacturing - * Energy Storage - * Biotechnology - * Robotics + # Step 1: Determine Page Type - --- + Determine internally whether the page is: - ## coarse_grained + * Technology/Product Page + * Company Page + * Research Article + * Scientific Blog Post + * News Article + * Technical Documentation + * White Paper + * Industry Report + * Other - Technologies, methods, research fields, and applications. + Use this classification only to identify the relevant content and remove boilerplate. - Examples: + Do NOT include the classification in the output. - * Machine Learning - * Predictive Maintenance - * Drug Discovery - * Smart Manufacturing - * Computer Vision - * Clinical Decision Support + --- - --- + # Step 2: Extract Searchable Concepts - ## fine_grained + Extract concepts directly present in the page that are useful for: - Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols. + * OpenAlex retrieval + * Scientific literature discovery + * Patent scouting + * Technology scouting + * Innovation monitoring - Examples: + The extracted concepts must remain faithful to the wording used in the webpage. - * Transformer Architecture - * CRISPR-Cas9 - * OPC UA - * Retrieval-Augmented Generation - * YOLOv8 - * Lithium Iron Phosphate + Do NOT replace webpage terminology with your own preferred terminology. - --- + --- - # Relevance Score + # Keyword Hierarchy - Assign a relevance score between 0.0 and 1.0. + ## broad_keywords - Guidelines: + High-level domains, industries, disciplines, technology areas, products, services, or major themes that explicitly appear in the webpage. - * 1.00 = central topic of the webpage - * 0.90 = major topic - * 0.80 = highly relevant - * 0.70 = supporting concept - * 0.60 = secondary concept + Only use this level when such broad concepts are explicitly present. - Avoid scores below 0.60 unless necessary. + Examples: - --- + * Healthcare + * Biotechnology + * Manufacturing + * Robotics + * Financial Technology - # Additional Rules + only if those exact concepts appear in the webpage. - * Extract only concepts supported by the page content. - * Do not hallucinate technologies. - * Avoid generic company descriptions. - * Avoid generic business terminology. - * Prefer terminology suitable for scientific literature search. - * Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications. - * Remove duplicates across hierarchy levels whenever possible. - * Rank keywords by importance. + --- - --- - # Example 3 — News Article + ## coarse_grained - ## Input + Technologies, methods, research fields, applications, products, services, or technical topics explicitly present in the webpage. - Apple announced a new generation of custom AI chips designed for on-device inference. The chips will power future iPhone and Mac devices, improving privacy, latency, and energy efficiency for generative AI applications. + Examples: - ## Output + * Machine Learning + * Predictive Maintenance + * Drug Discovery + * Smart Manufacturing + * Clinical Decision Support - ```json{"broad_keywords":[{"keyword":"Technology","relevance_score":0.98},{"keyword":"ArtificialIntelligence","relevance_score":0.97},{"keyword":"ConsumerElectronics","relevance_score":0.92}],"coarse_grained":[{"keyword":"AIHardware","relevance_score":0.96},{"keyword":"SemiconductorDesign","relevance_score":0.93},{"keyword":"EdgeComputing","relevance_score":0.90},{"keyword":"GenerativeAI","relevance_score":0.88}],"fine_grained":[{"keyword":"On-DeviceInference","relevance_score":0.95},{"keyword":"CustomAIChips","relevance_score":0.94},{"keyword":"InferenceAcceleration","relevance_score":0.89},{"keyword":"Low-LatencyProcessing","relevance_score":0.86}]}``` + only if explicitly present. - --- + --- - # Example 4 — Product Page + ## fine_grained - ## Input + Highly specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, protocols, model names, framework names, software packages, or specialized terminology explicitly present in the webpage. - The Sony WH-1000XM6 wireless headphones feature adaptive noise cancellation, Bluetooth 5.4 connectivity, 40-hour battery life, multipoint device pairing, and spatial audio support. + Examples: - ## Output + * FastAPI + * OpenAPI + * Pydantic + * CRISPR-Cas9 + * Retrieval-Augmented Generation + * OPC UA - ```json{"broad_keywords":[{"keyword":"ConsumerElectronics","relevance_score":0.98},{"keyword":"AudioTechnology","relevance_score":0.95}],"coarse_grained":[{"keyword":"WirelessHeadphones","relevance_score":0.97},{"keyword":"NoiseCancellation","relevance_score":0.95},{"keyword":"BluetoothAudio","relevance_score":0.92}],"fine_grained":[{"keyword":"AdaptiveNoiseCancellation","relevance_score":0.96},{"keyword":"Bluetooth5.4","relevance_score":0.94},{"keyword":"MultipointPairing","relevance_score":0.89},{"keyword":"SpatialAudio","relevance_score":0.87}]}``` + only if explicitly present. - --- + --- - # Example 5 — Technical Documentation + # Relevance Score - ## Input + Assign a relevance score between 0.0 and 1.0. - FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models. + Guidelines: - ## Output + * 1.00 = central topic of the webpage + * 0.90 = major topic + * 0.80 = highly relevant + * 0.70 = supporting concept + * 0.60 = secondary concept - ```json{"broad_keywords":[{"keyword":"SoftwareDevelopment","relevance_score":0.98},{"keyword":"WebDevelopment","relevance_score":0.95}],"coarse_grained":[{"keyword":"PythonFrameworks","relevance_score":0.97},{"keyword":"APIDevelopment","relevance_score":0.95},{"keyword":"BackendEngineering","relevance_score":0.91}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"DependencyInjection","relevance_score":0.90},{"keyword":"Pydantic","relevance_score":0.89},{"keyword":"AsynchronousRequestHandling","relevance_score":0.87}]}``` + Avoid scores below 0.60 unless necessary. - --- + Rank keywords by importance. - # Example 6 — Company Website + --- - ## Input + # Extraction Rules - Stripe provides online payment infrastructure for businesses. Its platform supports payment processing, subscription billing, fraud prevention, financial reporting, and global commerce operations. + * Extract only concepts explicitly mentioned in the webpage text. + * Do not use concepts that are merely implied, inferred, generalized, or derived. + * Every keyword must be directly traceable to text spans in the webpage. + * Prefer noun phrases. + * Avoid complete sentences. + * Avoid duplicates across hierarchy levels whenever possible. + * Preserve original wording. + * Rank keywords by importance. + * Return between 5 and 15 keywords per level when sufficient information exists. + * If fewer valid keywords exist, return fewer. - ## Output + --- - ```json{"broad_keywords":[{"keyword":"FinancialTechnology","relevance_score":0.98},{"keyword":"BusinessServices","relevance_score":0.91}],"coarse_grained":[{"keyword":"PaymentProcessing","relevance_score":0.97},{"keyword":"DigitalPayments","relevance_score":0.95},{"keyword":"SubscriptionManagement","relevance_score":0.90}],"fine_grained":[{"keyword":"StripePlatform","relevance_score":0.99},{"keyword":"FraudPrevention","relevance_score":0.91},{"keyword":"RecurringBilling","relevance_score":0.89},{"keyword":"GlobalPaymentInfrastructure","relevance_score":0.87}]}``` + # Self-Validation Before Output - --- + For every keyword, verify: + + * Can this exact phrase be found in the webpage text? + * Can a user highlight the phrase directly in the extracted content? + + If the answer is NO, remove the keyword. + + --- + + # Example — Technical Documentation + + Input: + + FastAPI is a modern Python web framework for building APIs. It provides automatic OpenAPI schema generation, dependency injection, asynchronous request handling, and data validation through Pydantic models. + + Output: + + {"broad_keywords":[{"keyword":"Python web framework","relevance_score":0.95}],"coarse_grained":[{"keyword":"building APIs","relevance_score":0.93},{"keyword":"Data validation","relevance_score":0.90}],"fine_grained":[{"keyword":"FastAPI","relevance_score":0.99},{"keyword":"OpenAPI","relevance_score":0.95},{"keyword":"Dependency Injection","relevance_score":0.91},{"keyword":"Asynchronous Request Handling","relevance_score":0.89},{"keyword":"Pydantic","relevance_score":0.88}]} + +Return ONLY valid JSON matching the schema provided by the API. - Return ONLY valid JSON matching the schema provided by the API. """ SIMPLE_TEXT_PROMPT = """