-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
55 lines (41 loc) · 1.64 KB
/
Copy pathutils.py
File metadata and controls
55 lines (41 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""Shared utility functions used across Wcode modules."""
from pathlib import Path
import yaml
from litellm.utils import function_to_dict
from config import WORKDIR, get_logger
logger = get_logger(__name__)
def parse_frontmatter(text: str) -> tuple[dict, str]:
"""Parse YAML frontmatter from a markdown string.
Returns (metadata_dict, body_text). If no frontmatter is found,
returns ({}, original_text).
"""
if not text.startswith("---"):
return {}, text
parts = text.split("---", 2)
if len(parts) < 3:
return {}, text
try:
meta = yaml.safe_load(parts[1]) or {}
except yaml.YAMLError:
logger.exception("Failed to parse frontmatter YAML")
meta = {}
return meta, parts[2].strip()
def tool_def(func) -> dict:
"""Generate an OpenAI tool definition from a Python function.
Uses litellm's function_to_dict to inspect type hints and numpy-style
docstring, then wraps the result in the ``{"type": "function", "function": {...}}``
envelope expected by the OpenAI chat completions API.
"""
return {"type": "function", "function": function_to_dict(func)}
def safe_path(p: str) -> Path:
"""Resolve a relative path inside WORKDIR. Raises ValueError on escape."""
path = (WORKDIR / p).resolve()
if not path.is_relative_to(WORKDIR):
raise ValueError(f"Path escapes workspace: {p}")
return path
def get_final_answer(messages: list) -> str:
"""Return the last assistant message content from a message list."""
for msg in reversed(messages):
if msg.get("role") == "assistant":
return msg.get("content", "")
return ""