Skip to content

Commit 2d2c719

Browse files
Template refactoring
1 parent d6a7702 commit 2d2c719

File tree

7 files changed

+377
-351
lines changed

7 files changed

+377
-351
lines changed

scrapegraphai/nodes/generate_code_node.py

Lines changed: 17 additions & 220 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@
2020
from jsonschema import validate, ValidationError
2121
import json
2222
import string
23+
from ..prompts import (
24+
TEMPLATE_INIT_CODE_GENERATION, TEMPLATE_SYNTAX_ANALYSIS, TEMPLATE_SYNTAX_CODE_GENERATION,
25+
TEMPLATE_EXECUTION_ANALYSIS, TEMPLATE_EXECUTION_CODE_GENERATION, TEMPLATE_VALIDATION_ANALYSIS,
26+
TEMPLATE_VALIDATION_CODE_GENERATION, TEMPLATE_SEMANTIC_COMPARISON, TEMPLATE_SEMANTIC_ANALYSIS,
27+
TEMPLATE_SEMANTIC_CODE_GENERATION
28+
)
2329

2430
class GenerateCodeNode(BaseNode):
2531
"""
@@ -232,47 +238,8 @@ def semantic_comparison_loop(self, state: dict) -> dict:
232238
return state
233239

234240
def generate_initial_code(self, state: dict) -> str:
235-
template_code_generator = """
236-
**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.
237-
238-
**User's Request**:
239-
{user_input}
240-
241-
**Desired JSON Output Schema**:
242-
```json
243-
{json_schema}
244-
```
245-
246-
**Initial Task Analysis**:
247-
{initial_analysis}
248-
249-
**HTML Code**:
250-
```html
251-
{html_code}
252-
```
253-
254-
**HTML Structure Analysis**:
255-
{html_analysis}
256-
257-
Based on the above analyses, generate the `extract_data(html: str) -> dict()` function that:
258-
1. Efficiently extracts the required data from the given HTML structure.
259-
2. Processes and structures the data according to the specified JSON schema.
260-
3. Returns the structured data as a dictionary.
261-
262-
Your code should be well-commented, explaining the reasoning behind key decisions and any potential areas for improvement or customization.
263-
264-
Use only the following pre-imported libraries:
265-
- BeautifulSoup from bs4
266-
- re
267-
268-
**Output ONLY the Python code of the extract_data function, WITHOUT ANY IMPORTS OR ADDITIONAL TEXT.**
269-
In your code do not include backticks.
270-
271-
**Response**:
272-
"""
273-
274241
prompt = PromptTemplate(
275-
template=template_code_generator,
242+
template=TEMPLATE_INIT_CODE_GENERATION,
276243
partial_variables={
277244
"user_input": state["user_input"],
278245
"json_schema": state["json_schema"],
@@ -288,78 +255,23 @@ def generate_initial_code(self, state: dict) -> str:
288255
return generated_code
289256

290257
def syntax_focused_analysis(self, state: dict) -> str:
291-
template = """
292-
The current code has encountered a syntax error. Here are the details:
293-
294-
Current Code:
295-
```python
296-
{generated_code}
297-
```
298-
299-
Syntax Error:
300-
{errors}
301-
302-
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.
303-
304-
Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
305-
"""
306-
307-
prompt = PromptTemplate(template=template, input_variables=["generated_code", "errors"])
258+
prompt = PromptTemplate(template=TEMPLATE_SYNTAX_ANALYSIS, input_variables=["generated_code", "errors"])
308259
chain = prompt | self.llm_model | StrOutputParser()
309260
return chain.invoke({
310261
"generated_code": state["generated_code"],
311262
"errors": state["errors"]["syntax"]
312263
})
313264

314265
def syntax_focused_code_generation(self, state: dict, analysis: str) -> str:
315-
template = """
316-
Based on the following analysis of a syntax error, please generate the corrected code, following the suggested fix.:
317-
318-
Error Analysis:
319-
{analysis}
320-
321-
Original Code:
322-
```python
323-
{generated_code}
324-
```
325-
326-
Generate the corrected code, applying the suggestions from the analysis. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
327-
"""
328-
329-
prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code"])
266+
prompt = PromptTemplate(template=TEMPLATE_SYNTAX_CODE_GENERATION, input_variables=["analysis", "generated_code"])
330267
chain = prompt | self.llm_model | StrOutputParser()
331268
return chain.invoke({
332269
"analysis": analysis,
333270
"generated_code": state["generated_code"]
334271
})
335272

336273
def execution_focused_analysis(self, state: dict) -> str:
337-
template = """
338-
The current code has encountered an execution error. Here are the details:
339-
340-
**Current Code**:
341-
```python
342-
{generated_code}
343-
```
344-
345-
**Execution Error**:
346-
{errors}
347-
348-
**HTML Code**:
349-
```html
350-
{html_code}
351-
```
352-
353-
**HTML Structure Analysis**:
354-
{html_analysis}
355-
356-
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.
357-
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.
358-
359-
Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
360-
"""
361-
362-
prompt = PromptTemplate(template=template, input_variables=["generated_code", "errors", "html_code", "html_analysis"])
274+
prompt = PromptTemplate(template=TEMPLATE_EXECUTION_ANALYSIS, input_variables=["generated_code", "errors", "html_code", "html_analysis"])
363275
chain = prompt | self.llm_model | StrOutputParser()
364276
return chain.invoke({
365277
"generated_code": state["generated_code"],
@@ -369,53 +281,15 @@ def execution_focused_analysis(self, state: dict) -> str:
369281
})
370282

371283
def execution_focused_code_generation(self, state: dict, analysis: str) -> str:
372-
template = """
373-
Based on the following analysis of an execution error, please generate the corrected code:
374-
375-
Error Analysis:
376-
{analysis}
377-
378-
Original Code:
379-
```python
380-
{generated_code}
381-
```
382-
383-
Generate the corrected code, applying the suggestions from the analysis. Output ONLY the corrected Python code, WITHOUT ANY ADDITIONAL TEXT.
384-
"""
385-
386-
prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code"])
284+
prompt = PromptTemplate(template=TEMPLATE_EXECUTION_CODE_GENERATION, input_variables=["analysis", "generated_code"])
387285
chain = prompt | self.llm_model | StrOutputParser()
388286
return chain.invoke({
389287
"analysis": analysis,
390288
"generated_code": state["generated_code"]
391289
})
392290

393291
def validation_focused_analysis(self, state: dict) -> str:
394-
template = """
395-
The current code's output does not match the required schema. Here are the details:
396-
397-
Current Code:
398-
```python
399-
{generated_code}
400-
```
401-
402-
Validation Errors:
403-
{errors}
404-
405-
Required Schema:
406-
```json
407-
{json_schema}
408-
```
409-
410-
Current Output:
411-
{execution_result}
412-
413-
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.
414-
415-
Provide your analysis and suggestions for fixing the error. DO NOT generate any code in your response.
416-
"""
417-
418-
prompt = PromptTemplate(template=template, input_variables=["generated_code", "errors", "json_schema", "execution_result"])
292+
prompt = PromptTemplate(template=TEMPLATE_VALIDATION_ANALYSIS, input_variables=["generated_code", "errors", "json_schema", "execution_result"])
419293
chain = prompt | self.llm_model | StrOutputParser()
420294
return chain.invoke({
421295
"generated_code": state["generated_code"],
@@ -425,26 +299,7 @@ def validation_focused_analysis(self, state: dict) -> str:
425299
})
426300

427301
def validation_focused_code_generation(self, state: dict, analysis: str) -> str:
428-
template = """
429-
Based on the following analysis of a validation error, please generate the corrected code:
430-
431-
Error Analysis:
432-
{analysis}
433-
434-
Original Code:
435-
```python
436-
{generated_code}
437-
```
438-
439-
Required Schema:
440-
```json
441-
{json_schema}
442-
```
443-
444-
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.
445-
"""
446-
447-
prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code", "json_schema"])
302+
prompt = PromptTemplate(template=TEMPLATE_VALIDATION_CODE_GENERATION, input_variables=["analysis", "generated_code", "json_schema"])
448303
chain = prompt | self.llm_model | StrOutputParser()
449304
return chain.invoke({
450305
"analysis": analysis,
@@ -470,27 +325,8 @@ def semantic_comparison(self, generated_result: Any, reference_result: Any) -> D
470325
]
471326
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
472327

473-
template = """
474-
Compare the Generated Result with the Reference Result and determine if they are semantically equivalent:
475-
476-
Generated Result:
477-
{generated_result}
478-
479-
Reference Result (Correct Output):
480-
{reference_result}
481-
482-
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.
483-
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.
484-
485-
{format_instructions}
486-
487-
Human: Are the generated result and reference result semantically equivalent? If not, what are the key differences?
488-
489-
Assistant: Let's analyze the two results carefully:
490-
"""
491-
492328
prompt = PromptTemplate(
493-
template=template,
329+
template=TEMPLATE_SEMANTIC_COMPARISON,
494330
input_variables=["generated_result", "reference_result"],
495331
partial_variables={"format_instructions": output_parser.get_format_instructions()}
496332
)
@@ -501,27 +337,8 @@ def semantic_comparison(self, generated_result: Any, reference_result: Any) -> D
501337
"reference_result": json.dumps(reference_result_dict, indent=2)
502338
})
503339

504-
def semantic_focused_analysis(self, state: dict, comparison_result: Dict[str, Any]) -> str:
505-
template = """
506-
The current code's output is semantically different from the reference answer. Here are the details:
507-
508-
Current Code:
509-
```python
510-
{generated_code}
511-
```
512-
513-
Semantic Differences:
514-
{differences}
515-
516-
Comparison Explanation:
517-
{explanation}
518-
519-
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.
520-
521-
Provide your analysis and suggestions for fixing the semantic differences. DO NOT generate any code in your response.
522-
"""
523-
524-
prompt = PromptTemplate(template=template, input_variables=["generated_code", "differences", "explanation"])
340+
def semantic_focused_analysis(self, state: dict, comparison_result: Dict[str, Any]) -> str:
341+
prompt = PromptTemplate(template=TEMPLATE_SEMANTIC_ANALYSIS, input_variables=["generated_code", "differences", "explanation"])
525342
chain = prompt | self.llm_model | StrOutputParser()
526343
return chain.invoke({
527344
"generated_code": state["generated_code"],
@@ -530,27 +347,7 @@ def semantic_focused_analysis(self, state: dict, comparison_result: Dict[str, An
530347
})
531348

532349
def semantic_focused_code_generation(self, state: dict, analysis: str) -> str:
533-
template = """
534-
Based on the following analysis of semantic differences, please generate the corrected code:
535-
536-
Semantic Analysis:
537-
{analysis}
538-
539-
Original Code:
540-
```python
541-
{generated_code}
542-
```
543-
544-
Generated Result:
545-
{generated_result}
546-
547-
Reference Result:
548-
{reference_result}
549-
550-
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.
551-
"""
552-
553-
prompt = PromptTemplate(template=template, input_variables=["analysis", "generated_code", "generated_result", "reference_result"])
350+
prompt = PromptTemplate(template=TEMPLATE_SEMANTIC_CODE_GENERATION, input_variables=["analysis", "generated_code", "generated_result", "reference_result"])
554351
chain = prompt | self.llm_model | StrOutputParser()
555352
return chain.invoke({
556353
"analysis": analysis,

0 commit comments

Comments
 (0)