-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuse_ai.py
More file actions
1588 lines (1389 loc) · 61.7 KB
/
use_ai.py
File metadata and controls
1588 lines (1389 loc) · 61.7 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import logging
import re
import argparse
import threading
from typing import Any, NamedTuple, Protocol, Callable, Iterator, cast
from compare_mathml_in_csv import setMathCATPreferences, areCanonicallyEqual, CanonicalResults
from dataclasses import dataclass
from enum import StrEnum
import xml.etree.ElementTree as ET
import yaml
import os
import sys
sys.stdout.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
# Conditional imports based on AI provider
try:
from google import genai
from google.genai import types
from google.api_core import exceptions as google_exceptions
GEMINI_IMPORT_ERROR = None
except ImportError:
GEMINI_IMPORT_ERROR = ImportError(
"Google GenAI library not available. Install with: pip install google-genai"
)
try:
from openai import OpenAI
from openai import APIError, RateLimitError, APIConnectionError
OPENAI_IMPORT_ERROR = None
except ImportError:
OPENAI_IMPORT_ERROR = ImportError(
"OpenAI library not available. Install with: pip install openai"
)
# Configure simple logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger("google_genai").setLevel(logging.WARNING)
logging.getLogger("openai").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
BRAILLE_REGEX = re.compile(r'([\u2800-\u28ff]+)')
MATHML_REGEX: re.Pattern[str] = re.compile(r'<math.*?</math>')
# ============================================================
# this comes from alt_use_ai.py
# ============================================================
class BrailleCode(StrEnum):
NEMETH = "nemeth"
UEB = "ueb"
@dataclass(slots=True)
class MathExample:
mathml: str
braille: str
code: BrailleCode
@dataclass(slots=True)
class SymbolMapping:
char: str
nemeth: str | None = None
nemeth_numeric: str | None = None
ueb: str | None = None
reverse_hint: str | None = None
class RunConfig(NamedTuple):
"""Configuration values for an AI API run."""
braille_code: BrailleCode
gen_braille: bool
ai_provider: str
model: str
service_tier: str
apiKeyName: str
batch_size: int
start_index: int
n_examples: int
symbol_mappings: list[SymbolMapping]
example_braille_file: str
example_mathml_file: str
input_braille_file: str
input_mathml_file: str
def print_config(self, n_tests: int | None = None, short: bool = False) -> str:
"""Return configuration values as a formatted string."""
lines = []
lines.append("\nConfiguration:")
lines.append(f" Braille Code: {self.braille_code}")
lines.append(f" Generate Braille: {self.gen_braille}")
lines.append(f" Model: {self.model} {'(' + self.service_tier + ')' if self.ai_provider == 'openai' else ''}")
lines.append(f" API Key: {self.apiKeyName}")
lines.append(f" Batch Size: {self.batch_size}")
lines.append(f" Number of Examples: {self.n_examples}")
if n_tests is not None:
lines.append(f" Number of Tests: {n_tests} starting at {self.start_index}")
lines.append(f" Example Braille File: {self.example_braille_file}")
lines.append(f" Example MathML File: {self.example_mathml_file}")
lines.append(f" Input Braille Dir: {self.input_braille_file}")
lines.append(f" Input MathML Dir: {self.input_mathml_file}")
return "\n".join(lines)
# ============================================================
# Prompt Builders (Unified)
# ============================================================
def build_instructions(
config: RunConfig,
symbol_block: str,
) -> str:
if config.gen_braille:
header = (
f"You are an expert MathML to {config.braille_code.value.upper()} Braille translator.\n"
)
example_prolog = (
"Use the following pairs of examples to infer the correct mapping from MathML to"
f" {config.braille_code.value.upper()} braille.\n\n"
)
test_prolog = (
f"After the examples, translate the following MathML expressions into "
f"{config.braille_code.value.upper()} Braille. "
"Each MathML is numbered and on its own line\n"
"Return ONLY Unicode braille characters. "
"It is important to pay attention to generating Unicode braille spaces when needed in the braille.\n"
"Relational operators such as <, >, ≤, ≥, =, ≠ almost always need to have spaces on the left and right "
"unless they are in a script position.\n"
)
if config.braille_code == BrailleCode.NEMETH:
test_prolog += (
"Some things to remember about Nemeth Braille: \n"
"- the number sign indicator ⠼ that precedes digits is ONLY needed in these two cases: \n"
" 1. at the start of a line, after a space, or after punctuation. \n"
" 2. if a digit follows a minus sign that is at the start of a line, after a space, or after "
"punctuation.\n"
"- the English letter indicator ⠰ that precedes Roman letters is ONLY needed in these five cases:\n"
" 1. after a space;\n"
" 2. before a single lowercase English letter when it is isolated or followed only by punctuation, "
'potentially with intervening open or close characters;\n'
" 3. if the MathML consists of only an 'mi' or 'mtext' element, "
"and that element contains a single letter;\n"
" 4. if the letter is in bold, italic, or some other non-Roman style;\n"
" 5. if the lowercase letter is part of a Roman numeral.\n"
"- the English letter indicator ⠰ is NEVER needed between two Roman letters, "
"following a function name, before an operator, or after an operator.\n"
"- a letter with an integer subscript should NOT use a subscript indicator if the subscript is not "
"inside of a subscript or superscript.\n"
"- the braille should never start or end with a braille space."
)
else: # UEB
test_prolog += (
"Some things to remember about UEB Braille:\n"
"- grade 1 symbol indicators ⠰, grade 1 word indicators ⠰⠰, and grade 1 passage indicators ⠰⠰⠰ are "
"often needed at the start of a line.\n"
"- in general, you want to minimize the use of grade 1 symbol indicators. "
"Use them only when they result in shorter braille than using grade 1 word or passage indicators. "
"If there are more than two braille spaces (⠀), and a grade 1 indicator is needed "
"in the first three braille characters, use the grade 1 passage indicators.\n"
"- A grade 1 indicator only sets grade 1 mode for the next symbol and is not needed "
"before the letters 'a', 'i', and 'o'.\n"
"- A grade 1 word indicator only sets grade 1 mode until the next space.\n"
"- A number sign indicator ⠼ sets grade 1 word mode.\n"
"- A letter or unbroken sequence of letters is 'standing alone' if the symbols before and after the "
"letter or sequence are spaces, hyphens, dashes, or any combination thereof, including some common "
"punctuation. An opening bracketing character before a sequence or closing bracketing character after "
"a sequence should be included in the above definition of 'standing alone'. A single letter (excluding "
"a, i and o) is considered 'standing alone' if it is preceded by a space.\n"
"- A grade 1 indicator ⠰ is needed before a standing alone letter or sequence of letters.\n"
"- the number sign indicator ⠼ is ONLY needed before digits and starts numeric mode.\n"
"- All fraction, root, subscript, superscript, etc., start, middle, and end indicators MUST "
"be in grade 1 mode; a grade 1 indicator is required before the fraction, etc., indicator if it is not "
" already in grade 1 mode.\n"
"- Numeric mode includes the digits and the fraction line (⠌) for simple numeric fractions. It also "
"includes ',', '.', and spaces when they appear inside of MathML mn elements.\n"
"- if the lowercase letters a-j follow a digit, you MUST use a grade 1 indicator ⠰ before the letter.\n"
"- numeric fraction do not use start or end fraction indicators, but all other fractions start with ⠷, "
"end with ⠾, and use ⠨⠌ as the fraction bar.\n"
"- all subscripts MUST start with the subscript indicator ⠢, and must be in grade 1 mode.\n"
)
symbols_text = (
"Here is a reminder of the mapping of some Unicode characters to their "
f"representation in {config.braille_code.value.upper()} braille that you may need to use:\n"
f"{symbol_block}"
)
test_prolog += (
"Do NOT include the input line numbers (e.g., '1)').\n"
"Add '|next-item|' between each braille output.\n"
)
else:
header = (
f"You are a expert {config.braille_code.value.upper()} braille to MathML translator.\n"
"Use the following pairs of examples to infer the correct mapping from"
f" {config.braille_code.value.upper()} braille to MathML.\n\n"
)
test_prolog = (
f"Now translate the following {config.braille_code.value.upper()} Braille into MathML.\n"
"Return ONLY valid MathML markup. MathML must start with a <math> tag and end with a </math> tag. "
"Do NOT include the input line numbers (e.g., '1)', '2)', etc.).\n"
"Add '|next-item|' between each MathML output."
)
symbols_text = (
f"Here is a reminder of the mapping of some Unicode {config.braille_code.value.upper()}"
f"braille characters and how they map to Unicode non-braille characters"
f"that you may need to use:\n{symbol_block}\n\n"
)
example_prolog = (
"Use the following pairs of examples to infer the correct mapping from "
f" {config.braille_code.value.upper()} braille to MathML.\n\n"
)
with open("debug.log", "a", encoding="utf-8") as f:
f.write(f"Instructions: {header + symbols_text + example_prolog}\n{test_prolog}\n\n\n")
return header + symbols_text + example_prolog + test_prolog
class UsageMetadata(Protocol):
"""Protocol for usage metadata objects."""
prompt_token_count: int
candidates_token_count: int
total_token_count: int
class OpenAIUsageMetadata:
"""Simple class to hold token usage information for GPT."""
def __init__(self, prompt_tokens: int = 0, completion_tokens: int = 0, total_tokens: int = 0):
self.prompt_token_count = prompt_tokens
self.candidates_token_count = completion_tokens
self.total_token_count = total_tokens
class AIClient(Protocol):
"""Protocol for AI clients."""
pass
def create_gemini_client(api_key: str) -> genai.Client:
"""Create and return a Gemini client."""
return genai.Client(api_key=api_key, http_options={"timeout": 2400000})
def create_openai_client(api_key: str) -> OpenAI:
"""Create and return a GPT client."""
return OpenAI(api_key=api_key, timeout=2400.0)
def _generate_with_retry_common(
client: Any,
config: RunConfig,
examples: list[dict[str, Any]],
tests: list[str],
symbol_block: str,
gemini_cache_id: str,
max_retries: int,
depth: int,
create_stream_func: Callable[[genai.Client, RunConfig, list[dict[str, Any]], str, str, str], Iterator[Any]],
process_chunk_func: Callable[[genai.Client, list[str]], tuple[str | None, Any | None, str | None] | None],
get_fallback_usage_func: Callable[
[Any, RunConfig, list[dict[str, Any]], str],
tuple[Any | None, str | None] | None
] | None,
is_max_tokens_func: Callable[[str | None], bool],
is_success_finish_func: Callable[[str | None], bool],
handle_retry_exception_func: Callable[[Exception, int, int, str, str], tuple[bool, str | None]],
sum_usage_func: Callable[[Any, Any], Any],
default_error_usage: Any,
recursive_call_func: Callable[
[Any, RunConfig, list[dict[str, Any]], list[str], str, str, int, int],
tuple[str, Any, float]
]
) -> tuple[str, Any, float]:
"""Common retry logic shared between Gemini and GPT."""
indent = " " * depth
t0 = time.perf_counter()
time_to_first_token = -1000.0
delay = 30
full_text_list: list[str] = []
final_usage: Any = default_error_usage
run_info = f"{'to-' if config.gen_braille else 'from-'}{config.braille_code}"
for attempt in range(1, max_retries + 1):
try:
# Add line numbers to content
numbered_tests = "\n".join(f"{i}) {s}" for i, s in enumerate(tests, 1))
response_stream = create_stream_func(
client, config, examples, numbered_tests, symbol_block, gemini_cache_id
)
full_text_list = []
first_token_received = False
final_usage = default_error_usage
finish_reason = None
for chunk in response_stream:
if not first_token_received:
time_to_first_token = time.perf_counter() - t0
print(f"⚡ Time to First Token for {run_info}: {time_to_first_token:.2f} seconds")
first_token_received = True
chunk_result = process_chunk_func(chunk, full_text_list)
if chunk_result:
text, usage, reason = chunk_result
if text:
full_text_list.append(text)
if usage is not None:
final_usage = usage
if reason is not None:
finish_reason = reason
# Try to get usage from fallback if not available (GPT only)
if (
get_fallback_usage_func
and hasattr(final_usage, 'total_token_count')
and final_usage.total_token_count == 0
):
fallback_result = get_fallback_usage_func(
client,
config,
examples,
numbered_tests
)
if fallback_result:
fallback_usage, fallback_reason = fallback_result
if fallback_usage is not None:
final_usage = fallback_usage
if fallback_reason is not None:
finish_reason = fallback_reason
if is_max_tokens_func(finish_reason):
raise ValueError("MAX_TOKENS")
if not is_success_finish_func(finish_reason):
raise Exception(f"Incomplete generation: {finish_reason}")
print(f"\n\n--- Performance Summary for {run_info} ---")
total_time = time.perf_counter() - t0
print(f"Total Latency: {total_time:.2f} s")
print(f"Time to 1st Token:{time_to_first_token:.2f} s")
print(f"Generation Time: {total_time - time_to_first_token:.2f} s (Streaming duration)")
return "".join(full_text_list), final_usage, total_time - time_to_first_token
except ValueError as e:
if str(e) != "MAX_TOKENS":
raise e
print(f"{indent}[!] In {run_info}: MAX_TOKENS hit on {len(tests)} lines.")
if len(tests) <= 1:
print(f"{indent}[X] Critical in {run_info}: Single input line is too large.")
raise e
mid = len(tests) // 2
left_part = tests[:mid]
right_part = tests[mid:]
print(f"{indent} -> Splitting: {len(left_part)} lines | {len(right_part)} lines")
text_a, usage_a, _ = recursive_call_func(
client, config, examples, left_part, symbol_block, gemini_cache_id, max_retries, depth + 1
)
text_b, usage_b, _ = recursive_call_func(
client, config, examples, right_part, symbol_block, gemini_cache_id, max_retries, depth + 1
)
if text_a is None or text_b is None:
return "Error", default_error_usage, time.perf_counter() - t0 - time_to_first_token
return (text_a + '|next-item|' + text_b,
sum_usage_func(usage_a, usage_b),
time.perf_counter() - t0 - time_to_first_token
)
except Exception as e:
should_retry, retry_msg = handle_retry_exception_func(e, attempt, max_retries, run_info, indent)
if should_retry:
print(f"{indent}{retry_msg} Retrying in {delay}s...")
time.sleep(delay)
delay *= 2
else:
print(f"{indent}Exception Type: {type(e).__name__}")
print(f"{indent}[X] Critical Error in {run_info}: {e}")
if len(full_text_list) > 0:
total_time = time.perf_counter() - t0
return "".join(full_text_list), final_usage, total_time - time_to_first_token
raise e
print(f"{indent}[X] Failed after max retries in {run_info}.")
if len(full_text_list) > 0:
total_time = time.perf_counter() - t0
return "".join(full_text_list), final_usage, total_time - time_to_first_token
else:
return "Error", default_error_usage, time.perf_counter() - t0 - time_to_first_token
def generate_with_retry_gemini(
client: genai.Client,
config: RunConfig,
examples: list[dict[str, Any]],
tests: list[str],
symbol_block: str,
gemini_cache_id: str,
max_retries: int = 3,
depth: int = 0
) -> tuple[str, Any, float]:
"""Generate with retry logic for Gemini API."""
def create_stream(
client: genai.Client,
config: RunConfig,
examples: list[dict[str, Any]],
numbered_tests: str,
symbol_block: str,
gemini_cache_id: str
) -> Iterator[Any]:
test_content = types.Content(
role="user",
parts=[types.Part.from_text(text=numbered_tests)]
)
is_gemma = "gemma" in config.model.lower()
gemini_config = types.GenerateContentConfig(
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold=types.HarmBlockThreshold.BLOCK_NONE,
)
],
temperature=0.0,
max_output_tokens=4096 if is_gemma else None,
)
if gemini_cache_id:
gemini_config.cached_content = gemini_cache_id
else:
gemini_config.system_instruction = build_instructions(config, symbol_block)
return client.models.generate_content_stream(
model=config.model,
config=gemini_config,
contents=[test_content] if gemini_cache_id else examples + [test_content],
)
def process_chunk(chunk: Any, full_text_list: list[str]) -> tuple[str | None, Any | None, str | None] | None:
text = chunk.text if hasattr(chunk, 'text') else None
usage = chunk.usage_metadata if hasattr(chunk, 'usage_metadata') else None
reason = chunk.candidates[0].finish_reason if (hasattr(chunk, 'candidates') and chunk.candidates) else None
return (text, usage, reason)
def is_max_tokens(finish_reason: str | None) -> bool:
return finish_reason == "MAX_TOKENS"
def is_success_finish(finish_reason: str | None) -> bool:
return finish_reason == "STOP"
def handle_retry_exception(
e: Exception,
attempt: int,
max_retries: int,
run_info: str,
indent: str
) -> tuple[bool, str | None]:
err = str(e)
if "503" in err or "UNAVAILABLE" in err:
return True, f"[!] 503 Unavailable (Attempt {attempt}/{max_retries}) {run_info}."
if "499" in err or "CANCELLED" in err:
return True, f"[!] 499 Cancelled (Attempt {attempt}/{max_retries}) {run_info}."
return False, None
return _generate_with_retry_common(
client=client,
config=config,
examples=examples,
tests=tests,
symbol_block=symbol_block,
gemini_cache_id=gemini_cache_id,
max_retries=max_retries,
depth=depth,
create_stream_func=create_stream,
process_chunk_func=process_chunk,
get_fallback_usage_func=None,
is_max_tokens_func=is_max_tokens,
is_success_finish_func=is_success_finish,
handle_retry_exception_func=handle_retry_exception,
sum_usage_func=_sum_usage_gemini,
default_error_usage=None,
recursive_call_func=generate_with_retry_gemini
)
def generate_with_retry_openai(
client: OpenAI,
config: RunConfig,
examples: list[dict[str, Any]],
tests: list[str],
symbol_block: str,
gemini_cache_id: str,
max_retries: int = 3,
depth: int = 0
) -> tuple[str, OpenAIUsageMetadata, float]:
"""Generate with retry logic for "OpenAI" API."""
messages_cache: list[dict[str, str]] | None = None
def create_stream(
client: OpenAI,
config: RunConfig,
examples: list[dict[str, Any]],
numbered_tests: str,
symbol_block: str,
gemini_cache_id: str
) -> Iterator[Any]:
nonlocal messages_cache
# Build messages array: system message, then examples (if list), then user/assistant for payload
messages_cache = [{"role": "system", "content": build_instructions(config, symbol_block)}]
# Insert example messages into the array
messages_cache.extend(examples)
messages_cache.extend([
{"role": "user", "content": numbered_tests}
])
return call_openai_model(
client=client,
config=config,
messages=messages_cache,
stream=True,
)
def process_chunk(
chunk: Any, full_text_list: list[str]
) -> tuple[str | None, OpenAIUsageMetadata | None, str | None] | None:
text: str | None = None
usage: OpenAIUsageMetadata | None = None
reason: str | None = None
if chunk.choices and len(chunk.choices) > 0:
delta = chunk.choices[0].delta
if delta and delta.content:
text = delta.content
if chunk.choices[0].finish_reason:
reason = chunk.choices[0].finish_reason
if chunk.usage:
usage = OpenAIUsageMetadata(
prompt_tokens=chunk.usage.prompt_tokens or 0,
completion_tokens=chunk.usage.completion_tokens or 0,
total_tokens=chunk.usage.total_tokens or 0
)
return (text, usage, reason)
def get_fallback_usage(
client: OpenAI,
config: RunConfig,
examples: list[dict[str, Any]],
payload_text: str
) -> tuple[OpenAIUsageMetadata | None, str | None] | None:
try:
if messages_cache is None:
return None
response = call_openai_model(
client=client,
config=config,
messages=messages_cache,
stream=False
)
usage = None
reason = None
if response.usage:
usage = OpenAIUsageMetadata(
prompt_tokens=response.usage.prompt_tokens or 0,
completion_tokens=response.usage.completion_tokens or 0,
total_tokens=response.usage.total_tokens or 0
)
if response.choices and len(response.choices) > 0:
reason = response.choices[0].finish_reason
return (usage, reason)
except Exception:
return (None, None)
def is_max_tokens(finish_reason: str | None) -> bool:
return finish_reason == "length"
def is_success_finish(finish_reason: str | None) -> bool:
return finish_reason == "stop"
def handle_retry_exception(
e: Exception,
attempt: int,
max_retries: int,
run_info: str,
indent: str
) -> tuple[bool, str | None]:
error_str = str(e)
if "rate_limit" in error_str.lower() or "429" in error_str or isinstance(e, RateLimitError):
return True, f"[!] Rate Limit Error (Attempt {attempt}/{max_retries}) {run_info}."
elif "connection" in error_str.lower() or isinstance(e, APIConnectionError):
return True, f"[!] Connection Error (Attempt {attempt}/{max_retries}) {run_info}."
return False, None
return _generate_with_retry_common(
client=client,
config=config,
examples=examples,
tests=tests,
symbol_block=symbol_block,
gemini_cache_id=gemini_cache_id,
max_retries=max_retries,
depth=depth,
create_stream_func=create_stream,
process_chunk_func=process_chunk,
get_fallback_usage_func=get_fallback_usage,
is_max_tokens_func=is_max_tokens,
is_success_finish_func=is_success_finish,
handle_retry_exception_func=handle_retry_exception,
sum_usage_func=_sum_usage_openai,
default_error_usage=OpenAIUsageMetadata(),
recursive_call_func=generate_with_retry_openai
)
def _sum_usage_gemini(usage1: Any, usage2: Any) -> Any:
"""Helper to sum two Gemini UsageMetadata objects."""
if not usage1:
return usage2
if not usage2:
return usage1
return types.GenerateContentResponseUsageMetadata(
prompt_token_count=usage1.prompt_token_count + usage2.prompt_token_count,
candidates_token_count=usage1.candidates_token_count + usage2.candidates_token_count,
total_token_count=usage1.total_token_count + usage2.total_token_count
)
def _sum_usage_openai(usage1: OpenAIUsageMetadata, usage2: OpenAIUsageMetadata) -> OpenAIUsageMetadata:
"""Helper to sum two GPT UsageMetadata objects."""
if not usage1:
return usage2
if not usage2:
return usage1
return OpenAIUsageMetadata(
prompt_tokens=usage1.prompt_token_count + usage2.prompt_token_count,
completion_tokens=usage1.candidates_token_count + usage2.candidates_token_count,
total_tokens=usage1.total_token_count + usage2.total_token_count
)
def call_openai_model(
client: OpenAI,
config: RunConfig,
messages: list[dict[str, str]],
stream: bool = True,
) -> Any:
"""
Call OpenAI model with the given messages.
Args:
client: OpenAI client instance
model: Model name to use
messages: List of message dicts with 'role' and 'content'
stream: Whether to stream the response
Returns:
If stream=True: Returns a stream object that can be iterated
If stream=False: Returns the full response object
"""
params: dict[str, Any] = {
"model": config.model,
"messages": messages,
"stream": stream,
"service_tier": config.service_tier,
"temperature": 0.1,
}
return client.chat.completions.create(**params)
def get_context_cache_id(
client: genai.Client,
config: RunConfig,
symbol_block: str,
examples: list[dict[str, Any]]
) -> types.CachedContent:
"""Get the cache id for the context of the examples and symbol block."""
cache_id = client.caches.create(
model=config.model,
config=types.CreateCachedContentConfig(
display_name='braille_translation_examples',
system_instruction=build_instructions(config, symbol_block),
contents=examples,
ttl="3600s",
)
)
time.sleep(15) # wait for the cache to be created -- was getting 503 and this is a suggested workaround
return cache_id
def convert_input_with_model(
config: RunConfig,
examples: list[dict[str, Any]],
tests: list[str],
) -> tuple[list[str], dict[str, int], float]:
"""
Returns
Splits input into batches, processes them with retries/streaming,
tracks token usage, and measures pure generation time.
"""
ai_provider = config.ai_provider.lower()
run_info = f"{'to-' if config.gen_braille else 'from-'}{config.braille_code}"
# Setup Client
api_key = os.environ.get(config.apiKeyName)
if not api_key:
raise ValueError(f"Please set the {config.apiKeyName} environment variable.")
# if ai_provider == "gemini":
# client = create_gemini_client(api_key)
# generate_func = generate_with_retry_gemini
# retry_exceptions = (google_exceptions.ServiceUnavailable, google_exceptions.ServerError)
# elif ai_provider == "openai":
# client = create_openai_client(api_key)
# generate_func = generate_with_retry_openai
# retry_exceptions = (APIError, RateLimitError, APIConnectionError)
# else:
# raise ValueError(f"Unknown AI provider: {ai_provider}. Must be 'gemini' or 'openai'")
# 1. Initialize accumulators
all_results = ""
total_tokens: dict[str, int] = {"prompt": 0, "candidates": 0, "total": 0}
total_generation_time: float = 0.0
first_attempt = True
# because we might batch the instructions, we need to extract the symbols from all the tests
paid_tier = False # TODO: apparently fails if this is an unpaid teir
if paid_tier and config.ai_provider == "gemini" and len(examples) > 300:
used_symbols = set().union(*(extract_symbols_from_mathml(test) for test in tests))
batch_symbol_block = build_symbol_block(
used_symbols,
config.symbol_mappings,
config.braille_code,
config.gen_braille
)
cached_content = get_context_cache_id(cast(genai.Client, client), config, batch_symbol_block, examples)
gemini_cache_id: str = cached_content.name if cached_content and cached_content.name else ""
else:
gemini_cache_id = ""
# 2. Loop through the data in chunks
for i in range(0, len(tests), config.batch_size):
# I thought we could do this once at the beginning, but it seems to be necessary to reestablish the connection when there are lots of batches
if ai_provider == "gemini":
client = create_gemini_client(api_key)
generate_func = generate_with_retry_gemini
retry_exceptions = (google_exceptions.ServiceUnavailable, google_exceptions.ServerError)
elif ai_provider == "openai":
client = create_openai_client(api_key)
generate_func = generate_with_retry_openai
retry_exceptions = (APIError, RateLimitError, APIConnectionError)
else:
raise ValueError(f"Unknown AI provider: {ai_provider}. Must be 'gemini' or 'openai'")
batch = tests[i:i + config.batch_size]
batch_id = (i // config.batch_size) + 1
print(
f"\n--- Processing Batch {batch_id} "
f"(Items {i+1} to {i+len(batch)}) "
f"{'to-' if config.gen_braille else 'from-'}{config.braille_code} ---"
)
if gemini_cache_id == "":
if config.gen_braille:
used_symbols = set().union(*(extract_symbols_from_mathml(test) for test in batch))
else:
used_symbols = set().union(*(extract_symbols_from_braille(test) for test in batch))
symbol_block = build_symbol_block(
used_symbols,
config.symbol_mappings,
config.braille_code,
config.gen_braille
)
else:
symbol_block = ""
# 3. Call helper (now returns duration too)
try:
batch_text, batch_usage, batch_time = generate_func(
cast(Any, client),
config,
examples,
batch,
symbol_block,
gemini_cache_id,
3
)
except retry_exceptions as e:
if first_attempt:
# reestablish connection and try one more time
if ai_provider == "gemini":
client = create_gemini_client(api_key)
else:
client = create_openai_client(api_key)
first_attempt = False
try:
batch_text, batch_usage, batch_time = generate_func(
cast(Any, client),
config,
examples,
batch,
symbol_block,
gemini_cache_id,
3
)
except Exception as e:
print(f"Exception raised during retry: {e}")
break
else:
print(f"Exception raised twice during generation: {e}")
batch_text, batch_usage, batch_time = None, None, 0.0
break
except Exception as e:
print(f"Exception raised during generation: {e}")
batch_text, batch_usage, batch_time = None, None, 0.0
break
# 4. Process results
if batch_text:
all_results += '|next-item|' + batch_text
# 5. Update stats
if batch_usage:
total_tokens["prompt"] += batch_usage.prompt_token_count
total_tokens["candidates"] += batch_usage.candidates_token_count
total_tokens["total"] += batch_usage.total_token_count
if batch_time:
total_generation_time += batch_time
print(f" > Batch Time: {batch_time:.2f}s")
if batch_usage:
print(f" > Batch Token Usage ({run_info}): {batch_usage.total_token_count} "
f"(Prompt: {batch_usage.prompt_token_count}, Output: {batch_usage.candidates_token_count})")
# delete the cache
if gemini_cache_id:
cast(genai.Client, client).caches.delete(name=gemini_cache_id)
# look at tests to see if we are generating MathML or braille
# trim the start and end, then split the string at '|next-item|' and return a list of strings
text = all_results
if config.gen_braille:
matches = list(BRAILLE_REGEX.finditer(text))
if not matches:
print(f"\n\n[!] Could not find braille chars in the response\n: '{text}'\n\n")
return [], total_tokens, total_generation_time
i_start = matches[0].start()
i_end = matches[-1].end()
regex = BRAILLE_REGEX
else:
i_start = text.find("<math")
i_end = text.rfind("</math>") + len("</math>")
if i_start == -1 or i_end == -1:
print(f"\n\n[!] Could not find braille chars in the response\n: '{text}'\n\n")
regex = MATHML_REGEX
# Return the substring including everything between the first and last Braille char/MathML start/end tags
as_list = []
for item in text[i_start:i_end].split("|next-item|"):
match = regex.search(item)
if match:
as_list.append(match.group(0).strip())
else:
as_list.append(item.strip())
return as_list, total_tokens, total_generation_time
# ============================================================
# Symbol Extraction + Structural Context
# ============================================================
def extract_symbols_from_mathml(mathml: str) -> set[str]:
root = ET.fromstring(mathml)
symbols: set[str] = set()
for elem in root.iter():
tag = elem.tag.split("}")[-1]
if tag in {"mo", "mi", "mn", "mtext"} and elem.text:
# if elem.text and not elem.text.strip().isalnum():
symbols.update(elem.text)
return symbols
def extract_symbols_from_braille(braille: str) -> set[str]:
return set(braille) if braille else set()
def extract_structural_context(mathml: str) -> list[str]:
root = ET.fromstring(mathml)
notes: list[str] = []
for elem in root.iter():
tag = elem.tag.split("}")[-1]
if tag == "mn" and elem.text:
if "," in elem.text or "." in elem.text:
notes.append("Comma inside <mn> → numeric comma.")
if tag == "mo" and elem.text:
if elem.text == "," or elem.text == ".":
notes.append("Comma as <mo> → argument separator.")
return sorted(set(notes))
def count_complicated_elements(mathml: str) -> int:
root = ET.fromstring(mathml)
count = 0
for elem in root.iter():
tag = elem.tag.split("}")[-1]
if tag in {"msub", "msup", "msubsup", "mmultiscripts",
"msqrt", "mroot",
"mfrac", "menclose",
"munder", "mover", "munderover",
"mtr", "mlabeledtr", "mtd", "mtable"}:
count += 1
return count
# ============================================================
# Symbol Mapping Blocks
# ============================================================
def _extract_first_t(obj: Any) -> str | None:
if isinstance(obj, dict):
if "t" in obj:
return obj["t"]
if "test" in obj:
tb: dict[str, Any] = obj["test"]
for key in ("then", "then_test"):
if key in tb:
for entry in tb[key]:
tval = _extract_first_t(entry)
if tval:
return tval
for key in ("else", "else_test"):
if key in tb:
for entry in tb[key]:
tval = _extract_first_t(entry)
if tval:
return tval
elif isinstance(obj, list):
for entry in obj:
tval = _extract_first_t(entry)
if tval:
return tval
return None
def _load_yaml_mapping_file_simple(path: str) -> dict[str, str]:
"""
Loads a YAML file where the top-level structure is a LIST.
Each list item may be:
A) {char: "(", rules: [...]}
B) {"(": [ ...rule objects... ]}
Returns:
{ char: first_braille_t }
"""
with open(path, "r", encoding="utf-8") as f:
raw = yaml.safe_load(f) or []
result: dict[str, str] = {}
for entry in raw:
# ----------------------------
# Case A: explicit fields
# ----------------------------
if isinstance(entry, dict) and "char" in entry:
char = entry["char"]
rules = entry.get("rules", [])
tval = _extract_first_t(rules)
if tval:
result[char] = tval
continue
# ----------------------------
# Case B: {"(": [ ... ]}
# ----------------------------
if isinstance(entry, dict) and len(entry) == 1:
char, rules = next(iter(entry.items()))
tval = _extract_first_t(rules)
if tval:
result[char] = tval
continue
raise ValueError(f"Unrecognized YAML mapping entry: {entry}")
return result
def load_symbol_mappings(nemeth_path: str, ueb_path: str) -> list[SymbolMapping]:
nemeth_map = _load_yaml_mapping_file_simple(nemeth_path)