Given the following functions, please identify common pattern and unify them as one single function that will find markdown code block marked with arbitrary user-provided tag like json/python/jsonl.
def extract_jsonl_from_response(self, response: str) -> List[Dict]:
"""
Extracts a JSONL (JSON Lines) markdown code block from an LLM response and parses it.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Args:
response (str): The LLM response containing a JSONL markdown code block.
Returns:
List[Dict]: A list of dictionaries parsed from the JSONL code block.
Raises:
ValueError: If no valid JSONL code block is found or parsing fails.
"""
lines = response.splitlines()
start, end = None, None
# Find the start and end of the JSONL block
for i, line in enumerate(lines):
if line.strip() == "```jsonl":
start = i + 1
elif line.strip() == "```" and start is not None:
end = i
break
if start is None or end is None:
raise ValueError("No JSONL markdown code block found in the response.")
jsonl_block = lines[start:end]
parsed_lines = []
try:
for line in jsonl_block:
parsed_lines.append(json.loads(line))
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse JSONL: {e}")
return parsed_lines
def extract_python_from_response(self, response: str) -> str:
"""
Extracts a Python code block from an LLM response.
Args:
response (str): The LLM response containing a Python code block.
Returns:
str: A string representing the Python code block.
Raises:
ValueError: If no valid Python code block is found.
"""
lines = response.splitlines()
start, end = None, None
# Find the start and end of the Python code block
for i, line in enumerate(lines):
if line.strip() == "```python":
start = i + 1
elif line.strip() == "```" and start is not None:
end = i
break
if start is None or end is None:
raise ValueError("No Python markdown code block found in the response.")
return "\n".join(lines[start:end])
Assistant
Unified Function to Extract Markdown Code Blocks
The provided functions share a common pattern of finding a markdown code block in a given response and extracting its content. We can unify these functions into a single function that takes an arbitrary user-provided tag.
Code
python
import json
from typing import List, Dict, Any
def extract_code_block_from_response(self, response: str, tag: str, parse_json: bool = False) -> Any:
"""
Extracts a markdown code block marked with a user-provided tag from an LLM response.
Args:
response (str): The LLM response containing a markdown code block.
tag (str): The tag marking the code block (e.g., json, python, jsonl).
parse_json (bool): Whether to parse the code block as JSON. Defaults to False.
Returns:
Any: The extracted code block. If parse_json is True, returns a list of dictionaries (for jsonl) or a dictionary (for json).
Raises:
ValueError: If no valid code block is found or parsing fails.
"""
lines = response.splitlines()
start, end = None, None
# Find the start and end of the code block
for i, line in enumerate(lines):
if line.strip() == f"```{tag}":
start = i + 1
elif line.strip() == "```" and start is not None:
end = i
break
if start is None or end is None:
raise ValueError(f"No markdown code block marked with '{tag}' found in the response.")
code_block = lines[start:end]
if parse_json:
if tag.lower() == "jsonl":
try:
return [json.loads(line) for line in code_block]
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse JSONL: {e}")
elif tag.lower() == "json":
try:
return json.loads("\n".join(code_block))
except json.JSONDecodeError as e:
raise ValueError(f"Failed to parse JSON: {e}")
else:
raise ValueError("JSON parsing is only supported for json and jsonl tags.")
return "\n".join(code_block)
# Example usage:
def extract_jsonl_from_response(self, response: str) -> List[Dict]:
return self.extract_code_block_from_response(response, "jsonl", parse_json=True)
def extract_python_from_response(self, response: str) -> str:
return self.extract_code_block_from_response(response, "python")
def extract_json_from_response(self, response: str) -> Dict:
return self.extract_code_block_from_response(response, "json", parse_json=True)
The unified function extract_code_block_from_response takes three parameters:
response: The LLM response containing a markdown code block.
tag: The tag marking the code block (e.g., json, python, jsonl).
parse_json: A boolean indicating whether to parse the code block as JSON. Defaults to False.
The function returns the extracted code block. If parse_json is True, it returns a list of dictionaries (for jsonl) or a dictionary (for json).
You can use this function to extract code blocks marked with different tags, and it supports JSON parsing for json and jsonl tags. The example usage demonstrates how to define specific functions for extracting JSONL, Python, and JSON code blocks using the unified function.