33
44# Copyright (c) Alibaba, Inc. and its affiliates.
55
6- import time
76from typing import Union , List , Optional , ClassVar , Dict , Any
87from typing_extensions import Self
98
2827from dashscope .finetune .reinforcement import (
2928 FunctionType ,
3029 DatasetsType ,
31- TrainingType ,
3230)
3331from dashscope .finetune .reinforcement import (
3432 RewardInput ,
4543from dashscope .finetune .reinforcement .common .errors import (
4644 RegistrationError ,
4745 ValidationError ,
48- InstanceQueryError ,
4946 RuntimeErrorWithCode ,
5047 ValueErrorWithCode ,
5148 DatasetsError ,
@@ -172,14 +169,11 @@ def submit_job(
172169 hyper_parameters : Optional [Dict [str , str ]] = None ,
173170 resources : Optional [Dict [str , str ]] = None ,
174171 job_name : Optional [str ] = None ,
175- teacher_model : Optional [str ] = None ,
176172 ** kwargs ,
177173 ) -> FineTune :
178174 """
179175 Submit RL tuning job to the platform.
180176 """
181- teacher_model = teacher_model or self .tuning .teacher_model
182-
183177 # Resolve job name (fallback to class default)
184178 if job_name :
185179 self .tuning .name = job_name
@@ -234,15 +228,6 @@ def submit_job(
234228 if resources :
235229 self .tuning .training .resources = resources
236230
237- training_type = self .tuning .training .type
238- if teacher_model :
239- training_type = TrainingType .PG_OPD
240- elif training_type == TrainingType .PG_OPD :
241- raise ValueErrorWithCode (
242- f"teacher_model is required when training.type is { training_type } " ,
243- error_code = 3006 ,
244- )
245-
246231 request = {
247232 "model" : self .tuning .model .name ,
248233 "training_datasets" : [ds .model_dump () for ds in training_datasets ],
@@ -253,8 +238,7 @@ def submit_job(
253238 "rewards" : rewards ,
254239 "hyper_parameters" : self .tuning .training .hyper_parameters ,
255240 "resource_config" : self .tuning .training .resources ,
256- "training_type" : str (training_type ),
257- "teacher_model" : teacher_model ,
241+ "training_type" : str (self .tuning .training .type ),
258242 "job_name" : job_name_with_suffix ,
259243 }
260244 request = deep_remove_none (request )
@@ -301,7 +285,6 @@ async def run(
301285 hyper_parameters : Optional [Dict [str , str ]] = None ,
302286 resources : Optional [Dict [str , str ]] = None ,
303287 job_name : Optional [str ] = None ,
304- teacher_model : Optional [str ] = None ,
305288 ** kwargs ,
306289 ) -> FineTune :
307290 """
@@ -330,7 +313,6 @@ async def run(
330313 hyper_parameters = hyper_parameters ,
331314 resources = resources ,
332315 job_name = job_name ,
333- teacher_model = teacher_model ,
334316 ** kwargs ,
335317 )
336318 except Exception as e :
@@ -444,28 +426,7 @@ async def test_functions(
444426 functype : FunctionType ,
445427 input_data : Dict [str , Any ],
446428 api_key : str = None ,
447- pull_logs : bool = False ,
448- log_page_size : int = 100 ,
449- start_time : Optional [int ] = None ,
450- end_time : Optional [int ] = None ,
451429 ):
452- """Test a deployed function instance with custom input data.
453-
454- Args:
455- instance_id: Target function instance ID.
456- functype: Function type (ROLLOUT/REWARD/GROUP_REWARD).
457- input_data: Test input payload.
458- api_key: DashScope API key (uses DASHSCOPE_API_KEY env var
459- if omitted).
460- pull_logs: If True, pull all logs of the function instance
461- (with pagination) after verification and print them
462- between separator markers.
463- log_page_size: Page size used when pulling logs.
464- start_time: Optional start time filter (in seconds) for log
465- pulling. Defaults to 24 hours before ``end_time``.
466- end_time: Optional end time filter (in seconds) for log
467- pulling. Defaults to the current time (now).
468- """
469430 try :
470431 set_api_key (api_key )
471432
@@ -489,197 +450,13 @@ async def test_functions(
489450 },
490451 )
491452
492- result = await AgenticRLFunctionComponent .verify_function (
453+ return await AgenticRLFunctionComponent .verify_function (
493454 value ,
494455 instance_id ,
495456 )
496457
497- if pull_logs :
498- await cls ._pull_function_instance_logs (
499- function_instance_id = instance_id ,
500- page_size = log_page_size ,
501- start_time = start_time ,
502- end_time = end_time ,
503- )
504-
505- return result
506-
507458 except Exception as e :
508459 raise ValidationError (
509460 "Function test failed" ,
510461 error_code = 3008 ,
511462 ) from e
512-
513- @classmethod
514- async def query_function_instance_logs (
515- cls ,
516- function_instance_id : str ,
517- page_number : int = 1 ,
518- page_size : int = 100 ,
519- start_time : Optional [int ] = None ,
520- end_time : Optional [int ] = None ,
521- keywords : Optional [List [str ]] = None ,
522- api_key : str = None ,
523- ) -> Dict [str , Any ]:
524- """Query one page of logs for a function (faas) instance.
525-
526- Args:
527- function_instance_id: Target function instance ID.
528- page_number: Page number, starting from 1.
529- page_size: Number of log entries per page.
530- start_time: Optional start time filter (in seconds).
531- end_time: Optional end time filter (in seconds).
532- keywords: Optional keyword filters for log messages.
533- api_key: DashScope API key (uses DASHSCOPE_API_KEY env var
534- if omitted).
535-
536- Returns:
537- Raw response dict of the log query API.
538- """
539- try :
540- set_api_key (api_key )
541-
542- fc_component = AgenticRLFunctionComponent
543- return await fc_component .query_function_instance_logs (
544- function_instance_id = function_instance_id ,
545- page_number = page_number ,
546- page_size = page_size ,
547- start_time = start_time ,
548- end_time = end_time ,
549- keywords = keywords ,
550- )
551-
552- except Exception as e :
553- if hasattr (e , "error_code" ):
554- raise
555- raise InstanceQueryError (
556- "Function instance log query failed" ,
557- error_code = 3009 ,
558- ) from e
559-
560- @classmethod
561- async def query_all_function_instance_logs (
562- cls ,
563- function_instance_id : str ,
564- page_size : int = 100 ,
565- start_time : Optional [int ] = None ,
566- end_time : Optional [int ] = None ,
567- keywords : Optional [List [str ]] = None ,
568- api_key : str = None ,
569- ) -> List [str ]:
570- """Fetch all logs of a function (faas) instance.
571-
572- Pages are fetched one by one via the paginated log query until
573- all entries are collected.
574-
575- Args:
576- function_instance_id: Target function instance ID.
577- page_size: Number of log entries per page.
578- start_time: Optional start time filter (in seconds).
579- end_time: Optional end time filter (in seconds).
580- keywords: Optional keyword filters for log messages.
581- api_key: DashScope API key (uses DASHSCOPE_API_KEY env var
582- if omitted).
583-
584- Returns:
585- Aggregated list of log messages across all pages.
586- """
587- try :
588- set_api_key (api_key )
589-
590- fc_component = AgenticRLFunctionComponent
591- return await fc_component .query_all_function_instance_logs (
592- function_instance_id = function_instance_id ,
593- page_size = page_size ,
594- start_time = start_time ,
595- end_time = end_time ,
596- keywords = keywords ,
597- )
598-
599- except Exception as e :
600- if hasattr (e , "error_code" ):
601- raise
602- raise InstanceQueryError (
603- "Function instance log query failed" ,
604- error_code = 3010 ,
605- ) from e
606-
607- @classmethod
608- async def delete_function_instance (
609- cls ,
610- function_instance_id : str ,
611- api_key : str = None ,
612- ) -> Dict [str , Any ]:
613- """Delete a function (faas) runtime instance.
614-
615- Args:
616- function_instance_id: Target function instance ID.
617- api_key: DashScope API key (uses DASHSCOPE_API_KEY env var
618- if omitted).
619-
620- Returns:
621- Raw response dict of the delete API, containing
622- ``data.status`` (e.g. "deleted") and
623- ``data.sandbox_code``.
624-
625- Raises:
626- InstanceQueryError: If the deletion fails.
627- """
628- try :
629- set_api_key (api_key )
630-
631- fc_component = AgenticRLFunctionComponent
632- return await fc_component .delete_function_instance (
633- function_instance_id = function_instance_id ,
634- )
635-
636- except Exception as e :
637- if hasattr (e , "error_code" ):
638- raise
639- raise InstanceQueryError (
640- "Function instance deletion failed" ,
641- error_code = 3011 ,
642- ) from e
643-
644- @classmethod
645- async def _pull_function_instance_logs (
646- cls ,
647- function_instance_id : str ,
648- page_size : int = 100 ,
649- start_time : Optional [int ] = None ,
650- end_time : Optional [int ] = None ,
651- ) -> None :
652- """Pull all logs of a function instance and print them between
653- separator markers (best effort, never raises).
654-
655- When ``start_time``/``end_time`` are not provided, defaults to
656- pulling logs from 24 hours ago until now.
657- """
658- if end_time is None :
659- end_time = int (time .time ())
660- if start_time is None :
661- start_time = end_time - 24 * 60 * 60
662- logger .info (
663- "************start query log "
664- f"(function_instance_id={ function_instance_id } )*******" ,
665- )
666- try :
667- logs = await cls .query_all_function_instance_logs (
668- function_instance_id = function_instance_id ,
669- page_size = page_size ,
670- start_time = start_time ,
671- end_time = end_time ,
672- )
673- for entry in logs :
674- logger .info (f"[function instance log] { entry } " )
675- logger .info (
676- f"Pulled { len (logs )} log entries for function instance "
677- f"{ function_instance_id } " ,
678- )
679- except Exception as e :
680- logger .warning (
681- f"Failed to pull logs for function instance "
682- f"{ function_instance_id } : { e } " ,
683- )
684- finally :
685- logger .info ("************end query log *******" )
0 commit comments