Serie: Humanoid
python
158 righe
· Aggiornato 2026-03-12
utils.py
Humanoid/May_12/RoboOS/slaver/tools/utils.py
#!/usr/bin/env python
# coding=utf-8
###############################################################
# Copyright 2025 BAAI. All rights reserved.
###############################################################
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ast
import base64
import json
import re
from io import BytesIO
from typing import TYPE_CHECKING, Any, Dict
import yaml
from flag_scale.flagscale.agent.collaboration import Collaborator
if TYPE_CHECKING:
from memory import AgentLogger
__all__ = ["AgentError"]
BASE_BUILTIN_MODULES = [
"collections",
"datetime",
"itertools",
"math",
"queue",
"random",
"re",
"stat",
"statistics",
"time",
"unicodedata",
]
def escape_code_brackets(text: str) -> str:
"""Escapes square brackets in code segments while preserving Rich styling tags."""
def replace_bracketed_content(match):
content = match.group(1)
cleaned = re.sub(
r"bold|red|green|blue|yellow|magenta|cyan|white|black|italic|dim|\s|#[0-9a-fA-F]{6}",
"",
content,
)
return f"\\[{content}\\]" if cleaned.strip() else f"[{content}]"
return re.sub(r"\[([^\]]*)\]", replace_bracketed_content, text)
class AgentError(Exception):
"""Base class for other agent-related exceptions"""
def __init__(self, message, logger: "AgentLogger"):
super().__init__(message)
self.message = message
logger.log_error(message)
def dict(self) -> Dict[str, str]:
return {"type": self.__class__.__name__, "message": str(self.message)}
class AgentMaxStepsError(AgentError):
"""Exception raised for errors in execution in the agent"""
pass
class AgentGenerationError(AgentError):
"""Exception raised for errors in generation in the agent"""
pass
def make_json_serializable(obj: Any) -> Any:
"""Recursive function to make objects JSON serializable"""
if obj is None:
return None
elif isinstance(obj, (str, int, float, bool)):
# Try to parse string as JSON if it looks like a JSON object/array
if isinstance(obj, str):
try:
if (obj.startswith("{") and obj.endswith("}")) or (
obj.startswith("[") and obj.endswith("]")
):
parsed = json.loads(obj)
return make_json_serializable(parsed)
except json.JSONDecodeError:
pass
return obj
elif isinstance(obj, (list, tuple)):
return [make_json_serializable(item) for item in obj]
elif isinstance(obj, dict):
return {str(k): make_json_serializable(v) for k, v in obj.items()}
elif hasattr(obj, "__dict__"):
# For custom objects, convert their __dict__ to a serializable format
return {
"_type": obj.__class__.__name__,
**{k: make_json_serializable(v) for k, v in obj.__dict__.items()},
}
else:
# For any other type, convert to string
return str(obj)
MAX_LENGTH_TRUNCATE_CONTENT = 20000
class ImportFinder(ast.NodeVisitor):
def __init__(self):
self.packages = set()
def visit_Import(self, node):
for alias in node.names:
# Get the base package name (before any dots)
base_package = alias.name.split(".")[0]
self.packages.add(base_package)
def visit_ImportFrom(self, node):
if node.module: # for "from x import y" statements
# Get the base package name (before any dots)
base_package = node.module.split(".")[0]
self.packages.add(base_package)
def encode_image_base64(image):
buffered = BytesIO()
image.save(buffered, format="PNG")
return base64.b64encode(buffered.getvalue()).decode("utf-8")
def make_image_url(base64_image):
return f"data:image/png;base64,{base64_image}"
class Config:
@classmethod
def load_config(cls, config_path="config.yaml"):
"""Initialize configuration"""
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
return config
Articoli correlati
Humanoid
python
Aggiornato 2026-03-12
run.py
run.py — python source code from the Humanoid learning materials (Humanoid/May_12/RoboOS/deploy/run.py).
Leggi l'articolo →
Humanoid
python
Aggiornato 2026-03-12
utils.py
utils.py — python source code from the Humanoid learning materials (Humanoid/May_12/RoboOS/deploy/utils.py).
Leggi l'articolo →
Humanoid
python
Aggiornato 2026-03-12
agent.py
agent.py — python source code from the Humanoid learning materials (Humanoid/May_12/RoboOS/master/agents/agent.py).
Leggi l'articolo →
Humanoid
python
Aggiornato 2026-03-12
planner.py
planner.py — python source code from the Humanoid learning materials (Humanoid/May_12/RoboOS/master/agents/planner.py).
Leggi l'articolo →
Humanoid
python
Aggiornato 2026-05-12
prompts.py
prompts.py — python source code from the Humanoid learning materials (Humanoid/May_12/RoboOS/master/agents/prompts.py).
Leggi l'articolo →
Humanoid
python
Aggiornato 2026-05-12
run.py
run.py — python source code from the Humanoid learning materials (Humanoid/May_12/RoboOS/master/run.py).
Leggi l'articolo →