code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def log_model( model, artifact_path: Optional[str] = None, save_exported_model=False, conda_env=None, signature: ModelSignature = None, input_example: ModelInputExample = None, registered_model_name=None, await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS, pip_requirements=None, ...
Log a Keras model along with metadata to MLflow. This method saves a Keras model along with metadata such as model signature and conda environments to MLflow. Args: model: an instance of `keras.Model`. The Keras model to be saved. artifact_path: Deprecated. Use `name` instead. ...
log_model
python
mlflow/mlflow
mlflow/keras/save.py
https://github.com/mlflow/mlflow/blob/master/mlflow/keras/save.py
Apache-2.0
def call_api( self, status_tracker: StatusTracker, callback_handlers: Optional[list[BaseCallbackHandler]] ): """ Calls the LangChain API and stores results. """ _logger.debug(f"Request #{self.index} started with payload: {self.request_json}") try: with ma...
Calls the LangChain API and stores results.
call_api
python
mlflow/mlflow
mlflow/langchain/api_request_parallel_processor.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/api_request_parallel_processor.py
Apache-2.0
def autolog( disable=False, exclusive=False, disable_for_unsupported_versions=False, silent=False, log_traces=True, ): """ Enables (or disables) and configures autologging from Langchain to MLflow. Args: disable: If ``True``, disables the Langchain autologging integration. If ``...
Enables (or disables) and configures autologging from Langchain to MLflow. Args: disable: If ``True``, disables the Langchain autologging integration. If ``False``, enables the Langchain autologging integration. exclusive: If ``True``, autologged content is not logged to user-creat...
autolog
python
mlflow/mlflow
mlflow/langchain/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/autolog.py
Apache-2.0
def _patched_callback_manager_merge(original, self, *args, **kwargs): """ Patch BaseCallbackManager.merge to avoid a duplicated callback issue. In the above patched __init__, we check `inheritable_handlers` to see if the MLflow tracer is already propagated. This works when the `inheritable_handlers` is...
Patch BaseCallbackManager.merge to avoid a duplicated callback issue. In the above patched __init__, we check `inheritable_handlers` to see if the MLflow tracer is already propagated. This works when the `inheritable_handlers` is specified as constructor arguments. However, in the `merge` method, Lang...
_patched_callback_manager_merge
python
mlflow/mlflow
mlflow/langchain/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/autolog.py
Apache-2.0
def _patched_runnable_sequence_batch(original, self, *args, **kwargs): """ Patch to terminate span context attachment during batch execution. RunnableSequence's batch() methods are implemented in a peculiar way that iterates on steps->items sequentially within the same thread. For example, if a seq...
Patch to terminate span context attachment during batch execution. RunnableSequence's batch() methods are implemented in a peculiar way that iterates on steps->items sequentially within the same thread. For example, if a sequence has 2 steps and the batch size is 3, the execution flow will be: -...
_patched_runnable_sequence_batch
python
mlflow/mlflow
mlflow/langchain/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/autolog.py
Apache-2.0
def parse_message( msg: AnyMessage, name: Optional[str] = None, attachments: Optional[dict] = None ) -> dict[str, Any]: """ Parse different LangChain message types into their ChatAgentMessage schema dict equivalents """ chat_message_dict = convert_lc_message_to_chat_message(msg).model_dump_compat() ...
Parse different LangChain message types into their ChatAgentMessage schema dict equivalents
parse_message
python
mlflow/mlflow
mlflow/langchain/chat_agent_langgraph.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/chat_agent_langgraph.py
Apache-2.0
def invoke(self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any) -> Any: """ Wraps the standard ToolNode invoke method to: - Parse ChatAgentState into LangChain messages - Parse dictionary string outputs from both UC function and standard LangChain python tools ...
Wraps the standard ToolNode invoke method to: - Parse ChatAgentState into LangChain messages - Parse dictionary string outputs from both UC function and standard LangChain python tools that include keys ``content``, ``attachments``, and ``custom_outputs``.
invoke
python
mlflow/mlflow
mlflow/langchain/chat_agent_langgraph.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/chat_agent_langgraph.py
Apache-2.0
def _isinstance_with_multiple_modules( object: Any, class_name: str, from_modules: list[str] ) -> bool: """ Databricks components are defined in different modules in LangChain e.g. langchain, langchain_community, databricks_langchain due to historical migrations. To keep backward compatibility, we n...
Databricks components are defined in different modules in LangChain e.g. langchain, langchain_community, databricks_langchain due to historical migrations. To keep backward compatibility, we need to check if the object is an instance of the class defined in any of those different modules. Args: ...
_isinstance_with_multiple_modules
python
mlflow/mlflow
mlflow/langchain/databricks_dependencies.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/databricks_dependencies.py
Apache-2.0
def _extract_dependency_list_from_lc_model(lc_model) -> Generator[Resource, None, None]: """ This function contains the logic to examine a non-Runnable component of a langchain model. The logic here does not cover all legacy chains. If you need to support a custom chain, you need to monkey patch this fu...
This function contains the logic to examine a non-Runnable component of a langchain model. The logic here does not cover all legacy chains. If you need to support a custom chain, you need to monkey patch this function.
_extract_dependency_list_from_lc_model
python
mlflow/mlflow
mlflow/langchain/databricks_dependencies.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/databricks_dependencies.py
Apache-2.0
def _traverse_runnable( lc_model, visited: Optional[set[int]] = None, ) -> Generator[Resource, None, None]: """ This function contains the logic to traverse a langchain_core.runnables.RunnableSerializable object. It first inspects the current object using _extract_dependency_list_from_lc_model a...
This function contains the logic to traverse a langchain_core.runnables.RunnableSerializable object. It first inspects the current object using _extract_dependency_list_from_lc_model and then, if the current object is a Runnable, it recursively inspects its children returned by lc_model.get_graph().nod...
_traverse_runnable
python
mlflow/mlflow
mlflow/langchain/databricks_dependencies.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/databricks_dependencies.py
Apache-2.0
def _get_deps_from_closures(lc_model): """ In some cases, the dependency extraction of Runnable Lambda fails because the call `inspect.getsource(func)` can fail. This causes deps of RunnableLambda to be empty. Therefore this method adds an additional way of getting dependencies through closure varia...
In some cases, the dependency extraction of Runnable Lambda fails because the call `inspect.getsource(func)` can fail. This causes deps of RunnableLambda to be empty. Therefore this method adds an additional way of getting dependencies through closure variables. TODO: Remove when issue gets resolv...
_get_deps_from_closures
python
mlflow/mlflow
mlflow/langchain/databricks_dependencies.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/databricks_dependencies.py
Apache-2.0
def _get_nodes_from_runnable_lambda(lc_model): """ This is a workaround for the LangGraph issue: https://github.com/langchain-ai/langgraph/issues/1856 For RunnableLambda, we calling lc_model.get_graph() to get the nodes, which inspect the input and output schema using wrapped function's type annotation...
This is a workaround for the LangGraph issue: https://github.com/langchain-ai/langgraph/issues/1856 For RunnableLambda, we calling lc_model.get_graph() to get the nodes, which inspect the input and output schema using wrapped function's type annotation. However, the prebuilt graph (e.g. create_react_a...
_get_nodes_from_runnable_lambda
python
mlflow/mlflow
mlflow/langchain/databricks_dependencies.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/databricks_dependencies.py
Apache-2.0
def _get_nodes_from_runnable_callable(lc_model): """ RunnableLambda has a `deps` property which goes through the function and extracts a ny dependencies. RunnableCallable does not have this property so we cannot derive all the dependencies from the function. This helper method also looks into the functi...
RunnableLambda has a `deps` property which goes through the function and extracts a ny dependencies. RunnableCallable does not have this property so we cannot derive all the dependencies from the function. This helper method also looks into the function of the callable to retrieve these dependencies. ...
_get_nodes_from_runnable_callable
python
mlflow/mlflow
mlflow/langchain/databricks_dependencies.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/databricks_dependencies.py
Apache-2.0
def _serialize_invocation_params( self, attributes: Optional[dict[str, Any]] ) -> Optional[dict[str, Any]]: """ Serialize the 'invocation_params' in the attributes dictionary. If 'invocation_params' contains a key 'response_format' whose value is a subclass of pydantic.BaseMo...
Serialize the 'invocation_params' in the attributes dictionary. If 'invocation_params' contains a key 'response_format' whose value is a subclass of pydantic.BaseModel, replace it with its JSON schema.
_serialize_invocation_params
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def _start_span( self, span_name: str, parent_run_id: Optional[UUID], span_type: str, run_id: UUID, inputs: Optional[Union[str, dict[str, Any]]] = None, attributes: Optional[dict[str, Any]] = None, ) -> LiveSpan: """Start MLflow Span (or Trace if it is...
Start MLflow Span (or Trace if it is root component)
_start_span
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def _get_parent_span(self, parent_run_id) -> Optional[LiveSpan]: """ Get parent span from multiple sources: 1. If there is an active span in current context, use it as parent span 2. If parent_run_id is provided, get the corresponding span from the run -> span mapping 3. If none ...
Get parent span from multiple sources: 1. If there is an active span in current context, use it as parent span 2. If parent_run_id is provided, get the corresponding span from the run -> span mapping 3. If none of the above, return None
_get_parent_span
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def _end_span( self, run_id: UUID, span: LiveSpan, outputs=None, attributes=None, status=SpanStatus(SpanStatusCode.OK), ): """Close MLflow Span (or Trace if it is root component)""" try: with maybe_set_prediction_context(self._prediction_co...
Close MLflow Span (or Trace if it is root component)
_end_span
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def flush(self): """Flush the state of the tracer.""" # Ideally, all spans should be popped and ended. However, LangChain sometimes # does not trigger the end event properly and some spans may be left open. # To avoid leaking tracing context, we remove all spans from the mapping. ...
Flush the state of the tracer.
flush
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def on_chat_model_start( self, serialized: dict[str, Any], messages: list[list[BaseMessage]], *, run_id: UUID, tags: Optional[list[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[dict[str, Any]] = None, name: Optional[str] = ...
Run when a chat model starts running.
on_chat_model_start
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def on_llm_start( self, serialized: dict[str, Any], prompts: list[str], *, run_id: UUID, tags: Optional[list[str]] = None, parent_run_id: Optional[UUID] = None, metadata: Optional[dict[str, Any]] = None, name: Optional[str] = None, **kwargs...
Run when LLM (non-chat models) starts running.
on_llm_start
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def on_llm_new_token( self, token: str, *, chunk: Optional[Union[GenerationChunk, ChatGenerationChunk]] = None, run_id: UUID, parent_run_id: Optional[UUID] = None, **kwargs: Any, ): """Run on new LLM token. Only available when streaming is enabled.""" ...
Run on new LLM token. Only available when streaming is enabled.
on_llm_new_token
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def on_llm_end(self, response: LLMResult, *, run_id: UUID, **kwargs: Any): """End the span for an LLM run.""" llm_span = self._get_span_by_run_id(run_id) # Record the chat messages attribute input_messages = llm_span.get_attribute(SpanAttributeKey.CHAT_MESSAGES) or [] # response...
End the span for an LLM run.
on_llm_end
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def on_llm_error( self, error: BaseException, *, run_id: UUID, **kwargs: Any, ): """Handle an error for an LLM run.""" llm_span = self._get_span_by_run_id(run_id) llm_span.add_event(SpanEvent.from_exception(error)) self._end_span(run_id, llm_sp...
Handle an error for an LLM run.
on_llm_error
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def on_agent_action( self, action: AgentAction, *, run_id: UUID, **kwargs: Any, ) -> Any: """ Run on agent action. NB: Agent action doesn't create a new LangChain Run, so instead of creating a new span, an action will be recorded as an event o...
Run on agent action. NB: Agent action doesn't create a new LangChain Run, so instead of creating a new span, an action will be recorded as an event of the existing span created by a parent chain.
on_agent_action
python
mlflow/mlflow
mlflow/langchain/langchain_tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/langchain_tracer.py
Apache-2.0
def get_default_pip_requirements(): """ Returns: A list of default pip requirements for MLflow Models produced by this flavor. Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment that, at a minimum, contains these requirements. """ # pin pydantic and c...
Returns: A list of default pip requirements for MLflow Models produced by this flavor. Calls to :func:`save_model()` and :func:`log_model()` produce a pip environment that, at a minimum, contains these requirements.
get_default_pip_requirements
python
mlflow/mlflow
mlflow/langchain/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/model.py
Apache-2.0
def predict( self, data: Union[pd.DataFrame, list[Union[str, dict[str, Any]]], Any], params: Optional[dict[str, Any]] = None, ) -> list[Union[str, dict[str, Any]]]: """ Args: data: Model input data. params: Additional parameters to pass to the model fo...
Args: data: Model input data. params: Additional parameters to pass to the model for inference. Returns: Model predictions.
predict
python
mlflow/mlflow
mlflow/langchain/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/model.py
Apache-2.0
def _predict_with_callbacks( self, data: Union[pd.DataFrame, list[Union[str, dict[str, Any]]], Any], params: Optional[dict[str, Any]] = None, callback_handlers=None, convert_chat_responses=False, ) -> list[Union[str, dict[str, Any]]]: """ Args: dat...
Args: data: Model input data. params: Additional parameters to pass to the model for inference. callback_handlers: Callback handlers to pass to LangChain. convert_chat_responses: If true, forcibly convert response to chat model response format. ...
_predict_with_callbacks
python
mlflow/mlflow
mlflow/langchain/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/model.py
Apache-2.0
def _prepare_predict_messages(self, data): """ Return a tuple of (preprocessed_data, return_first_element) `preprocessed_data` is always a list, and `return_first_element` means if True, we should return the first element of inference result, otherwise we should return the whole ...
Return a tuple of (preprocessed_data, return_first_element) `preprocessed_data` is always a list, and `return_first_element` means if True, we should return the first element of inference result, otherwise we should return the whole inference result.
_prepare_predict_messages
python
mlflow/mlflow
mlflow/langchain/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/model.py
Apache-2.0
def predict_stream( self, data: Any, params: Optional[dict[str, Any]] = None, ) -> Iterator[Union[str, dict[str, Any]]]: """ Args: data: Model input data, only single input is allowed. params: Additional parameters to pass to the model for inference. ...
Args: data: Model input data, only single input is allowed. params: Additional parameters to pass to the model for inference. Returns: An iterator of model prediction chunks.
predict_stream
python
mlflow/mlflow
mlflow/langchain/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/model.py
Apache-2.0
def _predict_stream_with_callbacks( self, data: Any, params: Optional[dict[str, Any]] = None, callback_handlers=None, convert_chat_responses=False, ) -> Iterator[Union[str, dict[str, Any]]]: """ Args: data: Model input data, only single input is al...
Args: data: Model input data, only single input is allowed. params: Additional parameters to pass to the model for inference. callback_handlers: Callback handlers to pass to LangChain. convert_chat_responses: If true, forcibly convert response to chat model ...
_predict_stream_with_callbacks
python
mlflow/mlflow
mlflow/langchain/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/model.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load a LangChain model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bu...
Load a LangChain model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlflo...
load_model
python
mlflow/mlflow
mlflow/langchain/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/model.py
Apache-2.0
def parse(self, text: str) -> dict[str, Any]: """Returns the input text as a ChatCompletionResponse with no changes.""" return ChatCompletionResponse( choices=[ChatChoice(message=ChatMessage(role="assistant", content=text))] ).to_dict()
Returns the input text as a ChatCompletionResponse with no changes.
parse
python
mlflow/mlflow
mlflow/langchain/output_parsers.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/output_parsers.py
Apache-2.0
def parse(self, text: str) -> dict[str, Any]: """ Returns the output text as a dictionary representation of a :py:class:`ChatAgentResponse <mlflow.types.agent.ChatAgentResponse>`. """ return ChatAgentResponse( messages=[ChatAgentMessage(content=text, role="assistant",...
Returns the output text as a dictionary representation of a :py:class:`ChatAgentResponse <mlflow.types.agent.ChatAgentResponse>`.
parse
python
mlflow/mlflow
mlflow/langchain/output_parsers.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/output_parsers.py
Apache-2.0
def transform(self, input: Iterator[BaseMessage], config, **kwargs) -> Iterator[dict[str, Any]]: """ Returns a generator of :py:class:`ChatAgentChunk <mlflow.types.agent.ChatAgentChunk>` objects """ for chunk in input: if chunk.content: yield ChatAgent...
Returns a generator of :py:class:`ChatAgentChunk <mlflow.types.agent.ChatAgentChunk>` objects
transform
python
mlflow/mlflow
mlflow/langchain/output_parsers.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/output_parsers.py
Apache-2.0
def _call( self, inputs: dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> dict[str, Any]: """Run _get_docs on input query. Returns the retrieved documents under the key 'source_documents'. Example: .. code-block:: python ...
Run _get_docs on input query. Returns the retrieved documents under the key 'source_documents'. Example: .. code-block:: python chain = _RetrieverChain(retriever=...) res = chain({"query": "This is my query"}) docs = res["source_documents"]
_call
python
mlflow/mlflow
mlflow/langchain/retriever_chain.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/retriever_chain.py
Apache-2.0
def _load_runnable_with_steps(file_path: Union[Path, str], model_type: str): """Load the model Args: file_path: Path to file to load the model from. model_type: Type of the model to load. """ from langchain.schema.runnable import RunnableParallel, RunnableSequence load_path = _vali...
Load the model Args: file_path: Path to file to load the model from. model_type: Type of the model to load.
_load_runnable_with_steps
python
mlflow/mlflow
mlflow/langchain/runnables.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/runnables.py
Apache-2.0
def runnable_sequence_from_steps(steps): """Construct a RunnableSequence from steps. Args: steps: List of steps to construct the RunnableSequence from. """ from langchain.schema.runnable import RunnableSequence if len(steps) < 2: raise ValueError(f"RunnableSequence must have at lea...
Construct a RunnableSequence from steps. Args: steps: List of steps to construct the RunnableSequence from.
runnable_sequence_from_steps
python
mlflow/mlflow
mlflow/langchain/runnables.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/runnables.py
Apache-2.0
def _load_runnable_branch(file_path: Union[Path, str]): """Load the model Args: file_path: Path to file to load the model from. """ from langchain.schema.runnable import RunnableBranch load_path = _validate_path(file_path) branches_conf_file = load_path / _RUNNABLE_BRANCHES_FILE_NAME ...
Load the model Args: file_path: Path to file to load the model from.
_load_runnable_branch
python
mlflow/mlflow
mlflow/langchain/runnables.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/runnables.py
Apache-2.0
def _load_runnable_binding(file_path: Union[Path, str]): """ Load runnable binding model from the path """ from langchain.schema.runnable import RunnableBinding load_path = _validate_path(file_path) model_conf = _load_from_yaml(load_path / _RUNNABLE_BINDING_CONF_FILE_NAME) for field, value...
Load runnable binding model from the path
_load_runnable_binding
python
mlflow/mlflow
mlflow/langchain/runnables.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/runnables.py
Apache-2.0
def _warning_if_imported_from_lc_partner_pkg(runnable): """ Issues a warning if the model contains LangChain partner packages in its requirements. Popular integrations like OpenAI have been migrated from the central langchain-community package to their own partner packages (e.g. langchain-openai). Howe...
Issues a warning if the model contains LangChain partner packages in its requirements. Popular integrations like OpenAI have been migrated from the central langchain-community package to their own partner packages (e.g. langchain-openai). However, the class loading mechanism in MLflow does not handle ...
_warning_if_imported_from_lc_partner_pkg
python
mlflow/mlflow
mlflow/langchain/runnables.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/runnables.py
Apache-2.0
def _save_runnable_with_steps(model, file_path: Union[Path, str], loader_fn=None, persist_dir=None): # noqa: D417 """Save the model with steps. Currently it supports saving RunnableSequence and RunnableParallel. If saving a RunnableSequence, steps is a list of Runnable objects. We save each step to the ...
Save the model with steps. Currently it supports saving RunnableSequence and RunnableParallel. If saving a RunnableSequence, steps is a list of Runnable objects. We save each step to the subfolder named by the step index. e.g. - model - steps - 0 - model.yaml ...
_save_runnable_with_steps
python
mlflow/mlflow
mlflow/langchain/runnables.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/runnables.py
Apache-2.0
def _save_runnable_branch(model, file_path, loader_fn, persist_dir): """ Save runnable branch in to path. """ save_path = Path(file_path) save_path.mkdir(parents=True, exist_ok=True) # save branches into a folder branches_path = save_path / _BRANCHES_FOLDER_NAME branches_path.mkdir() ...
Save runnable branch in to path.
_save_runnable_branch
python
mlflow/mlflow
mlflow/langchain/runnables.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/runnables.py
Apache-2.0
def convert_lc_message_to_chat_message(lc_message: Union[BaseMessage]) -> ChatMessage: """ Convert LangChain's message format to the MLflow's standard chat message format. """ if isinstance(lc_message, AIMessage): if tool_calls := _get_tool_calls_from_ai_message(lc_message): return C...
Convert LangChain's message format to the MLflow's standard chat message format.
convert_lc_message_to_chat_message
python
mlflow/mlflow
mlflow/langchain/utils/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/chat.py
Apache-2.0
def _chat_model_to_langchain_message(message: ChatMessage) -> BaseMessage: """ Convert the MLflow's standard chat message format to LangChain's message format. """ if message.role == "system": return SystemMessage(content=message.content) elif message.role == "assistant": return AIMe...
Convert the MLflow's standard chat message format to LangChain's message format.
_chat_model_to_langchain_message
python
mlflow/mlflow
mlflow/langchain/utils/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/chat.py
Apache-2.0
def convert_lc_generation_to_chat_message(lc_gen: Generation) -> ChatMessage: """ Convert LangChain's generation format to the MLflow's standard chat message format. """ if isinstance(lc_gen, ChatGeneration): try: return convert_lc_message_to_chat_message(lc_gen.message) exce...
Convert LangChain's generation format to the MLflow's standard chat message format.
convert_lc_generation_to_chat_message
python
mlflow/mlflow
mlflow/langchain/utils/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/chat.py
Apache-2.0
def try_transform_response_to_chat_format(response: Any) -> dict: """ Try to convert the response to the standard chat format and return its dict representation. If the response is not one of the supported types, return the response as-is. """ if isinstance(response, (str, AIMessage)): if i...
Try to convert the response to the standard chat format and return its dict representation. If the response is not one of the supported types, return the response as-is.
try_transform_response_to_chat_format
python
mlflow/mlflow
mlflow/langchain/utils/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/chat.py
Apache-2.0
def transform_request_json_for_chat_if_necessary(request_json, lc_model): """ Convert the input request JSON to LangChain's Message format if the LangChain model accepts ChatMessage objects (e.g. AIMessage, HumanMessage, SystemMessage) as input. Args: request_json: The input request JSON. ...
Convert the input request JSON to LangChain's Message format if the LangChain model accepts ChatMessage objects (e.g. AIMessage, HumanMessage, SystemMessage) as input. Args: request_json: The input request JSON. lc_model: The LangChain model. Returns: A 2-element tuple contain...
transform_request_json_for_chat_if_necessary
python
mlflow/mlflow
mlflow/langchain/utils/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/chat.py
Apache-2.0
def parse_token_usage( lc_generations: list[Generation], ) -> Optional[dict[str, int]]: """Parse the token usage from the LangChain generations.""" aggregated = defaultdict(int) for generation in lc_generations: if token_usage := _parse_token_usage_from_generation(generation): for ke...
Parse the token usage from the LangChain generations.
parse_token_usage
python
mlflow/mlflow
mlflow/langchain/utils/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/chat.py
Apache-2.0
def _parse_token_counts(usage_metadata: dict[str, Any]) -> dict[str, int]: """Standardize token usage metadata keys to MLflow's token usage keys.""" usage = {} for key, value in usage_metadata.items(): if usage_key := _TOKEN_USAGE_KEY_MAPPING.get(key): usage[usage_key] = value # If ...
Standardize token usage metadata keys to MLflow's token usage keys.
_parse_token_counts
python
mlflow/mlflow
mlflow/langchain/utils/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/chat.py
Apache-2.0
def picklable_runnable_types(): """ Runnable types that can be pickled and unpickled by cloudpickle. """ from langchain.chat_models.base import SimpleChatModel from langchain.prompts import ChatPromptTemplate from langchain.schema.runnable import RunnableLambda, RunnablePassthrough return (...
Runnable types that can be pickled and unpickled by cloudpickle.
picklable_runnable_types
python
mlflow/mlflow
mlflow/langchain/utils/logging.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/logging.py
Apache-2.0
def safe_import_and_add(module_name, class_name): """Add conditional support for `partner` and `community` APIs in langchain""" try: module = importlib.import_module(module_name) try_adding_llm(module, class_name) except ImportError: pass
Add conditional support for `partner` and `community` APIs in langchain
safe_import_and_add
python
mlflow/mlflow
mlflow/langchain/utils/logging.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/logging.py
Apache-2.0
def _patch_loader(loader_func: Callable) -> Callable: """ Patch LangChain loader function like load_chain() to handle the breaking change introduced in LangChain 0.1.12. Since langchain-community 0.0.27, loading a module that relies on the pickle deserialization requires the `allow_dangerous_deseri...
Patch LangChain loader function like load_chain() to handle the breaking change introduced in LangChain 0.1.12. Since langchain-community 0.0.27, loading a module that relies on the pickle deserialization requires the `allow_dangerous_deserialization` flag to be set to True, for security reasons. ...
_patch_loader
python
mlflow/mlflow
mlflow/langchain/utils/logging.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/logging.py
Apache-2.0
def register_pydantic_serializer(): """ Helper function to pickle pydantic fields for pydantic v1. Pydantic's Cython validators are not serializable. https://github.com/cloudpipe/cloudpickle/issues/408 """ import pydantic if Version(pydantic.__version__) >= Version("2.0.0"): return ...
Helper function to pickle pydantic fields for pydantic v1. Pydantic's Cython validators are not serializable. https://github.com/cloudpipe/cloudpickle/issues/408
register_pydantic_serializer
python
mlflow/mlflow
mlflow/langchain/utils/logging.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/logging.py
Apache-2.0
def convert_to_serializable(response): """ Convert the response to a JSON serializable format. LangChain response objects often contains Pydantic objects, which causes an serialization error when the model is served behind REST endpoint. """ import langchain # LangChain >= 0.3.0 uses Pydan...
Convert the response to a JSON serializable format. LangChain response objects often contains Pydantic objects, which causes an serialization error when the model is served behind REST endpoint.
convert_to_serializable
python
mlflow/mlflow
mlflow/langchain/utils/serialization.py
https://github.com/mlflow/mlflow/blob/master/mlflow/langchain/utils/serialization.py
Apache-2.0
def update_and_persist_config(profile, databricks_config): """ Takes a DatabricksConfig and adds the in memory contents to the persisted version of the config. This will overwrite any other config that was persisted to the file system under the same profile. Args: profile: str datab...
Takes a DatabricksConfig and adds the in memory contents to the persisted version of the config. This will overwrite any other config that was persisted to the file system under the same profile. Args: profile: str databricks_config: DatabricksConfig
update_and_persist_config
python
mlflow/mlflow
mlflow/legacy_databricks_cli/configure/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/legacy_databricks_cli/configure/provider.py
Apache-2.0
def get_config(): """ Returns a DatabricksConfig containing the hostname and authentication used to talk to the Databricks API. By default, we leverage the DefaultConfigProvider to get this config, but this behavior may be overridden by calling 'set_config_provider' If no DatabricksConfig can be fo...
Returns a DatabricksConfig containing the hostname and authentication used to talk to the Databricks API. By default, we leverage the DefaultConfigProvider to get this config, but this behavior may be overridden by calling 'set_config_provider' If no DatabricksConfig can be found, an InvalidConfigurat...
get_config
python
mlflow/mlflow
mlflow/legacy_databricks_cli/configure/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/legacy_databricks_cli/configure/provider.py
Apache-2.0
def get_config_for_profile(profile): """ [Deprecated] Reads from the filesystem and gets a DatabricksConfig for the specified profile. If it does not exist, then return a DatabricksConfig with fields set to None. Internal callers should prefer get_config() to use user-specified overrides, and t...
[Deprecated] Reads from the filesystem and gets a DatabricksConfig for the specified profile. If it does not exist, then return a DatabricksConfig with fields set to None. Internal callers should prefer get_config() to use user-specified overrides, and to return appropriate error messages as oppos...
get_config_for_profile
python
mlflow/mlflow
mlflow/legacy_databricks_cli/configure/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/legacy_databricks_cli/configure/provider.py
Apache-2.0
def set_config_provider(provider): """ Sets a DatabricksConfigProvider that will be used for all future calls to get_config(), used by the Databricks CLI code to discover the user's credentials. """ global _config_provider if provider and not isinstance(provider, DatabricksConfigProvider): ...
Sets a DatabricksConfigProvider that will be used for all future calls to get_config(), used by the Databricks CLI code to discover the user's credentials.
set_config_provider
python
mlflow/mlflow
mlflow/legacy_databricks_cli/configure/provider.py
https://github.com/mlflow/mlflow/blob/master/mlflow/legacy_databricks_cli/configure/provider.py
Apache-2.0
def save_model( lgb_model, path, conda_env=None, code_paths=None, mlflow_model=None, signature: ModelSignature = None, input_example: ModelInputExample = None, pip_requirements=None, extra_pip_requirements=None, metadata=None, ): """ Save a LightGBM model to a path on the...
Save a LightGBM model to a path on the local file system. Args: lgb_model: LightGBM model (an instance of `lightgbm.Booster`_) or models that implement the `scikit-learn API`_ to be saved. path: Local path where the model is to be saved. conda_env: {{ conda_env }} ...
save_model
python
mlflow/mlflow
mlflow/lightgbm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/lightgbm/__init__.py
Apache-2.0
def _save_model(lgb_model, model_path): """ LightGBM Boosters are saved using the built-in method `save_model()`, whereas LightGBM scikit-learn models are serialized using Cloudpickle. """ import lightgbm as lgb if isinstance(lgb_model, lgb.Booster): lgb_model.save_model(model_path) ...
LightGBM Boosters are saved using the built-in method `save_model()`, whereas LightGBM scikit-learn models are serialized using Cloudpickle.
_save_model
python
mlflow/mlflow
mlflow/lightgbm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/lightgbm/__init__.py
Apache-2.0
def log_model( lgb_model, artifact_path: Optional[str] = None, conda_env=None, code_paths=None, registered_model_name=None, signature: ModelSignature = None, input_example: ModelInputExample = None, await_registration_for=DEFAULT_AWAIT_MAX_SLEEP_SECONDS, pip_requirements=None, ex...
Log a LightGBM model as an MLflow artifact for the current run. Args: lgb_model: LightGBM model (an instance of `lightgbm.Booster`_) or models that implement the `scikit-learn API`_ to be saved. artifact_path: Deprecated. Use `name` instead. conda_env: {{ conda_env }} ...
log_model
python
mlflow/mlflow
mlflow/lightgbm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/lightgbm/__init__.py
Apache-2.0
def _load_model(path): """ Load Model Implementation. Args: path: Local filesystem path to the MLflow Model with the ``lightgbm`` flavor (MLflow < 1.23.0) or the top-level MLflow Model directory (MLflow >= 1.23.0). """ model_dir = os.path.dirname(path) if os.path.is...
Load Model Implementation. Args: path: Local filesystem path to the MLflow Model with the ``lightgbm`` flavor (MLflow < 1.23.0) or the top-level MLflow Model directory (MLflow >= 1.23.0).
_load_model
python
mlflow/mlflow
mlflow/lightgbm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/lightgbm/__init__.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load a LightGBM model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_buc...
Load a LightGBM model from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` - ``runs:/<mlflow...
load_model
python
mlflow/mlflow
mlflow/lightgbm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/lightgbm/__init__.py
Apache-2.0
def record_eval_results(eval_results, metrics_logger): """ Create a callback function that records evaluation results. """ return picklable_exception_safe_function( functools.partial( _autolog_callback, metrics_logger=metrics_logger, ev...
Create a callback function that records evaluation results.
record_eval_results
python
mlflow/mlflow
mlflow/lightgbm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/lightgbm/__init__.py
Apache-2.0
def autolog( log_traces: bool = True, disable: bool = False, silent: bool = False, ): """ Enables (or disables) and configures autologging from LiteLLM to MLflow. Currently, MLflow only supports autologging for tracing. Args: log_traces: If ``True``, traces are logged for LiteLLM ca...
Enables (or disables) and configures autologging from LiteLLM to MLflow. Currently, MLflow only supports autologging for tracing. Args: log_traces: If ``True``, traces are logged for LiteLLM calls. If ``False``, no traces are collected during inference. Default to ``True``. dis...
autolog
python
mlflow/mlflow
mlflow/litellm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/litellm/__init__.py
Apache-2.0
def _patch_threading_in_function(target, function_name: str): """ Apply the threading patch to a synchronous function. We capture the threads started by the function using the _patch_thread_start context manager, then join them to ensure they are finished before the notebook cell finishes executing. ...
Apply the threading patch to a synchronous function. We capture the threads started by the function using the _patch_thread_start context manager, then join them to ensure they are finished before the notebook cell finishes executing.
_patch_threading_in_function
python
mlflow/mlflow
mlflow/litellm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/litellm/__init__.py
Apache-2.0
def _patch_thread_start(): """ A context manager to collect threads started for logging handlers. This is done by monkey-patching the start() method of threading.Thread. Note that failure handlers are executed synchronously, so we don't need to patch them. """ original = Thread.start logging...
A context manager to collect threads started for logging handlers. This is done by monkey-patching the start() method of threading.Thread. Note that failure handlers are executed synchronously, so we don't need to patch them.
_patch_thread_start
python
mlflow/mlflow
mlflow/litellm/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/litellm/__init__.py
Apache-2.0
def autolog( log_traces: bool = True, disable: bool = False, silent: bool = False, ): """ Enables (or disables) and configures autologging from LlamaIndex to MLflow. Currently, MLflow only supports autologging for tracing. Args: log_traces: If ``True``, traces are logged for LlamaIn...
Enables (or disables) and configures autologging from LlamaIndex to MLflow. Currently, MLflow only supports autologging for tracing. Args: log_traces: If ``True``, traces are logged for LlamaIndex models by using. If ``False``, no traces are collected during inference. Default to ``Tru...
autolog
python
mlflow/mlflow
mlflow/llama_index/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/autolog.py
Apache-2.0
def _autolog( log_traces: bool, disable: bool = False, silent: bool = False, ): """ TODO: Implement patching logic for autologging models and artifacts. """
TODO: Implement patching logic for autologging models and artifacts.
_autolog
python
mlflow/mlflow
mlflow/llama_index/autolog.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/autolog.py
Apache-2.0
def get_chat_messages_from_event(event: BaseEvent) -> list[ChatMessage]: """ Extract chat messages from the LlamaIndex callback event. """ if isinstance(event, LLMCompletionStartEvent): return [ChatMessage(role="user", content=event.prompt)] elif isinstance(event, LLMCompletionEndEvent): ...
Extract chat messages from the LlamaIndex callback event.
get_chat_messages_from_event
python
mlflow/mlflow
mlflow/llama_index/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/chat.py
Apache-2.0
def _convert_message_to_mlflow_chat(message: LLamaChatMessage) -> ChatMessage: """Convert a message object from LlamaIndex to MLflow's standard format.""" message = to_openai_message_dict(message, drop_none=False) # tool calls are pydantic models in llama-index if tool_calls := message.get("tool_calls"...
Convert a message object from LlamaIndex to MLflow's standard format.
_convert_message_to_mlflow_chat
python
mlflow/mlflow
mlflow/llama_index/chat.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/chat.py
Apache-2.0
def save_model( llama_index_model, path: str, engine_type: Optional[str] = None, model_config: Optional[Union[str, dict[str, Any]]] = None, code_paths=None, mlflow_model: Optional[Model] = None, signature: Optional[ModelSignature] = None, input_example: Optional[ModelInputExample] = None...
Save a LlamaIndex model to a path on the local file system. .. attention:: Saving a non-index object is only supported in the 'Model-from-Code' saving mode. Please refer to the `Models From Code Guide <https://www.mlflow.org/docs/latest/model/models-from-code.html>`_ for more informat...
save_model
python
mlflow/mlflow
mlflow/llama_index/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/model.py
Apache-2.0
def log_model( llama_index_model, artifact_path: Optional[str] = None, engine_type: Optional[str] = None, model_config: Optional[dict[str, Any]] = None, code_paths: Optional[list[str]] = None, registered_model_name: Optional[str] = None, signature: Optional[ModelSignature] = None, input_...
Log a LlamaIndex model as an MLflow artifact for the current run. .. attention:: Saving a non-index object is only supported in the 'Model-from-Code' saving mode. Please refer to the `Models From Code Guide <https://www.mlflow.org/docs/latest/model/models-from-code.html>`_ for more in...
log_model
python
mlflow/mlflow
mlflow/llama_index/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/model.py
Apache-2.0
def _load_llama_model(path, flavor_conf): """Load the LlamaIndex index/engine/workflow from either model code or serialized index.""" from llama_index.core import StorageContext, load_index_from_storage _add_code_from_conf_to_system_path(path, flavor_conf) # Handle model-from-code pyfunc_flavor_co...
Load the LlamaIndex index/engine/workflow from either model code or serialized index.
_load_llama_model
python
mlflow/mlflow
mlflow/llama_index/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/model.py
Apache-2.0
def load_model(model_uri, dst_path=None): """ Load a LlamaIndex index/engine/workflow from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` ...
Load a LlamaIndex index/engine/workflow from a local file or a run. Args: model_uri: The location, in URI format, of the MLflow model. For example: - ``/Users/me/path/to/local/model`` - ``relative/path/to/local/model`` - ``s3://my_bucket/path/to/model`` ...
load_model
python
mlflow/mlflow
mlflow/llama_index/model.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/model.py
Apache-2.0
def _convert_llm_input_data_with_unwrapping(data): """ Transforms the input data to the format expected by the LlamaIndex engine. TODO: Migrate the unwrapping logic to mlflow.evaluate() function or _convert_llm_input_data, # because it is not specific to LlamaIndex. """ data = _convert_llm_inpu...
Transforms the input data to the format expected by the LlamaIndex engine. TODO: Migrate the unwrapping logic to mlflow.evaluate() function or _convert_llm_input_data, # because it is not specific to LlamaIndex.
_convert_llm_input_data_with_unwrapping
python
mlflow/mlflow
mlflow/llama_index/pyfunc_wrapper.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/pyfunc_wrapper.py
Apache-2.0
def _do_inference(self, input, params: Optional[dict[str, Any]]) -> dict: """ Perform engine inference on a single engine input e.g. not an iterable of engine inputs. The engine inputs must already be preprocessed/cleaned. """ if isinstance(input, dict): return self....
Perform engine inference on a single engine input e.g. not an iterable of engine inputs. The engine inputs must already be preprocessed/cleaned.
_do_inference
python
mlflow/mlflow
mlflow/llama_index/pyfunc_wrapper.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/pyfunc_wrapper.py
Apache-2.0
def _wait_async_task(self, task: asyncio.Future) -> Any: """ A utility function to run async tasks in a blocking manner. If there is no event loop running already, for example, in a model serving endpoint, we can simply create a new event loop and run the task there. However, in a noteb...
A utility function to run async tasks in a blocking manner. If there is no event loop running already, for example, in a model serving endpoint, we can simply create a new event loop and run the task there. However, in a notebook environment (or pytest with asyncio decoration), there i...
_wait_async_task
python
mlflow/mlflow
mlflow/llama_index/pyfunc_wrapper.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/pyfunc_wrapper.py
Apache-2.0
def create_pyfunc_wrapper( model: Any, engine_type: Optional[str] = None, model_config: Optional[dict[str, Any]] = None, ): """ A factory function that creates a Pyfunc wrapper around a LlamaIndex index/engine/workflow. Args: model: A LlamaIndex index/engine/workflow. engine_typ...
A factory function that creates a Pyfunc wrapper around a LlamaIndex index/engine/workflow. Args: model: A LlamaIndex index/engine/workflow. engine_type: The type of the engine. Only required if `model` is an index and must be one of [chat, query, retriever]. model_config: ...
create_pyfunc_wrapper
python
mlflow/mlflow
mlflow/llama_index/pyfunc_wrapper.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/pyfunc_wrapper.py
Apache-2.0
def _construct_prompt_template_object( constructor: Callable, kwargs: dict[str, Any] ) -> PromptTemplate: """Construct a PromptTemplate object based on the constructor and kwargs. This method is necessary because the `template_vars` cannot be passed directly to the constructor and needs to be set on an...
Construct a PromptTemplate object based on the constructor and kwargs. This method is necessary because the `template_vars` cannot be passed directly to the constructor and needs to be set on an instantiated object.
_construct_prompt_template_object
python
mlflow/mlflow
mlflow/llama_index/serialize_objects.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/serialize_objects.py
Apache-2.0
def serialize_settings(path: str) -> None: """Serialize the global LlamaIndex Settings object to a JSON file at the given path.""" from llama_index.core import Settings _logger.info( "API key(s) will be removed from the global Settings object during serialization " "to protect against key l...
Serialize the global LlamaIndex Settings object to a JSON file at the given path.
serialize_settings
python
mlflow/mlflow
mlflow/llama_index/serialize_objects.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/serialize_objects.py
Apache-2.0
def deserialize_settings(path: str): """Deserialize the global LlamaIndex Settings object from a JSON file at the given path.""" settings_dict = _deserialize_dict_of_objects(path) from llama_index.core import Settings for k, v in settings_dict.items(): # To use the property setter rather than ...
Deserialize the global LlamaIndex Settings object from a JSON file at the given path.
deserialize_settings
python
mlflow/mlflow
mlflow/llama_index/serialize_objects.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/serialize_objects.py
Apache-2.0
def set_llama_index_tracer(): """ Set the MlflowSpanHandler and MlflowEventHandler to the global dispatcher. If the handlers are already set, skip setting. """ from llama_index.core.instrumentation import get_dispatcher dsp = get_dispatcher() span_handler = None for handler in dsp.span...
Set the MlflowSpanHandler and MlflowEventHandler to the global dispatcher. If the handlers are already set, skip setting.
set_llama_index_tracer
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def remove_llama_index_tracer(): """ Remove the MlflowSpanHandler and MlflowEventHandler from the global dispatcher. """ from llama_index.core.instrumentation import get_dispatcher dsp = get_dispatcher() dsp.span_handlers = [h for h in dsp.span_handlers if h.class_name() != "MlflowSpanHandler"]...
Remove the MlflowSpanHandler and MlflowEventHandler from the global dispatcher.
remove_llama_index_tracer
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def _end_span(span: LiveSpan, status=SpanStatusCode.OK, outputs=None, token=None): """An utility function to end the span or trace.""" if isinstance(outputs, (StreamingResponse, AsyncStreamingResponse, StreamingAgentChatResponse)): _logger.warning( "Trying to record streaming response to the...
An utility function to end the span or trace.
_end_span
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def prepare_to_drop_span(self, id_: str, err: Optional[Exception], **kwargs) -> _LlamaSpan: """Logic for handling errors during the model execution.""" with self.lock: llama_span = self.open_spans.get(id_) span = llama_span._mlflow_span token = self._span_id_to_token.pop(span...
Logic for handling errors during the model execution.
prepare_to_drop_span
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def _get_span_type(self, instance: Any) -> SpanType: """ Map LlamaIndex instance type to MLflow span type. Some span type cannot be determined by instance type alone, rather need event info e.g. ChatModel, ReRanker """ if isinstance(instance, (BaseLLM, MultiModalLLM)): ...
Map LlamaIndex instance type to MLflow span type. Some span type cannot be determined by instance type alone, rather need event info e.g. ChatModel, ReRanker
_get_span_type
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def _get_instance_attributes(self, instance: Any) -> dict[str, Any]: """ Extract span attributes from LlamaIndex objects. NB: There are some overlap between attributes extracted from instance metadata and the events. For example, model name for an LLM is available in both. However, even...
Extract span attributes from LlamaIndex objects. NB: There are some overlap between attributes extracted from instance metadata and the events. For example, model name for an LLM is available in both. However, events might not always be triggered (e.g. 3P llm integration doesn't implem...
_get_instance_attributes
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def _(self, event: LLMPredictStartEvent, span: LiveSpan): """ An event triggered when LLM's predict() is called. In LlamaIndex, predict() is a gateway method that dispatch the request to either chat() or completion() method depending on the model type, as well as crafting prompt...
An event triggered when LLM's predict() is called. In LlamaIndex, predict() is a gateway method that dispatch the request to either chat() or completion() method depending on the model type, as well as crafting prompt from the template.
_
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def register_stream_span(self, span: LiveSpan, result: Any) -> bool: """ Register the pending streaming span with the associated generator. Args: span: The span that has a streaming output. result: The streaming result that is being processed. Returns: ...
Register the pending streaming span with the associated generator. Args: span: The span that has a streaming output. result: The streaming result that is being processed. Returns: True if the span is registered successfully, False otherwise.
register_stream_span
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def resolve(self, span: LiveSpan, event: _StreamEndEvent): """ Finish the streaming span and recursively resolve the parent spans that returns the same (or derived) stream. """ _, stream = self._span_id_to_span_and_gen.pop(span.span_id, (None, None)) if not stream: ...
Finish the streaming span and recursively resolve the parent spans that returns the same (or derived) stream.
resolve
python
mlflow/mlflow
mlflow/llama_index/tracer.py
https://github.com/mlflow/mlflow/blob/master/mlflow/llama_index/tracer.py
Apache-2.0
def _validate_text_data(data, metric_name, col_specifier): """Validates that the data is a list of strs and is non-empty""" if data is None or len(data) == 0: _logger.warning( f"Cannot calculate {metric_name} for empty inputs: " f"{col_specifier} is empty or the parameter is not ...
Validates that the data is a list of strs and is non-empty
_validate_text_data
python
mlflow/mlflow
mlflow/metrics/metric_definitions.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/metric_definitions.py
Apache-2.0
def _validate_array_like_id_data(data, metric_name, col_specifier): """Validates that the data is a list of lists/np.ndarrays of strings/ints and is non-empty""" if data is None or len(data) == 0: return False for index, value in data.items(): if not ( (isinstance(value, list) a...
Validates that the data is a list of lists/np.ndarrays of strings/ints and is non-empty
_validate_array_like_id_data
python
mlflow/mlflow
mlflow/metrics/metric_definitions.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/metric_definitions.py
Apache-2.0
def _prepare_row_for_ndcg(predictions, targets): """Prepare data one row from predictions and targets to y_score, y_true for ndcg calculation. Args: predictions: A list of strings of at most k doc IDs retrieved. targets: A list of strings of ground-truth doc IDs. Returns: y_true : ...
Prepare data one row from predictions and targets to y_score, y_true for ndcg calculation. Args: predictions: A list of strings of at most k doc IDs retrieved. targets: A list of strings of ground-truth doc IDs. Returns: y_true : ndarray of shape (1, n_docs) Representing the ground-tru...
_prepare_row_for_ndcg
python
mlflow/mlflow
mlflow/metrics/metric_definitions.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/metric_definitions.py
Apache-2.0
def latency() -> EvaluationMetric: """ This function will create a metric for calculating latency. Latency is determined by the time it takes to generate a prediction for a given input. Note that computing latency requires each row to be predicted sequentially, which will likely slow down the evaluation...
This function will create a metric for calculating latency. Latency is determined by the time it takes to generate a prediction for a given input. Note that computing latency requires each row to be predicted sequentially, which will likely slow down the evaluation process.
latency
python
mlflow/mlflow
mlflow/metrics/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py
Apache-2.0
def token_count() -> EvaluationMetric: """ This function will create a metric for calculating token_count. Token count is calculated using tiktoken by using the `cl100k_base` tokenizer. """ return make_metric( eval_fn=_token_count_eval_fn, greater_is_better=True, name="token_...
This function will create a metric for calculating token_count. Token count is calculated using tiktoken by using the `cl100k_base` tokenizer.
token_count
python
mlflow/mlflow
mlflow/metrics/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py
Apache-2.0
def toxicity() -> EvaluationMetric: """ This function will create a metric for evaluating `toxicity`_ using the model `roberta-hate-speech-dynabench-r4`_, which defines hate as "abusive speech targeting specific group characteristics, such as ethnic origin, religion, gender, or sexual orientation." ...
This function will create a metric for evaluating `toxicity`_ using the model `roberta-hate-speech-dynabench-r4`_, which defines hate as "abusive speech targeting specific group characteristics, such as ethnic origin, religion, gender, or sexual orientation." The score ranges from 0 to 1, where sc...
toxicity
python
mlflow/mlflow
mlflow/metrics/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py
Apache-2.0
def exact_match() -> EvaluationMetric: """ This function will create a metric for calculating `accuracy`_ using sklearn. This metric only computes an aggregate score which ranges from 0 to 1. .. _accuracy: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html """ ...
This function will create a metric for calculating `accuracy`_ using sklearn. This metric only computes an aggregate score which ranges from 0 to 1. .. _accuracy: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html
exact_match
python
mlflow/mlflow
mlflow/metrics/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py
Apache-2.0
def rouge1() -> EvaluationMetric: """ This function will create a metric for evaluating `rouge1`_. The score ranges from 0 to 1, where a higher score indicates higher similarity. `rouge1`_ uses unigram based scoring to calculate similarity. Aggregations calculated for this metric: - mean ...
This function will create a metric for evaluating `rouge1`_. The score ranges from 0 to 1, where a higher score indicates higher similarity. `rouge1`_ uses unigram based scoring to calculate similarity. Aggregations calculated for this metric: - mean .. _rouge1: https://huggingface.co/sp...
rouge1
python
mlflow/mlflow
mlflow/metrics/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py
Apache-2.0
def rouge2() -> EvaluationMetric: """ This function will create a metric for evaluating `rouge2`_. The score ranges from 0 to 1, where a higher score indicates higher similarity. `rouge2`_ uses bigram based scoring to calculate similarity. Aggregations calculated for this metric: - mean ...
This function will create a metric for evaluating `rouge2`_. The score ranges from 0 to 1, where a higher score indicates higher similarity. `rouge2`_ uses bigram based scoring to calculate similarity. Aggregations calculated for this metric: - mean .. _rouge2: https://huggingface.co/spa...
rouge2
python
mlflow/mlflow
mlflow/metrics/__init__.py
https://github.com/mlflow/mlflow/blob/master/mlflow/metrics/__init__.py
Apache-2.0