File size: 4,015 Bytes
d370082 | 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 | import asyncio
from dataclasses import dataclass
import json
from pathlib import Path
import re
import httpx
from openai import AsyncOpenAI, DefaultAioHttpClient
from omegaconf import OmegaConf
from pydantic import BaseModel
from rich import print
from refined_v4.data import atomic_json
from .data import ROOT, DEFAULT_STYLE
MODEL = 'gpt-6-luna'
WORDS = set(('use the given values quantities compute calculate work through each operation step first next then '
'combine these intermediate results final calculation remaining from in order follow shown arithmetic carefully '
'now with and to obtain evaluate using this result is a an value operations proceed continue toward answer '
'start by take apply perform carry out keep track of find determine solve required consider complete '
'for are as at we can will should need do our all together into before after').split())
QUESTIONS = ('Evaluate {expression}.', 'Calculate {expression}.',
'What is the value of {expression}?', 'Find the result of {expression}.')
class Style(BaseModel):
opening: str
transition: str
final: str
class Styles(BaseModel):
styles: list[Style]
@dataclass
class Config:
root: str = str(ROOT)
requests: int = 8
styles_per_request: int = 8
def safe(text: str) -> bool:
return (2 <= len(text.split()) <= 16 and text.isascii()
and not re.search(r'[^A-Za-z .,;:-]', text)
and set(re.findall(r'[a-z]+', text.lower())) <= WORDS)
async def run(config: Config):
root = Path(config.root)
root.mkdir(parents=True, exist_ok=True)
path = root / 'styles.json'
if path.exists():
return json.loads(path.read_text())
prompt = (f'Create {config.styles_per_request} diverse short generic mathematical explanation styles. '
'Each has opening, transition, final. They introduce verified equations that our program inserts. '
'Do not solve or invent any problem. Do not mention people, objects, units, numbers or particular operators. '
'Each phrase has two to sixteen words. Use ONLY words in this vocabulary, plus ordinary punctuation: '
+ ' '.join(sorted(WORDS)) + '. An example final phrase is: The remaining calculation is')
async with AsyncOpenAI(http_client=DefaultAioHttpClient(
limits=httpx.Limits(max_connections=12), timeout=90.), max_retries=1) as client:
async def request(index: int):
response = await client.responses.parse(model=MODEL,
input=prompt + f'. Style batch {index}.', text_format=Styles,
reasoning={'effort': 'none'}, max_output_tokens=3000, store=False)
values = response.output_parsed.styles if response.output_parsed else []
return dict(response_id=response.id, usage=response.usage.model_dump() if response.usage else {},
styles=[value.model_dump() for value in values])
responses = await asyncio.gather(*(request(index) for index in range(config.requests)))
accepted, seen = [], set()
for response in responses:
for row in response['styles']:
key = tuple(row.values())
if key in seen or not all(safe(text) for text in row.values()):
continue
seen.add(key)
for question in QUESTIONS:
accepted.append(dict(row, question=question))
if len(accepted) < 16:
raise ValueError('Too few safe API styles; saved source math must remain locked')
value = dict(model=MODEL, styles=accepted, responses=responses,
policy='Teacher supplies generic wording from a closed vocabulary; facts, questions, equations and answers are never generated by the teacher.')
atomic_json(path, value)
print(f'[green]{len(accepted)} safe styles ready; mathematical facts stay locked[/green]')
return value
if __name__ == '__main__':
asyncio.run(run(OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(Config), OmegaConf.from_cli()))))
|