Skip to content

Commit 32f94c7

Browse files
committed
ref: add processor response method in base
1 parent dd13d9f commit 32f94c7

2 files changed

Lines changed: 49 additions & 34 deletions

File tree

‎src/bespokelabs/curator/request_processor/base_request_processor.py‎

Lines changed: 45 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ def __init__(self, config: RequestProcessorConfig):
5252
desired_limit = min(10_000_000, hard)
5353
logger.debug(f"Adjusting file descriptor limit from {soft} to {desired_limit} (hard limit: {hard})")
5454
resource.setrlimit(resource.RLIMIT_NOFILE, (desired_limit, hard))
55+
self._viewer_client = None
5556
self.config = config
5657
self._cost_processor = cost_processor_factory(self.backend)
5758

@@ -81,9 +82,15 @@ def requests_to_responses(self, generic_request_files: list[str]) -> None:
8182
"""
8283
pass
8384

84-
def register_client(self, client):
85-
"""Register the client for the request processor."""
86-
self.client = client
85+
@property
86+
def viewer_client(self):
87+
"""Return the viewer client for the request processor."""
88+
return self._viewer_client
89+
90+
@viewer_client.setter
91+
def viewer_client(self, client):
92+
"""Set the viewer client for the request processor."""
93+
self._viewer_client = client
8794

8895
def check_structured_output_support(self) -> bool:
8996
"""Check if the model supports structured output.
@@ -329,6 +336,37 @@ def attempt_loading_cached_dataset(self, parse_func_hash: str) -> Optional["Data
329336
"Deleted file and attempting to regenerate dataset from cached LLM responses."
330337
)
331338

339+
def _process_response(self, data: GenericResponse) -> List | None:
340+
try:
341+
data.response_message = self.prompt_formatter.response_to_response_format(data.response_message)
342+
except (json.JSONDecodeError, ValidationError):
343+
logger.warning("Skipping response due to error parsing response message into response format")
344+
return
345+
346+
# parse_func can return a single row or a list of rows
347+
responses = None
348+
if self.prompt_formatter.parse_func:
349+
try:
350+
responses = self.prompt_formatter.parse_func(
351+
data.generic_request.original_row,
352+
data.response_message,
353+
)
354+
except Exception as e:
355+
logger.warning(f"Skipping response due to error in `parse_func` :: {e}")
356+
return
357+
358+
if not isinstance(responses, list):
359+
responses = [responses]
360+
else:
361+
# Convert response to dict before adding to dataset
362+
response_value = data.response_message
363+
if hasattr(response_value, "model_dump"):
364+
response_value = response_value.model_dump()
365+
elif hasattr(response_value, "__dict__"):
366+
response_value = response_value.__dict__
367+
responses = [{"response": response_value}]
368+
return responses
369+
332370
def create_dataset_files(
333371
self,
334372
parse_func_hash: str,
@@ -373,7 +411,10 @@ def create_dataset_files(
373411
if len(error_sample) < 10:
374412
error_sample.append(str(response.response_errors))
375413
continue
376-
dataset_rows = response.parsed_response_message
414+
if response.parsed_response_message is None:
415+
dataset_rows = self._process_response(response)
416+
else:
417+
dataset_rows = response.parsed_response_message
377418

378419
for row in dataset_rows:
379420
if isinstance(row, BaseModel):

‎src/bespokelabs/curator/request_processor/online/base_online_request_processor.py‎

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818
import aiofiles
1919
import aiohttp
20-
from pydantic import ValidationError
2120

2221
from bespokelabs.curator.llm.prompt_formatter import PromptFormatter
2322
from bespokelabs.curator.request_processor import _DEFAULT_COST_MAP
@@ -433,7 +432,7 @@ async def process_requests_from_file(
433432
done, pending_retries = await asyncio.wait(pending_retries, timeout=0.1)
434433

435434
status_tracker.stop_tracker()
436-
await self.client.session_completed()
435+
await self.viewer_client.session_completed()
437436

438437
# Log final status
439438
logger.info(f"Processing complete. Results saved to {response_file}")
@@ -570,34 +569,9 @@ async def append_generic_response(self, status_tracker: OnlineStatusTracker, dat
570569
data: Response data to append
571570
filename: File to append to
572571
"""
573-
try:
574-
data.response_message = self.prompt_formatter.response_to_response_format(data.response_message)
575-
except (json.JSONDecodeError, ValidationError):
576-
logger.warning("Skipping response due to error parsing response message into response format")
572+
responses = self._process_response(data)
573+
if not responses:
577574
return
578-
579-
# parse_func can return a single row or a list of rows
580-
if self.prompt_formatter.parse_func:
581-
try:
582-
responses = self.prompt_formatter.parse_func(
583-
data.generic_request.original_row,
584-
data.response_message,
585-
)
586-
except Exception as e:
587-
logger.warning(f"Skipping response due to error in `parse_func` :: {e}")
588-
return
589-
590-
if not isinstance(responses, list):
591-
responses = [responses]
592-
else:
593-
# Convert response to dict before adding to dataset
594-
response_value = data.response_message
595-
if hasattr(response_value, "model_dump"):
596-
response_value = response_value.model_dump()
597-
elif hasattr(response_value, "__dict__"):
598-
response_value = response_value.__dict__
599-
responses = [{"response": response_value}]
600-
601575
data.parsed_response_message = responses
602576
data_dump = data.model_dump()
603577
json_string = json.dumps(data_dump, default=str)
@@ -607,4 +581,4 @@ async def append_generic_response(self, status_tracker: OnlineStatusTracker, dat
607581
filename = os.path.basename(filename).split(".")[0]
608582
idx = status_tracker.num_parsed_responses
609583
status_tracker.num_parsed_responses = idx + len(responses)
610-
await self.client.stream_response(json_string, idx)
584+
await self.viewer_client.stream_response(json_string, idx)

0 commit comments

Comments
 (0)