Skip to content

Python scraper based on AI

Template refactoring

Matteo Vedovati2d2c7194bef8
diff --git a/scrapegraphai/nodes/generate_code_node.py b/scrapegraphai/nodes/generate_code_node.py
index c4c04d52..c7cdd031 100644
--- a/scrapegraphai/nodes/generate_code_node.py
+++ b/scrapegraphai/nodes/generate_code_node.py
@@ -20,6 +20,12 @@ from ..utils import transform_schema
from jsonschema import validate, ValidationError
import json
import string
+from ..prompts import (
+ TEMPLATE_INIT_CODE_GENERATION, TEMPLATE_SYNTAX_ANALYSIS, TEMPLATE_SYNTAX_CODE_GENERATION,
+ TEMPLATE_EXECUTION_ANALYSIS, TEMPLATE_EXECUTION_CODE_GENERATION, TEMPLATE_VALIDATION_ANALYSIS,
+ TEMPLATE_VALIDATION_CODE_GENERATION, TEMPLATE_SEMANTIC_COMPARISON, TEMPLATE_SEMANTIC_ANALYSIS,
+ TEMPLATE_SEMANTIC_CODE_GENERATION
+)
class GenerateCodeNode(BaseNode):
"""
@@ -232,47 +238,8 @@ class GenerateCodeNode(BaseNode):
return state
def generate_initial_code(self, state: dict) -> str:
- template_code_generator = """
- **Task**: Create a Python function named `extract_data(html: str) -> dict()` using BeautifulSoup that extracts relevant information from the given HTML code string and returns it in a dictionary matching the Desired JSON Output Schema.
-
- **User's Request**:
- {user_input}
-
- **Desired JSON Output Schema**:
- ```json
- {json_schema}
- ```
-
- **Initial Task Analysis**:
- {initial_analysis}
-
- **HTML Code**:
- ```html
- {html_code}
- ```
-
- **HTML Structure Analysis**:
- {html_analysis}
-
- Based on the above analyses, generate the `extract_data(html: str) -> dict()` function that:
- 1. Efficiently extracts the required data from the given HTML structure.
- 2. Processes and structures the data according to the specified JSON schema.
- 3. Returns the structured data as a dictionary.
-
- Your code should be well-commented, explaining the reasoning behind key decisions and any potential areas for improvement or customization.
-
- Use only the following pre-imported libraries:
- - BeautifulSoup from bs4
- - re
-
- **Output ONLY the Python code of the extract_data function, WITHOUT ANY IMPORTS OR ADDITIONAL TEXT.**
- In your code do not include backticks.
-
- **Response**:
- """
-
prompt = PromptTemplate(
- template=template_code_generator,
+ template=TEMPLATE_INIT_CODE_GENERATION,
partial_variables={
"user_input": state["user_input"],
"json_schema": state["json_schema"],
@@ -288,23 +255,7 @@ class GenerateCodeNode(BaseNode):
return generated_code
def syntax_focused_analysis(self, state: dict) -> str:
- template = """
- The current code has encountered a syntax error. Here are the details:
-
- Current Code:
- ```python
- {generated_code}
- ```
-
- Syntax Error:
- {errors}
-
- Please analyze in detail the syntax error and suggest a fix. Focus only on correcting the syntax issue while ensuring the code still meets the original requirements.
-
- Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["generated_code", "errors"])
+ prompt = PromptTemplate(template=TEMPLATE_SYNTAX_ANALYSIS, input_variables=["generated_code", "errors"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"generated_code": state["generated_code"],
@@ -312,21 +263,7 @@ class GenerateCodeNode(BaseNode):
})
def syntax_focused_code_generation(self, state: dict, analysis: str) -> str:
- template = """
- Based on the following analysis of a syntax error, please generate the corrected code, following the suggested fix.:
-
- Error Analysis:
- {analysis}
-
- Original Code:
- ```python
- {generated_code}
- ```
-
- Generate the corrected code, applying the suggestions from the analysis. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code"])
+ prompt = PromptTemplate(template=TEMPLATE_SYNTAX_CODE_GENERATION, input_variables=["analysis", "generated_code"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"analysis": analysis,
@@ -334,32 +271,7 @@ class GenerateCodeNode(BaseNode):
})
def execution_focused_analysis(self, state: dict) -> str:
- template = """
- The current code has encountered an execution error. Here are the details:
-
- **Current Code**:
- ```python
- {generated_code}
- ```
-
- **Execution Error**:
- {errors}
-
- **HTML Code**:
- ```html
- {html_code}
- ```
-
- **HTML Structure Analysis**:
- {html_analysis}
-
- Please analyze the execution error and suggest a fix. Focus only on correcting the execution issue while ensuring the code still meets the original requirements and maintains correct syntax.
- The suggested fix should address the execution error and ensure the function can successfully extract the required data from the provided HTML structure. Be sure to be precise and specific in your analysis.
-
- Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["generated_code", "errors", "html_code", "html_analysis"])
+ prompt = PromptTemplate(template=TEMPLATE_EXECUTION_ANALYSIS, input_variables=["generated_code", "errors", "html_code", "html_analysis"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"generated_code": state["generated_code"],
@@ -369,21 +281,7 @@ class GenerateCodeNode(BaseNode):
})
def execution_focused_code_generation(self, state: dict, analysis: str) -> str:
- template = """
- Based on the following analysis of an execution error, please generate the corrected code:
-
- Error Analysis:
- {analysis}
-
- Original Code:
- ```python
- {generated_code}
- ```
-
- Generate the corrected code, applying the suggestions from the analysis. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code"])
+ prompt = PromptTemplate(template=TEMPLATE_EXECUTION_CODE_GENERATION, input_variables=["analysis", "generated_code"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"analysis": analysis,
@@ -391,31 +289,7 @@ class GenerateCodeNode(BaseNode):
})
def validation_focused_analysis(self, state: dict) -> str:
- template = """
- The current code's output does not match the required schema. Here are the details:
-
- Current Code:
- ```python
- {generated_code}
- ```
-
- Validation Errors:
- {errors}
-
- Required Schema:
- ```json
- {json_schema}
- ```
-
- Current Output:
- {execution_result}
-
- Please analyze the validation errors and suggest fixes. Focus only on correcting the output to match the required schema while ensuring the code maintains correct syntax and execution.
-
- Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["generated_code", "errors", "json_schema", "execution_result"])
+ prompt = PromptTemplate(template=TEMPLATE_VALIDATION_ANALYSIS, input_variables=["generated_code", "errors", "json_schema", "execution_result"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"generated_code": state["generated_code"],
@@ -425,26 +299,7 @@ class GenerateCodeNode(BaseNode):
})
def validation_focused_code_generation(self, state: dict, analysis: str) -> str:
- template = """
- Based on the following analysis of a validation error, please generate the corrected code:
-
- Error Analysis:
- {analysis}
-
- Original Code:
- ```python
- {generated_code}
- ```
-
- Required Schema:
- ```json
- {json_schema}
- ```
-
- Generate the corrected code, applying the suggestions from the analysis and ensuring the output matches the required schema. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code", "json_schema"])
+ prompt = PromptTemplate(template=TEMPLATE_VALIDATION_CODE_GENERATION, input_variables=["analysis", "generated_code", "json_schema"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"analysis": analysis,
@@ -470,27 +325,8 @@ class GenerateCodeNode(BaseNode):
]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
- template = """
- Compare the Generated Result with the Reference Result and determine if they are semantically equivalent:
-
- Generated Result:
- {generated_result}
-
- Reference Result (Correct Output):
- {reference_result}
-
- Analyze the content, structure, and meaning of both results. They should be considered semantically equivalent if they convey the same information, even if the exact wording or structure differs.
- If they are not semantically equivalent, identify what are the key differences in the Generated Result. The Reference Result should be considered the correct output, you need to pinpoint the problems in the Generated Result.
-
- {format_instructions}
-
- Human: Are the generated result and reference result semantically equivalent? If not, what are the key differences?
-
- Assistant: Let's analyze the two results carefully:
- """
-
prompt = PromptTemplate(
- template=template,
+ template=TEMPLATE_SEMANTIC_COMPARISON,
input_variables=["generated_result", "reference_result"],
partial_variables={"format_instructions": output_parser.get_format_instructions()}
)
@@ -501,27 +337,8 @@ class GenerateCodeNode(BaseNode):
"reference_result": json.dumps(reference_result_dict, indent=2)
})
- def semantic_focused_analysis(self, state: dict, comparison_result: Dict[str, Any]) -> str:
- template = """
- The current code's output is semantically different from the reference answer. Here are the details:
-
- Current Code:
- ```python
- {generated_code}
- ```
-
- Semantic Differences:
- {differences}
-
- Comparison Explanation:
- {explanation}
-
- Please analyze these semantic differences and suggest how to modify the code to produce a result that is semantically equivalent to the reference answer. Focus on addressing the key differences while maintaining the overall structure and functionality of the code.
-
- Provide your analysis and suggestions for fixing the semantic differences. DO NOT generate any code in your response.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["generated_code", "differences", "explanation"])
+ def semantic_focused_analysis(self, state: dict, comparison_result: Dict[str, Any]) -> str:
+ prompt = PromptTemplate(template=TEMPLATE_SEMANTIC_ANALYSIS, input_variables=["generated_code", "differences", "explanation"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"generated_code": state["generated_code"],
@@ -530,27 +347,7 @@ class GenerateCodeNode(BaseNode):
})
def semantic_focused_code_generation(self, state: dict, analysis: str) -> str:
- template = """
- Based on the following analysis of semantic differences, please generate the corrected code:
-
- Semantic Analysis:
- {analysis}
-
- Original Code:
- ```python
- {generated_code}
- ```
-
- Generated Result:
- {generated_result}
-
- Reference Result:
- {reference_result}
-
- Generate the corrected code, applying the suggestions from the analysis to make the output semantically equivalent to the reference result. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
- """
-
- prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code", "generated_result", "reference_result"])
+ prompt = PromptTemplate(template=TEMPLATE_SEMANTIC_CODE_GENERATION, input_variables=["analysis", "generated_code", "generated_result", "reference_result"])
chain = prompt | self.llm_model | StrOutputParser()
return chain.invoke({
"analysis": analysis,
diff --git a/scrapegraphai/nodes/html_analyzer_node.py b/scrapegraphai/nodes/html_analyzer_node.py
index 83bc9fbc..d526315c 100644
--- a/scrapegraphai/nodes/html_analyzer_node.py
+++ b/scrapegraphai/nodes/html_analyzer_node.py
@@ -10,6 +10,9 @@ from langchain_community.chat_models import ChatOllama
from tqdm import tqdm
from .base_node import BaseNode
from ..utils import reduce_html
+from ..prompts import (
+ TEMPLATE_HTML_ANALYSIS, TEMPLATE_HTML_ANALYSIS_WITH_CONTEXT
+)
class HtmlAnalyzerNode(BaseNode):
"""
@@ -70,73 +73,6 @@ class HtmlAnalyzerNode(BaseNode):
KeyError: If the input keys are not found in the state, indicating
that the necessary information for generating an answer is missing.
"""
-
- template_html_analysis = """
- Task: Your job is to analyze the provided HTML code in relation to the initial scraping task analysis and provide all the necessary HTML information useful for implementing a function that extracts data from the given HTML string.
-
- **Initial Analysis**:
- {initial_analysis}
-
- **HTML Code**:
- ```html
- {html_code}
- ```
-
- **HTML Analysis Instructions**:
- 1. Examine the HTML code and identify elements, classes, or IDs that correspond to each required data field mentioned in the Initial Analysis.
- 2. Look for patterns or repeated structures that could indicate multiple items (e.g., product listings).
- 3. Note any nested structures or relationships between elements that are relevant to the data extraction task.
- 4. Discuss any additional considerations based on the specific HTML layout that are crucial for accurate data extraction.
- 5. Recommend the specific strategy to use for scraping the content, remeber.
-
- **Important Notes**:
- - The function that the code generator is gonig to implement will receive the HTML as a string parameter, not as a live webpage.
- - No web scraping, automation, or handling of dynamic content is required.
- - The analysis should focus solely on extracting data from the static HTML provided.
- - Be precise and specific in your analysis, as the code generator will, possibly, not have access to the full HTML context.
-
- This HTML analysis will be used to guide the final code generation process for a function that extracts data from the given HTML string.
- Please provide only the analysis with relevant, specific information based on this HTML code. Avoid vague statements and focus on exact details needed for accurate data extraction.
-
- Focus on providing a concise, step-by-step analysis of the HTML structure and the key elements needed for data extraction. Do not include any code examples or implementation logic. Keep the response focused and avoid general statements.**
-
- **HTML Analysis for Data Extraction**:
- """
-
- template_html_analysis_with_context = """
- Task: Your job is to analyze the provided HTML code in relation to the initial scraping task analysis and the additional context the user provided and provide all the necessary HTML information useful for implementing a function that extracts data from the given HTML string.
-
- **Initial Analysis**:
- {initial_analysis}
-
- **HTML Code**:
- ```html
- {html_code}
- ```
-
- **Additional Context**:
- {additional_context}
-
- **HTML Analysis Instructions**:
- 1. Examine the HTML code and identify elements, classes, or IDs that correspond to each required data field mentioned in the Initial Analysis.
- 2. Look for patterns or repeated structures that could indicate multiple items (e.g., product listings).
- 3. Note any nested structures or relationships between elements that are relevant to the data extraction task.
- 4. Discuss any additional considerations based on the specific HTML layout that are crucial for accurate data extraction.
- 5. Recommend the specific strategy to use for scraping the content, remeber.
-
- **Important Notes**:
- - The function that the code generator is gonig to implement will receive the HTML as a string parameter, not as a live webpage.
- - No web scraping, automation, or handling of dynamic content is required.
- - The analysis should focus solely on extracting data from the static HTML provided.
- - Be precise and specific in your analysis, as the code generator will, possibly, not have access to the full HTML context.
-
- This HTML analysis will be used to guide the final code generation process for a function that extracts data from the given HTML string.
- Please provide only the analysis with relevant, specific information based on this HTML code. Avoid vague statements and focus on exact details needed for accurate data extraction.
-
- Focus on providing a concise, step-by-step analysis of the HTML structure and the key elements needed for data extraction. Do not include any code examples or implementation logic. Keep the response focused and avoid general statements.**
- In your code do not include backticks.
- **HTML Analysis for Data Extraction**:
- """
self.logger.info(f"--- Executing {self.node_name} Node ---")
@@ -150,13 +86,13 @@ class HtmlAnalyzerNode(BaseNode):
if self.additional_info is not None: # use additional context if present
prompt = PromptTemplate(
- template=template_html_analysis_with_context,
+ template=TEMPLATE_HTML_ANALYSIS_WITH_CONTEXT,
partial_variables={"initial_analysis": refined_prompt,
"html_code": reduced_html,
"additional_context": self.additional_info})
else:
prompt = PromptTemplate(
- template=template_html_analysis,
+ template=TEMPLATE_HTML_ANALYSIS,
partial_variables={"initial_analysis": refined_prompt,
"html_code": reduced_html})
diff --git a/scrapegraphai/nodes/prompt_refiner_node.py b/scrapegraphai/nodes/prompt_refiner_node.py
index 50e5f76e..e6f4579c 100644
--- a/scrapegraphai/nodes/prompt_refiner_node.py
+++ b/scrapegraphai/nodes/prompt_refiner_node.py
@@ -12,6 +12,9 @@ from langchain_community.chat_models import ChatOllama
from tqdm import tqdm
from .base_node import BaseNode
from ..utils import transform_schema
+from ..prompts import (
+ TEMPLATE_REFINER, TEMPLATE_REFINER_WITH_CONTEXT
+)
class PromptRefinerNode(BaseNode):
"""
@@ -76,66 +79,6 @@ class PromptRefinerNode(BaseNode):
KeyError: If the input keys are not found in the state, indicating
that the necessary information for generating an answer is missing.
"""
-
- template_prompt_builder = """
- **Task**: Analyze the user's request and the provided JSON schema to clearly map the desired data extraction.\n
- Break down the user's request into key components, and then explicitly connect these components to the
- corresponding elements within the JSON schema.
-
- **User's Request**:
- {user_input}
-
- **Desired JSON Output Schema**:
- ```json
- {json_schema}
- ```
-
- **Analysis Instructions**:
- 1. **Break Down User Request:**
- * Clearly identify the core entities or data types the user is asking for.\n
- * Highlight any specific attributes or relationships mentioned in the request.\n
-
- 2. **Map to JSON Schema**:
- * For each identified element in the user request, pinpoint its exact counterpart in the JSON schema.\n
- * Explain how the schema structure accommodates the user's needs.
- * If applicable, mention any schema elements that are not directly addressed in the user's request.\n
-
- This analysis will be used to guide the HTML structure examination and ultimately inform the code generation process.\n
- Please generate only the analysis and no other text.
-
- **Response**:
- """
-
- template_prompt_builder_with_context = """
- **Task**: Analyze the user's request, the provided JSON schema, and the additional context the user provided to clearly map the desired data extraction.\n
- Break down the user's request into key components, and then explicitly connect these components to the corresponding elements within the JSON schema.\n
-
- **User's Request**:
- {user_input}
-
- **Desired JSON Output Schema**:
- ```json
- {json_schema}
- ```
-
- **Additional Context**:
- {additional_context}
-
- **Analysis Instructions**:
- 1. **Break Down User Request:**
- * Clearly identify the core entities or data types the user is asking for.\n
- * Highlight any specific attributes or relationships mentioned in the request.\n
-
- 2. **Map to JSON Schema**:
- * For each identified element in the user request, pinpoint its exact counterpart in the JSON schema.\n
- * Explain how the schema structure accommodates the user's needs.\n
- * If applicable, mention any schema elements that are not directly addressed in the user's request.\n
-
- This analysis will be used to guide the HTML structure examination and ultimately inform the code generation process.\n
- Please generate only the analysis and no other text.
-
- **Response**:
- """
self.logger.info(f"--- Executing {self.node_name} Node ---")
@@ -145,13 +88,13 @@ class PromptRefinerNode(BaseNode):
if self.additional_info is not None:
prompt = PromptTemplate(
- template=template_prompt_builder_with_context,
+ template=TEMPLATE_REFINER_WITH_CONTEXT,
partial_variables={"user_input": user_prompt,
"json_schema": str(self.simplefied_schema),
"additional_context": self.additional_info})
else:
prompt = PromptTemplate(
- template=template_prompt_builder,
+ template=TEMPLATE_REFINER,
partial_variables={"user_input": user_prompt,
"json_schema": str(self.simplefied_schema)})
diff --git a/scrapegraphai/prompts/__init__.py b/scrapegraphai/prompts/__init__.py
index f5b72f3e..479d6ece 100644
--- a/scrapegraphai/prompts/__init__.py
+++ b/scrapegraphai/prompts/__init__.py
@@ -11,3 +11,6 @@ from .robots_node_prompts import TEMPLATE_ROBOT
from .search_internet_node_prompts import TEMPLATE_SEARCH_INTERNET
from .search_link_node_prompts import TEMPLATE_RELEVANT_LINKS
from .search_node_with_context_prompts import TEMPLATE_SEARCH_WITH_CONTEXT_CHUNKS, TEMPLATE_SEARCH_WITH_CONTEXT_NO_CHUNKS
+from .prompt_refiner_node_prompts import TEMPLATE_REFINER, TEMPLATE_REFINER_WITH_CONTEXT
+from .html_analyzer_node_prompts import TEMPLATE_HTML_ANALYSIS, TEMPLATE_HTML_ANALYSIS_WITH_CONTEXT
+from .generate_code_node_prompts import TEMPLATE_INIT_CODE_GENERATION, TEMPLATE_SYNTAX_ANALYSIS, TEMPLATE_SYNTAX_CODE_GENERATION, TEMPLATE_EXECUTION_ANALYSIS, TEMPLATE_EXECUTION_CODE_GENERATION, TEMPLATE_VALIDATION_ANALYSIS, TEMPLATE_VALIDATION_CODE_GENERATION, TEMPLATE_SEMANTIC_COMPARISON, TEMPLATE_SEMANTIC_ANALYSIS, TEMPLATE_SEMANTIC_CODE_GENERATION
\ No newline at end of file
diff --git a/scrapegraphai/prompts/generate_code_node_templates.py b/scrapegraphai/prompts/generate_code_node_templates.py
new file mode 100644
index 00000000..eab92ee4
--- /dev/null
+++ b/scrapegraphai/prompts/generate_code_node_templates.py
@@ -0,0 +1,213 @@
+"""
+Generate code prompts helper
+"""
+
+
+TEMPLATE_INIT_CODE_GENERATION = """
+**Task**: Create a Python function named `extract_data(html: str) -> dict()` using BeautifulSoup that extracts relevant information from the given HTML code string and returns it in a dictionary matching the Desired JSON Output Schema.
+
+**User's Request**:
+{user_input}
+
+**Desired JSON Output Schema**:
+```json
+{json_schema}
+```
+
+**Initial Task Analysis**:
+{initial_analysis}
+
+**HTML Code**:
+```html
+{html_code}
+```
+
+**HTML Structure Analysis**:
+{html_analysis}
+
+Based on the above analyses, generate the `extract_data(html: str) -> dict()` function that:
+1. Efficiently extracts the required data from the given HTML structure.
+2. Processes and structures the data according to the specified JSON schema.
+3. Returns the structured data as a dictionary.
+
+Your code should be well-commented, explaining the reasoning behind key decisions and any potential areas for improvement or customization.
+
+Use only the following pre-imported libraries:
+- BeautifulSoup from bs4
+- re
+
+**Output ONLY the Python code of the extract_data function, WITHOUT ANY IMPORTS OR ADDITIONAL TEXT.**
+In your code do not include backticks.
+
+**Response**:
+"""
+
+TEMPLATE_SYNTAX_ANALYSIS = """
+The current code has encountered a syntax error. Here are the details:
+
+Current Code:
+```python
+{generated_code}
+```
+
+Syntax Error:
+{errors}
+
+Please analyze in detail the syntax error and suggest a fix. Focus only on correcting the syntax issue while ensuring the code still meets the original requirements.
+
+Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
+"""
+
+TEMPLATE_SYNTAX_CODE_GENERATION = """
+Based on the following analysis of a syntax error, please generate the corrected code, following the suggested fix.:
+
+Error Analysis:
+{analysis}
+
+Original Code:
+```python
+{generated_code}
+```
+
+Generate the corrected code, applying the suggestions from the analysis. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
+"""
+
+TEMPLATE_EXECUTION_ANALYSIS = """
+The current code has encountered an execution error. Here are the details:
+
+**Current Code**:
+```python
+{generated_code}
+```
+
+**Execution Error**:
+{errors}
+
+**HTML Code**:
+```html
+{html_code}
+```
+
+**HTML Structure Analysis**:
+{html_analysis}
+
+Please analyze the execution error and suggest a fix. Focus only on correcting the execution issue while ensuring the code still meets the original requirements and maintains correct syntax.
+The suggested fix should address the execution error and ensure the function can successfully extract the required data from the provided HTML structure. Be sure to be precise and specific in your analysis.
+
+Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
+"""
+
+TEMPLATE_EXECUTION_CODE_GENERATION = """
+Based on the following analysis of an execution error, please generate the corrected code:
+
+Error Analysis:
+{analysis}
+
+Original Code:
+```python
+{generated_code}
+```
+
+Generate the corrected code, applying the suggestions from the analysis. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
+"""
+
+TEMPLATE_VALIDATION_ANALYSIS = """
+The current code's output does not match the required schema. Here are the details:
+
+Current Code:
+```python
+{generated_code}
+```
+
+Validation Errors:
+{errors}
+
+Required Schema:
+```json
+{json_schema}
+```
+
+Current Output:
+{execution_result}
+
+Please analyze the validation errors and suggest fixes. Focus only on correcting the output to match the required schema while ensuring the code maintains correct syntax and execution.
+
+Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
+"""
+
+TEMPLATE_VALIDATION_CODE_GENERATION = """
+Based on the following analysis of a validation error, please generate the corrected code:
+
+Error Analysis:
+{analysis}
+
+Original Code:
+```python
+{generated_code}
+```
+
+Required Schema:
+```json
+{json_schema}
+```
+
+Generate the corrected code, applying the suggestions from the analysis and ensuring the output matches the required schema. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
+"""
+
+TEMPLATE_SEMANTIC_COMPARISON = """
+Compare the Generated Result with the Reference Result and determine if they are semantically equivalent:
+
+Generated Result:
+{generated_result}
+
+Reference Result (Correct Output):
+{reference_result}
+
+Analyze the content, structure, and meaning of both results. They should be considered semantically equivalent if they convey the same information, even if the exact wording or structure differs.
+If they are not semantically equivalent, identify what are the key differences in the Generated Result. The Reference Result should be considered the correct output, you need to pinpoint the problems in the Generated Result.
+
+{format_instructions}
+
+Human: Are the generated result and reference result semantically equivalent? If not, what are the key differences?
+
+Assistant: Let's analyze the two results carefully:
+"""
+
+TEMPLATE_SEMANTIC_ANALYSIS = """
+The current code's output is semantically different from the reference answer. Here are the details:
+
+Current Code:
+```python
+{generated_code}
+```
+
+Semantic Differences:
+{differences}
+
+Comparison Explanation:
+{explanation}
+
+Please analyze these semantic differences and suggest how to modify the code to produce a result that is semantically equivalent to the reference answer. Focus on addressing the key differences while maintaining the overall structure and functionality of the code.
+
+Provide your analysis and suggestions for fixing the semantic differences. DO NOT generate any code in your response.
+"""
+
+TEMPLATE_SEMANTIC_CODE_GENERATION = """
+Based on the following analysis of semantic differences, please generate the corrected code:
+
+Semantic Analysis:
+{analysis}
+
+Original Code:
+```python
+{generated_code}
+```
+
+Generated Result:
+{generated_result}
+
+Reference Result:
+{reference_result}
+
+Generate the corrected code, applying the suggestions from the analysis to make the output semantically equivalent to the reference result. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
+"""
\ No newline at end of file
diff --git a/scrapegraphai/prompts/html_analyzer_node_prompts.py b/scrapegraphai/prompts/html_analyzer_node_prompts.py
new file mode 100644
index 00000000..d7e6e342
--- /dev/null
+++ b/scrapegraphai/prompts/html_analyzer_node_prompts.py
@@ -0,0 +1,71 @@
+"""
+HTML analysis prompts helper
+"""
+
+
+TEMPLATE_HTML_ANALYSIS = """
+Task: Your job is to analyze the provided HTML code in relation to the initial scraping task analysis and provide all the necessary HTML information useful for implementing a function that extracts data from the given HTML string.
+
+**Initial Analysis**:
+{initial_analysis}
+
+**HTML Code**:
+```html
+{html_code}
+```
+
+**HTML Analysis Instructions**:
+1. Examine the HTML code and identify elements, classes, or IDs that correspond to each required data field mentioned in the Initial Analysis.
+2. Look for patterns or repeated structures that could indicate multiple items (e.g., product listings).
+3. Note any nested structures or relationships between elements that are relevant to the data extraction task.
+4. Discuss any additional considerations based on the specific HTML layout that are crucial for accurate data extraction.
+5. Recommend the specific strategy to use for scraping the content, remeber.
+
+**Important Notes**:
+- The function that the code generator is gonig to implement will receive the HTML as a string parameter, not as a live webpage.
+- No web scraping, automation, or handling of dynamic content is required.
+- The analysis should focus solely on extracting data from the static HTML provided.
+- Be precise and specific in your analysis, as the code generator will, possibly, not have access to the full HTML context.
+
+This HTML analysis will be used to guide the final code generation process for a function that extracts data from the given HTML string.
+Please provide only the analysis with relevant, specific information based on this HTML code. Avoid vague statements and focus on exact details needed for accurate data extraction.
+
+Focus on providing a concise, step-by-step analysis of the HTML structure and the key elements needed for data extraction. Do not include any code examples or implementation logic. Keep the response focused and avoid general statements.**
+
+**HTML Analysis for Data Extraction**:
+"""
+
+TEMPLATE_HTML_ANALYSIS_WITH_CONTEXT = """
+Task: Your job is to analyze the provided HTML code in relation to the initial scraping task analysis and the additional context the user provided and provide all the necessary HTML information useful for implementing a function that extracts data from the given HTML string.
+
+**Initial Analysis**:
+{initial_analysis}
+
+**HTML Code**:
+```html
+{html_code}
+```
+
+**Additional Context**:
+{additional_context}
+
+**HTML Analysis Instructions**:
+1. Examine the HTML code and identify elements, classes, or IDs that correspond to each required data field mentioned in the Initial Analysis.
+2. Look for patterns or repeated structures that could indicate multiple items (e.g., product listings).
+3. Note any nested structures or relationships between elements that are relevant to the data extraction task.
+4. Discuss any additional considerations based on the specific HTML layout that are crucial for accurate data extraction.
+5. Recommend the specific strategy to use for scraping the content, remeber.
+
+**Important Notes**:
+- The function that the code generator is gonig to implement will receive the HTML as a string parameter, not as a live webpage.
+- No web scraping, automation, or handling of dynamic content is required.
+- The analysis should focus solely on extracting data from the static HTML provided.
+- Be precise and specific in your analysis, as the code generator will, possibly, not have access to the full HTML context.
+
+This HTML analysis will be used to guide the final code generation process for a function that extracts data from the given HTML string.
+Please provide only the analysis with relevant, specific information based on this HTML code. Avoid vague statements and focus on exact details needed for accurate data extraction.
+
+Focus on providing a concise, step-by-step analysis of the HTML structure and the key elements needed for data extraction. Do not include any code examples or implementation logic. Keep the response focused and avoid general statements.**
+In your code do not include backticks.
+**HTML Analysis for Data Extraction**:
+"""
\ No newline at end of file
diff --git a/scrapegraphai/prompts/prompt_refiner_node_prompts.py b/scrapegraphai/prompts/prompt_refiner_node_prompts.py
new file mode 100644
index 00000000..edbb1498
--- /dev/null
+++ b/scrapegraphai/prompts/prompt_refiner_node_prompts.py
@@ -0,0 +1,63 @@
+"""
+Prompts refiner prompts helper
+"""
+
+TEMPLATE_REFINER = """
+**Task**: Analyze the user's request and the provided JSON schema to clearly map the desired data extraction.\n
+Break down the user's request into key components, and then explicitly connect these components to the
+corresponding elements within the JSON schema.
+
+**User's Request**:
+{user_input}
+
+**Desired JSON Output Schema**:
+```json
+{json_schema}
+```
+
+**Analysis Instructions**:
+1. **Break Down User Request:**
+* Clearly identify the core entities or data types the user is asking for.\n
+* Highlight any specific attributes or relationships mentioned in the request.\n
+
+2. **Map to JSON Schema**:
+* For each identified element in the user request, pinpoint its exact counterpart in the JSON schema.\n
+* Explain how the schema structure accommodates the user's needs.
+* If applicable, mention any schema elements that are not directly addressed in the user's request.\n
+
+This analysis will be used to guide the HTML structure examination and ultimately inform the code generation process.\n
+Please generate only the analysis and no other text.
+
+**Response**:
+"""
+
+TEMPLATE_REFINER_WITH_CONTEXT = """
+**Task**: Analyze the user's request, the provided JSON schema, and the additional context the user provided to clearly map the desired data extraction.\n
+Break down the user's request into key components, and then explicitly connect these components to the corresponding elements within the JSON schema.\n
+
+**User's Request**:
+{user_input}
+
+**Desired JSON Output Schema**:
+```json
+{json_schema}
+```
+
+**Additional Context**:
+{additional_context}
+
+**Analysis Instructions**:
+1. **Break Down User Request:**
+* Clearly identify the core entities or data types the user is asking for.\n
+* Highlight any specific attributes or relationships mentioned in the request.\n
+
+2. **Map to JSON Schema**:
+* For each identified element in the user request, pinpoint its exact counterpart in the JSON schema.\n
+* Explain how the schema structure accommodates the user's needs.\n
+* If applicable, mention any schema elements that are not directly addressed in the user's request.\n
+
+This analysis will be used to guide the HTML structure examination and ultimately inform the code generation process.\n
+Please generate only the analysis and no other text.
+
+**Response**:
+"""
\ No newline at end of file