Skip to content

Commit 5e856c5

Browse files
committed
style: apply Black formatting
1 parent be9d166 commit 5e856c5

11 files changed

Lines changed: 84 additions & 26 deletions

File tree

__init__.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@
2323
__version__ = "1.1"
2424

2525
# XXX Replace this with an appropriate author or supybot.Author instance.
26-
__author__ = supybot.Author("Barry Suridge", "Alcheri", "barry.suridge@gmail.com")
26+
__author__ = supybot.Author(
27+
"Barry Suridge", "Alcheri", "barry.suridge@gmail.com"
28+
)
2729
# This is a dictionary mapping supybot.Author instances to lists of
2830
# contributions.
2931
__contributors__ = {}
@@ -47,7 +49,10 @@
4749
except ImportError as e:
4850
missing_names = {"test", f"{__name__}.test"}
4951
missing_test_import = "cannot import name 'test'" in str(e)
50-
if getattr(e, "name", None) not in missing_names and not missing_test_import:
52+
if (
53+
getattr(e, "name", None) not in missing_names
54+
and not missing_test_import
55+
):
5156
raise
5257

5358
Class = plugin.Class

config/runtime.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,15 @@ def get_config() -> dict[str, Any]:
5858
"max_tokens": _to_int(
5959
plugin_conf.maxUserTokens(), default_config["max_tokens"]
6060
),
61-
"cooldown": _to_int(plugin_conf.cooldownSeconds(), default_config["cooldown"]),
62-
"irc_chunk": _to_int(plugin_conf.ircChunkSize(), default_config["irc_chunk"]),
61+
"cooldown": _to_int(
62+
plugin_conf.cooldownSeconds(), default_config["cooldown"]
63+
),
64+
"irc_chunk": _to_int(
65+
plugin_conf.ircChunkSize(), default_config["irc_chunk"]
66+
),
6367
"botnick": _to_str(plugin_conf.botnick(), default_config["botnick"]),
64-
"language": _to_str(plugin_conf.language(), default_config["language"]),
68+
"language": _to_str(
69+
plugin_conf.language(), default_config["language"]
70+
),
6571
"debug": _to_bool(plugin_conf.debugMode(), default_config["debug"]),
6672
}

cooldown.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ def should_wait_message(self, context_key, now, cooldown_s):
3434

3535
if delta < cd:
3636
wait_time = int(cd - delta) + 1
37-
return "Please wait {}s before sending another request.".format(wait_time)
37+
return "Please wait {}s before sending another request.".format(
38+
wait_time
39+
)
3840

3941
return None
4042

core/__init__.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
from .chat import chat_with_model, execute_chat_with_input_moderation
2-
from .text import clean_output, count_tokens, is_likely_math, split_irc_reply_lines
2+
from .text import (
3+
clean_output,
4+
count_tokens,
5+
is_likely_math,
6+
split_irc_reply_lines,
7+
)
38

49
__all__ = [
510
"chat_with_model",

core/chat.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,14 @@ async def chat_with_model(
2121
context_key: str,
2222
config: dict[str, Any],
2323
*,
24-
get_history_fn: Callable[[str, str], list[dict[str, str]]] = get_user_history,
24+
get_history_fn: Callable[
25+
[str, str], list[dict[str, str]]
26+
] = get_user_history,
2527
trim_history_fn: Callable[[str], list[dict[str, str]]] = trim_history,
2628
ensure_openai_client_fn: Callable[[], Any] = ensure_openai_client,
27-
create_completion_fn: Callable[..., Any] = create_chat_completion_with_fallback,
29+
create_completion_fn: Callable[
30+
..., Any
31+
] = create_chat_completion_with_fallback,
2832
) -> str:
2933
math_mode = is_likely_math(user_message)
3034

@@ -82,7 +86,9 @@ async def execute_chat_with_input_moderation(
8286
*,
8387
cooldown_manager: Any,
8488
check_moderation_flag_fn: Callable[[str], Any] = check_moderation_flag,
85-
chat_with_model_fn: Callable[[str, str, dict[str, Any]], Any] = chat_with_model,
89+
chat_with_model_fn: Callable[
90+
[str, str, dict[str, Any]], Any
91+
] = chat_with_model,
8692
count_tokens_fn: Callable[[str | None], int] = count_tokens,
8793
now_fn: Callable[[], float] = time.time,
8894
) -> str:

core/text.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@ def clean_output(text: str | None) -> str:
3232
return cleaned.strip()
3333

3434

35-
def split_irc_reply_lines(text: str | None, chunk_size: int = 350) -> list[str]:
35+
def split_irc_reply_lines(
36+
text: str | None, chunk_size: int = 350
37+
) -> list[str]:
3638
payload = (text or "").strip()
3739
if not payload:
3840
return []

plugin.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ def chat(self, irc, msg, args, user_input):
5252

5353
# ---- Pre-cooldown check (UX polish) ----
5454
now = time.time()
55-
msg_wait = COOLDOWNS.should_wait_message(context_key, now, config["cooldown"])
55+
msg_wait = COOLDOWNS.should_wait_message(
56+
context_key, now, config["cooldown"]
57+
)
5658

5759
if msg_wait:
5860
irc.reply(msg_wait, prefixNick=False)
@@ -80,21 +82,28 @@ def chat(self, irc, msg, args, user_input):
8082
)
8183
)
8284

