You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cbmc/specgen/util/util.py

36 lines
988 B

import os
import re
def file2str(filename):
res = ""
with open(filename,"r") as f:
for line in f.readlines():
res = res + line
return res
# Compile regex for code fence matching
FENCE_RE = re.compile(r"```[a-zA-Z+]*\n(.*?)```", re.DOTALL)
def parse_code_from_reply(content):
"""
Parse code from API response, handling various code block formats.
Supports C, C++, Java, and generic code blocks.
Accepts both raw content strings and response dictionaries.
"""
# Handle response dictionaries
if isinstance(content, dict) and 'choices' in content:
try:
content = content['choices'][0]['message']['content']
except Exception:
return ""
if not isinstance(content, str):
return ""
# Use regex to extract code from fenced blocks
m = FENCE_RE.search(content)
if m:
return m.group(1)
# If no code fence found, return the original content
return content