[docs]classLangSmithRunChatLoader(BaseChatLoader):""" Load chat sessions from a list of LangSmith "llm" runs. Attributes: runs (Iterable[Union[str, Run]]): The list of LLM run IDs or run objects. client (Client): Instance of LangSmith client for fetching data. """
[docs]def__init__(self,runs:Iterable[Union[str,Run]],client:Optional["Client"]=None):""" Initialize a new LangSmithRunChatLoader instance. :param runs: List of LLM run IDs or run objects. :param client: An instance of LangSmith client, if not provided, a new client instance will be created. """fromlangsmith.clientimportClientself.runs=runsself.client=clientorClient()
@staticmethoddef_load_single_chat_session(llm_run:"Run")->ChatSession:""" Convert an individual LangSmith LLM run to a ChatSession. :param llm_run: The LLM run object. :return: A chat session representing the run's data. """chat_session=LangSmithRunChatLoader._get_messages_from_llm_run(llm_run)functions=LangSmithRunChatLoader._get_functions_from_llm_run(llm_run)iffunctions:chat_session["functions"]=functionsreturnchat_session@staticmethoddef_get_messages_from_llm_run(llm_run:"Run")->ChatSession:""" Extract messages from a LangSmith LLM run. :param llm_run: The LLM run object. :return: ChatSession with the extracted messages. """ifllm_run.run_type!="llm":raiseValueError(f"Expected run of type llm. Got: {llm_run.run_type}")if"messages"notinllm_run.inputs:raiseValueError(f"Run has no 'messages' inputs. Got {llm_run.inputs}")ifnotllm_run.outputs:raiseValueError("Cannot convert pending run")messages=load(llm_run.inputs)["messages"]message_chunk=load(llm_run.outputs)["generations"][0]["message"]returnChatSession(messages=messages+[message_chunk])@staticmethoddef_get_functions_from_llm_run(llm_run:"Run")->Optional[List[Dict]]:""" Extract functions from a LangSmith LLM run if they exist. :param llm_run: The LLM run object. :return: Functions from the run or None. """ifllm_run.run_type!="llm":raiseValueError(f"Expected run of type llm. Got: {llm_run.run_type}")return(llm_run.extraor{}).get("invocation_params",{}).get("functions")
[docs]deflazy_load(self)->Iterator[ChatSession]:""" Lazy load the chat sessions from the iterable of run IDs. This method fetches the runs and converts them to chat sessions on-the-fly, yielding one session at a time. :return: Iterator of chat sessions containing messages. """fromlangsmith.schemasimportRunforrun_objinself.runs:try:ifhasattr(run_obj,"id"):run=run_objelse:run=self.client.read_run(run_obj)session=self._load_single_chat_session(cast(Run,run))yieldsessionexceptValueErrorase:logger.warning(f"Could not load run {run_obj}: {repr(e)}")continue
[docs]classLangSmithDatasetChatLoader(BaseChatLoader):""" Load chat sessions from a LangSmith dataset with the "chat" data type. Attributes: dataset_name (str): The name of the LangSmith dataset. client (Client): Instance of LangSmith client for fetching data. """
[docs]def__init__(self,*,dataset_name:str,client:Optional["Client"]=None):""" Initialize a new LangSmithChatDatasetLoader instance. :param dataset_name: The name of the LangSmith dataset. :param client: An instance of LangSmith client; if not provided, a new client instance will be created. """try:fromlangsmith.clientimportClientexceptImportErrorase:raiseImportError("The LangSmith client is required to load LangSmith datasets.\n""Please install it with `pip install langsmith`")fromeself.dataset_name=dataset_nameself.client=clientorClient()
[docs]deflazy_load(self)->Iterator[ChatSession]:""" Lazy load the chat sessions from the specified LangSmith dataset. This method fetches the chat data from the dataset and converts each data point to chat sessions on-the-fly, yielding one session at a time. :return: Iterator of chat sessions containing messages. """fromlangchain_community.adaptersimportopenaiasoai_adapterdata=self.client.read_dataset_openai_finetuning(dataset_name=self.dataset_name)fordata_pointindata:yieldChatSession(messages=[oai_adapter.convert_dict_to_message(m)formindata_point.get("messages",[])],functions=data_point.get("functions"),)