Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace the use of assert in non-test code #80

Merged
merged 14 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions autogen/agentchat/conversable_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from collections import defaultdict
import copy
import json
import logging
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from autogen import oai
from .agent import Agent
Expand All @@ -21,6 +22,9 @@ def colored(x, *args, **kwargs):
return x


logger = logging.getLogger(__name__)


class ConversableAgent(Agent):
"""(In preview) A class for generic conversable agents which can be configured as assistant or user proxy.

Expand Down Expand Up @@ -757,7 +761,11 @@ def generate_reply(
Returns:
str or dict or None: reply. None if no reply is generated.
"""
assert messages is not None or sender is not None, "Either messages or sender must be provided."
if all((messages is None, sender is None)):
error_msg = f"Either {messages=} or {sender=} must be provided."
sonichi marked this conversation as resolved.
Show resolved Hide resolved
logger.error(error_msg)
raise AssertionError(error_msg)

if messages is None:
messages = self._oai_messages[sender]

Expand Down Expand Up @@ -804,7 +812,11 @@ async def a_generate_reply(
Returns:
str or dict or None: reply. None if no reply is generated.
"""
assert messages is not None or sender is not None, "Either messages or sender must be provided."
if all((messages is None, sender is None)):
error_msg = f"Either {messages=} or {sender=} must be provided."
logger.error(error_msg)
raise AssertionError(error_msg)

if messages is None:
messages = self._oai_messages[sender]

Expand Down
10 changes: 8 additions & 2 deletions autogen/code_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
WIN32 = sys.platform == "win32"
PATH_SEPARATOR = WIN32 and "\\" or "/"

logger = logging.getLogger(__name__)


def infer_lang(code):
"""infer the language for the code.
Expand Down Expand Up @@ -250,7 +252,11 @@ def execute_code(
str: The error message if the code fails to execute; the stdout otherwise.
image: The docker image name after container run when docker is used.
"""
assert code is not None or filename is not None, "Either code or filename must be provided."
if all((code is None, filename is None)):
error_msg = f"Either {code=} or {filename=} must be provided."
logger.error(error_msg)
raise AssertionError(error_msg)

timeout = timeout or DEFAULT_TIMEOUT
original_filename = filename
if WIN32 and lang in ["sh", "shell"]:
Expand All @@ -276,7 +282,7 @@ def execute_code(
f".\\{filename}" if WIN32 else filename,
]
if WIN32:
logging.warning("SIGALRM is not supported on Windows. No timeout will be enforced.")
logger.warning("SIGALRM is not supported on Windows. No timeout will be enforced.")
result = subprocess.run(
cmd,
cwd=work_dir,
Expand Down
14 changes: 9 additions & 5 deletions autogen/math_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ def remove_boxed(string: str) -> Optional[str]:
"""
left = "\\boxed{"
try:
assert string[: len(left)] == left
assert string[-1] == "}"
if not all((string[: len(left)] == left, string[-1] == "}")):
raise AssertionError

return string[len(left) : -1]
except Exception:
return None
Expand Down Expand Up @@ -94,7 +95,8 @@ def _fix_fracs(string: str) -> str:
new_str += substr
else:
try:
assert len(substr) >= 2
if not len(substr) >= 2:
raise AssertionError
except Exception:
return string
a = substr[0]
Expand Down Expand Up @@ -129,7 +131,8 @@ def _fix_a_slash_b(string: str) -> str:
try:
a = int(a_str)
b = int(b_str)
assert string == "{}/{}".format(a, b)
if not string == "{}/{}".format(a, b):
raise AssertionError
new_string = "\\frac{" + str(a) + "}{" + str(b) + "}"
return new_string
except Exception:
Expand All @@ -143,7 +146,8 @@ def _remove_right_units(string: str) -> str:
"""
if "\\text{ " in string:
splits = string.split("\\text{ ")
assert len(splits) == 2
if not len(splits) == 2:
raise AssertionError
return splits[0]
else:
return string
Expand Down
29 changes: 20 additions & 9 deletions autogen/oai/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,23 +582,31 @@ def eval_func(responses, **data):
cls._prompts = space.get("prompt")
if cls._prompts is None:
cls._messages = space.get("messages")
assert isinstance(cls._messages, list) and isinstance(
cls._messages[0], (dict, list)
), "messages must be a list of dicts or a list of lists."
if not all((isinstance(cls._messages, list), isinstance(cls._messages[0], (dict, list)))):
error_msg = "messages must be a list of dicts or a list of lists."
logger.error(error_msg)
raise AssertionError(error_msg)
if isinstance(cls._messages[0], dict):
cls._messages = [cls._messages]
space["messages"] = tune.choice(list(range(len(cls._messages))))
else:
assert space.get("messages") is None, "messages and prompt cannot be provided at the same time."
assert isinstance(cls._prompts, (str, list)), "prompt must be a string or a list of strings."
if space.get("messages") is not None:
error_msg = "messages and prompt cannot be provided at the same time."
logger.error(error_msg)
raise AssertionError(error_msg)
if not isinstance(cls._prompts, (str, list)):
error_msg = "prompt must be a string or a list of strings."
logger.error(error_msg)
raise AssertionError(error_msg)
if isinstance(cls._prompts, str):
cls._prompts = [cls._prompts]
space["prompt"] = tune.choice(list(range(len(cls._prompts))))
cls._stops = space.get("stop")
if cls._stops:
assert isinstance(
cls._stops, (str, list)
), "stop must be a string, a list of strings, or a list of lists of strings."
if not isinstance(cls._stops, (str, list)):
error_msg = "stop must be a string, a list of strings, or a list of lists of strings."
logger.error(error_msg)
raise AssertionError(error_msg)
if not (isinstance(cls._stops, list) and isinstance(cls._stops[0], list)):
cls._stops = [cls._stops]
space["stop"] = tune.choice(list(range(len(cls._stops))))
Expand Down Expand Up @@ -969,7 +977,10 @@ def eval_func(responses, **data):
elif isinstance(agg_method, dict):
for key in metric_keys:
metric_agg_method = agg_method[key]
assert callable(metric_agg_method), "please provide a callable for each metric"
if not callable(metric_agg_method):
error_msg = "please provide a callable for each metric"
logger.error(error_msg)
raise AssertionError(error_msg)
result_agg[key] = metric_agg_method([r[key] for r in result_list])
else:
raise ValueError(
Expand Down
3 changes: 2 additions & 1 deletion autogen/retrieve_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ def split_text_to_chunks(
overlap: int = 10,
):
"""Split a long text into chunks of max_tokens."""
assert chunk_mode in {"one_line", "multi_lines"}
if chunk_mode not in {"one_line", "multi_lines"}:
raise AssertionError
if chunk_mode == "one_line":
must_break_at_empty_line = False
chunks = []
Expand Down
Loading