83-
chunks = split_irc_reply_lines(response, chunk_size=config["irc_chunk"])
85+
chunks = split_irc_reply_lines(
86+
response, chunk_size=config["irc_chunk"]
87+
)
8488
if not chunks:
8589
irc.reply("AI returned no response.", prefixNick=False)
8690
else:
8791
for chunk in chunks:
8892
irc.reply(chunk, prefixNick=False)
8993

9094
if config["debug"]:
91-
log.info("[Asyncio DEBUG] {}: {}".format(context_key, response))
95+
log.info(
96+
"[Asyncio DEBUG] {}: {}".format(context_key, response)
97+
)
9298

9399
except Exception as error:
94100
log.error(
95-
"[Asyncio] Exception in chat command: {}".format(error), exc_info=True
101+
"[Asyncio] Exception in chat command: {}".format(error),
102+
exc_info=True,
103+
)
104+
irc.reply(
105+
"An unexpected error occurred. Check logs.", prefixNick=False
96106
)
97-
irc.reply("An unexpected error occurred. Check logs.", prefixNick=False)
98107

99108
def resetCommand(self, irc, msg, args):
100109
"""Reset your conversation memory for this channel (or PM)."""

services/openai_client.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ def _chat_model_candidates() -> list[str]:
2727
"""Ordered model fallback list for chat completions."""
2828
env_value = os.getenv("OPENAI_CHAT_MODELS", "")
2929
if env_value.strip():
30-
models = [model.strip() for model in env_value.split(",") if model.strip()]
30+
models = [
31+
model.strip() for model in env_value.split(",") if model.strip()
32+
]
3133
if models:
3234
return models
3335

@@ -70,7 +72,9 @@ def create_chat_completion_with_fallback(
7072
**kwargs,
7173
)
7274
if state.active_chat_model != model_name:
73-
log.warning("[Asyncio] Chat model switched to '{}'".format(model_name))
75+
log.warning(
76+
"[Asyncio] Chat model switched to '{}'".format(model_name)
77+
)
7478
state.active_chat_model = model_name
7579
return response
7680
except Exception as error:
@@ -89,7 +93,9 @@ def create_chat_completion_with_fallback(
8993
raise RuntimeError("No chat model candidates configured.")
9094

9195

92-
def ensure_openai_client(runtime_state: OpenAIRuntimeState | None = None) -> Any:
96+
def ensure_openai_client(
97+
runtime_state: OpenAIRuntimeState | None = None,
98+
) -> Any:
9399
state = runtime_state or OPENAI_RUNTIME
94100
if state.client is not None:
95101
return state.client

state/memory.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,13 @@ def make_context_key(msg: Any) -> str:
1111
return f"{channel}:{nick}"
1212

1313

14-
def get_user_history(context_key: str, system_prompt: str) -> list[dict[str, str]]:
14+
def get_user_history(
15+
context_key: str, system_prompt: str
16+
) -> list[dict[str, str]]:
1517
if context_key not in USER_HISTORIES:
16-
USER_HISTORIES[context_key] = [{"role": "system", "content": system_prompt}]
18+
USER_HISTORIES[context_key] = [
19+
{"role": "system", "content": system_prompt}
20+
]
1721
return USER_HISTORIES[context_key]
1822

1923
history = USER_HISTORIES[context_key]
@@ -27,7 +31,9 @@ def get_user_history(context_key: str, system_prompt: str) -> list[dict[str, str
2731
return history
2832

2933

30-
def trim_history(context_key: str, max_messages: int = 12) -> list[dict[str, str]]:
34+
def trim_history(
35+
context_key: str, max_messages: int = 12
36+
) -> list[dict[str, str]]:
3137
history = USER_HISTORIES.get(context_key, [])
3238
if len(history) > max_messages:
3339
USER_HISTORIES[context_key] = [history[0]] + history[-10:]

tests/test_core_chat.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ def should_wait_message(self, context_key, now, cooldown):
2323
return "Please wait 1s before sending another request."
2424

2525
def record(self, context_key, now):
26-
raise AssertionError("record should not be called when cooldown blocks")
26+
raise AssertionError(
27+
"record should not be called when cooldown blocks"
28+
)
2729

2830

2931
class CoreChatTestCase(unittest.IsolatedAsyncioTestCase):
@@ -59,7 +61,13 @@ async def fake_chat_with_model(user_request, context_key, config):
5961
self.assertEqual(response, "ok")
6062
self.assertEqual(
6163
events,
62-
["cooldown_check", "cooldown_record", "count_tokens", "moderation", "chat"],
64+
[
65+
"cooldown_check",
66+
"cooldown_record",
67+
"count_tokens",
68+
"moderation",
69+
"chat",
70+
],
6371
)
6472

6573
async def test_cooldown_blocks_early(self):
@@ -120,4 +128,6 @@ async def fake_chat_with_model(_a, _b, _c):
120128
)
121129

122130
self.assertIn("flagged as inappropriate", response)
123-
self.assertEqual(events, ["cooldown_check", "cooldown_record", "moderation"])
131+
self.assertEqual(
132+
events, ["cooldown_check", "cooldown_record", "moderation"]
133+
)

0 commit comments

Comments
 (0)