repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
mlflow | examples/catboost/train.py | .py | # Based on the official regression example:
# https://catboost.ai/docs/concepts/python-usages-examples.html#regression
import numpy as np
from catboost import CatBoostRegressor
import mlflow
from mlflow.models import infer_signature
# Initialize data
train_data = np.array([[1, 4, 5, 6], [4, 5, 6, 7], [30, 40, 50, 60... | 39 | 1,057 |
mlflow | examples/statsmodels/train.py | .py | import argparse
import numpy as np
import statsmodels.api as sm
from sklearn.metrics import mean_squared_error
import mlflow
import mlflow.statsmodels
def parse_args():
parser = argparse.ArgumentParser(description="Statsmodels example")
parser.add_argument(
"--inverse-method",
type=str,
... | 56 | 1,332 |
mlflow | examples/pyfunc/custom_code.py | .py | flower_classes = ["setosa", "versicolor", "virginica"]
def iris_classes(preds):
return [flower_classes[x] for x in preds]
| 6 | 128 |
mlflow | examples/pyfunc/infer_model_code_paths.py | .py | from typing import Any
from custom_code import iris_classes
import mlflow
class CustomPredict(mlflow.pyfunc.PythonModel):
"""Custom pyfunc class used to create customized mlflow models"""
def predict(self, context, model_input, params: dict[str, Any] | None = None):
prediction = [x % 3 for x in mod... | 24 | 666 |
mlflow | examples/pyfunc/train.py | .py | import os
from typing import Any
from custom_code import iris_classes
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
import mlflow
from mlflow.models import infer_signature
class CustomPredict(mlflow.pyfunc.PythonModel):
"""Custom pyfunc class used to create customize... | 44 | 1,467 |
mlflow | examples/pyfunc/model_as_code.py | .py | # This example demonstrates defining a model directly from code.
# This feature allows for defining model logic within a python script, module, or notebook that is stored
# directly as serialized code, as opposed to object serialization that would otherwise occur when saving
# or logging a model object.
# This script d... | 53 | 1,998 |
mlflow | examples/pyfunc/model_as_code_driver.py | .py | # This is an example for logging a Python model from code using the
# mlflow.pyfunc.log_model API. When a path to a valid Python script is submitted to the
# python_model argument, the model code itself is serialized instead of the model object.
# Within the targeted script, the model implementation must be defined and... | 29 | 1,013 |
mlflow | examples/openai/embeddings.py | .py | import os
import numpy as np
import openai
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import ColSpec, ParamSchema, ParamSpec, Schema, TensorSpec
assert "OPENAI_API_KEY" in os.environ, " OPENAI_API_KEY environment variable must be set"
print(
"""
# ****************... | 54 | 1,543 |
mlflow | examples/openai/chat_completions.py | .py | import logging
import os
import openai
import pandas as pd
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import ColSpec, ParamSchema, ParamSpec, Schema
logging.getLogger("mlflow").setLevel(logging.ERROR)
# Uncomment the following lines to run this script without using a r... | 189 | 4,976 |
mlflow | examples/openai/completions.py | .py | import os
import openai
import mlflow
from mlflow.models.signature import ModelSignature
from mlflow.types.schema import ColSpec, ParamSchema, ParamSpec, Schema
assert "OPENAI_API_KEY" in os.environ, " OPENAI_API_KEY environment variable must be set"
print(
"""
# ************************************************... | 57 | 1,869 |
mlflow | examples/openai/azure_openai.py | .py | import openai
import pandas as pd
import mlflow
"""
Set environment variables for Azure OpenAI service
export OPENAI_API_KEY="<AZURE OPENAI KEY>"
# OPENAI_API_BASE should be the endpoint of your Azure OpenAI resource
# e.g. https://<service-name>.openai.azure.com/
export OPENAI_API_BASE="<AZURE OPENAI BASE>"
# OPENAI... | 64 | 1,663 |
mlflow | examples/openai/spark_udf.py | .py | import os
import openai
from pyspark.sql import SparkSession
import mlflow
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
with mlflow.start_run():
model_info = mlflow.openai.log_model(
model="gpt-4o-mini",
task=openai.chat.completions,
messag... | 31 | 855 |
mlflow | examples/openai/autologging/module_client.py | .py | import os
import openai
import mlflow
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
mlflow.openai.autolog(
log_input_examples=True,
log_model_signatures=True,
log_models=True,
registered_model_name="openai_model",
)
messages = [
{
"role": "... | 36 | 848 |
mlflow | examples/openai/autologging/instantiated_client.py | .py | import argparse
import os
import openai
import mlflow
mlflow.openai.autolog(
log_input_examples=True,
log_model_signatures=True,
log_models=True,
registered_model_name="openai_model",
)
parser = argparse.ArgumentParser()
parser.add_argument("--api-key", type=str, help="OpenAI API key")
args = parser... | 45 | 1,176 |
mlflow | examples/anthropic/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for Anthropic.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
"""
import os
import anthropic
import mlflow
# Turn on auto tracing for Anthropic by calling mlflow.anthropic.autolog()
mlfl... | 28 | 684 |
mlflow | examples/sentence_transformers/simple.py | .py | from sentence_transformers import SentenceTransformer
import mlflow
import mlflow.sentence_transformers
model = SentenceTransformer("all-MiniLM-L6-v2")
example_sentences = ["This is a sentence.", "This is another sentence."]
# Define the signature
signature = mlflow.models.infer_signature(
model_input=example_s... | 43 | 1,360 |
mlflow | examples/remote_store/remote_server.py | .py | import os
import random
import shutil
import sys
import tempfile
from mlflow import (
MlflowClient,
active_run,
get_artifact_uri,
get_tracking_uri,
log_artifact,
log_artifacts,
log_metric,
log_param,
)
if __name__ == "__main__":
print(f"Running {sys.argv[0]} with tracking URI {get_... | 43 | 1,198 |
mlflow | examples/sklearn_logistic_regression/train.py | .py | import numpy as np
from sklearn.linear_model import LogisticRegression
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
if __name__ == "__main__":
X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
y = np.array([0, 0, 1, 1, 1, 0])
lr = LogisticRegression()
lr.fit(X, y)
... | 20 | 642 |
mlflow | examples/gateway/gemini/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Gemini endpoints: {client.list_endpoints()}\n")
print(f"Gemini completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Chat example
response_chat = clie... | 63 | 1,885 |
mlflow | examples/gateway/bedrock/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Bedrock endpoints: {client.list_endpoints()}\n")
print(f"Bedrock completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions example
response_co... | 24 | 683 |
mlflow | examples/gateway/ai21_labs/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"AI21 Labs endpoints: {client.list_endpoints()}\n")
print(f"AI21 Labs completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
respons... | 23 | 659 |
mlflow | examples/gateway/mistral/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Mistral endpoints: {client.list_endpoints()}\n")
print(f"Mistral completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
response_co... | 35 | 1,037 |
mlflow | examples/gateway/huggingface/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Hugging Face TGI endpoints: {client.list_endpoints()}\n")
print(
f"Hugging Face completions endpoint info: {client.get_endpoint(endpoint='completions')}\n"
)
# Complet... | 26 | 645 |
mlflow | examples/gateway/openai/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"OpenAI endpoints: {client.list_endpoints()}\n")
print(f"OpenAI endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions example
response_completions = cl... | 48 | 1,414 |
mlflow | examples/gateway/anthropic/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Anthropic endpoints: {client.list_endpoints()}\n")
print(f"Anthropic completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
respons... | 24 | 696 |
mlflow | examples/gateway/togetherai/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Togetherai endpoints: {client.list_endpoints()}\n")
print(f"Togetherai completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
print(f"Togetherai chat endpoint... | 44 | 1,314 |
mlflow | examples/gateway/plugin/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://127.0.0.1:7000")
print(f"Plugin endpoints: {client.list_endpoints()}\n")
print(f"Plugin chat endpoint info: {client.get_endpoint(endpoint='chat')}\n")
# Chat request
response_chat = client.predict(
... | 27 | 634 |
mlflow | examples/gateway/plugin/my-llm/my_llm/config.py | .py | import os
from pydantic import field_validator
from mlflow.gateway.base_models import ConfigModel
class MyLLMConfig(ConfigModel):
my_llm_api_key: str
@field_validator("my_llm_api_key", mode="before")
def validate_my_llm_api_key(cls, value):
if value.startswith("$"):
# This resolves ... | 21 | 610 |
mlflow | examples/gateway/plugin/my-llm/my_llm/providers.py | .py | import time
from mlflow.gateway.config import EndpointConfig
from mlflow.gateway.providers import BaseProvider
from mlflow.gateway.schemas import chat
from my_llm.config import MyLLMConfig
class MyLLMProvider(BaseProvider):
NAME = "MyLLM"
CONFIG_TYPE = MyLLMConfig
def __init__(self, config: EndpointConf... | 38 | 1,260 |
mlflow | examples/gateway/mosaicml/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"MosaicML endpoints: {client.list_endpoints()}\n")
print(f"MosaicML completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
response_... | 49 | 1,538 |
mlflow | examples/gateway/uc_functions/run.py | .py | import argparse
import json
import openai
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--uc-function-name",
type=str,
required=True,
help="Name of the UC function to use",
)
return parser.parse_args()
def main():
args = parse_args()
... | 114 | 2,884 |
mlflow | examples/gateway/palm/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"PaLM endpoints: {client.list_endpoints()}\n")
print(f"PaLM completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
response_completi... | 49 | 1,518 |
mlflow | examples/gateway/cohere/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"Cohere endpoints: {client.list_endpoints()}\n")
print(f"Cohere completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
response_comp... | 30 | 905 |
mlflow | examples/gateway/mlflow_models/example.py | .py | # Prior to running the example code below, view the README.md within this directory
from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"MLflow model endpoints: {client.list_endpoints()}\n")
print(f"MLflow completions endpoint info: {cli... | 36 | 1,007 |
mlflow | examples/xgboost/xgboost_native/train.py | .py | import argparse
import matplotlib as mpl
import xgboost as xgb
from sklearn import datasets
from sklearn.metrics import accuracy_score, log_loss
from sklearn.model_selection import train_test_split
import mlflow
import mlflow.xgboost
mpl.use("Agg")
def parse_args():
parser = argparse.ArgumentParser(description... | 79 | 2,084 |
mlflow | examples/xgboost/xgboost_sklearn/train.py | .py | from pprint import pprint
import xgboost as xgb
from sklearn.datasets import load_diabetes
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from utils import fetch_logged_data
import mlflow
import mlflow.xgboost
def main():
# prepare example dataset
X, y = ... | 37 | 1,059 |
mlflow | examples/sklearn_autolog/pipeline.py | .py | from pprint import pprint
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from utils import fetch_logged_data
import mlflow
def main():
# enable autologging
mlflow.sklearn.autolog()
# prepare tra... | 34 | 841 |
mlflow | examples/sklearn_autolog/grid_search_cv.py | .py | from pprint import pprint
import pandas as pd
from sklearn import datasets, svm
from sklearn.model_selection import GridSearchCV
from utils import fetch_logged_data
import mlflow
def main():
mlflow.sklearn.autolog()
iris = datasets.load_iris()
parameters = {"kernel": ("linear", "rbf"), "C": [1, 10]}
... | 41 | 1,183 |
mlflow | examples/sklearn_autolog/linear_regression.py | .py | from pprint import pprint
import numpy as np
from sklearn.linear_model import LinearRegression
from utils import fetch_logged_data
import mlflow
def main():
# enable autologging
mlflow.sklearn.autolog()
# prepare training data
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
y = np.dot(X, np.arra... | 32 | 705 |
mlflow | examples/keras/train.py | .py | """Trains and evaluate a simple MLP
on the Reuters newswire topic classification task.
"""
import numpy as np
from tensorflow import keras
from tensorflow.keras.datasets import reuters
from tensorflow.keras.layers import Activation, Dense, Dropout
from tensorflow.keras.models import Sequential
from tensorflow.keras.pr... | 60 | 1,974 |
mlflow | examples/pydanticai/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for Pydantic AI.
Most codes are from https://ai.pydantic.dev/examples/bank-support/.
"""
import mlflow
import mlflow.pydantic_ai
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("Pydantic AI Example")
mlflow.pydantic_ai.aut... | 87 | 2,551 |
mlflow | examples/h2o/random_forest.py | .py | import h2o
from h2o.estimators.random_forest import H2ORandomForestEstimator
import mlflow
import mlflow.h2o
h2o.init()
wine = h2o.import_file(path="wine-quality.csv")
r = wine["quality"].runif()
train = wine[r < 0.7]
test = wine[0.3 <= r]
def train_random_forest(ntrees):
with mlflow.start_run():
rf = ... | 33 | 841 |
mlflow | examples/open_webui/mlflow_filter_pipeline.py | .py | # ruff: noqa
"""
title: MLflow Filter Pipeline
author: open-webui
date: 2026-04-20
version: 0.0.1
license: MIT
description: A filter pipeline that uses MLflow for tracing multi-turn chat sessions.
requirements: mlflow>=2.14.0
"""
from typing import List, Optional
import os
import re
import uuid
from utils.pipelines.m... | 162 | 6,093 |
mlflow | examples/jwt_auth/jwt_auth.py | .py | """Sample JWT authentication module for testing purposes.
NOT SUITABLE FOR PRODUCTION USE.
"""
import logging
import jwt
from flask import Response, make_response, request
from werkzeug.datastructures import Authorization
BEARER_PREFIX = "bearer "
_logger = logging.getLogger(__name__)
def authenticate_request() ... | 45 | 1,537 |
mlflow | examples/jwt_auth/__init__.py | .py | """The jwt_auth.py example in this module directory is also used by
tests/server/auth/test_auth.py.
"""
| 4 | 104 |
mlflow | examples/supply_chain_security/train.py | .py | import sklearn
import mlflow
# Use explicit model logging to control the conda environment and pip requirements
mlflow.sklearn.autolog(log_models=False)
# Load data
X, y = sklearn.datasets.load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(
X, y, test_size=... | 27 | 707 |
mlflow | examples/livekit/voice_agent.py | .py | import logging
import os
from livekit.agents import JobContext, JobProcess, WorkerOptions, cli
from livekit.agents.telemetry import set_tracer_provider
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import openai, silero
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.... | 79 | 2,646 |
mlflow | examples/hyperparam/train.py | .py | """
Train a simple Keras DL model on the dataset used in MLflow tutorial (wine-quality.csv).
Dataset is split into train (~ 0.56), validation(~ 0.19) and test (0.25).
Validation data is used to select the best hyperparameters, test set performance is evaluated only
at epochs which improved performance on the validatio... | 170 | 6,808 |
mlflow | examples/hyperparam/search_hyperopt.py | .py | """
Example of hyperparameter search in MLflow using Hyperopt.
The run method will instantiate and run Hyperopt optimizer. Each parameter configuration is
evaluated in a new MLflow run invoking main entry point with selected parameters.
The runs are evaluated based on validation set loss. Test set score is calculated... | 166 | 6,374 |
mlflow | examples/hyperparam/search_random.py | .py | """
Example of hyperparameter search in MLflow using simple random search.
The run method will evaluate random combinations of parameters in a new MLflow run.
The runs are evaluated based on validation set loss. Test set score is calculated to verify the
results.
Several runs can be run in parallel.
"""
from concur... | 117 | 4,582 |
mlflow | examples/pyspark_ml_connect/pipeline.py | .py | from pyspark.ml.connect.classification import LogisticRegression
from pyspark.ml.connect.feature import StandardScaler
from pyspark.ml.connect.pipeline import Pipeline
from pyspark.sql import SparkSession
from sklearn import datasets
import mlflow
spark = SparkSession.builder.remote("local[2]").getOrCreate()
scaler ... | 38 | 1,337 |
mlflow | examples/transformers/conversational.py | .py | import transformers
import mlflow
conversational_pipeline = transformers.pipeline(model="microsoft/DialoGPT-medium")
with mlflow.start_run():
model_info = mlflow.transformers.log_model(
transformers_model=conversational_pipeline,
name="chatbot",
task="conversational",
input_exampl... | 26 | 680 |
mlflow | examples/transformers/simple.py | .py | import transformers
import mlflow
task = "text-generation"
generation_pipeline = transformers.pipeline(
task=task,
model="gpt2",
)
input_example = ["prompt 1", "prompt 2", "prompt 3"]
parameters = {"max_length": 512, "do_sample": True}
with mlflow.start_run() as run:
model_info = mlflow.transformers.l... | 32 | 806 |
mlflow | examples/transformers/load_components.py | .py | import transformers
import mlflow
pipeline = transformers.pipeline(
task="fill-mask",
model=transformers.AutoModelForMaskedLM.from_pretrained("distilbert-base-uncased"),
tokenizer=transformers.AutoTokenizer.from_pretrained("distilbert-base-uncased"),
)
with mlflow.start_run():
model_info = mlflow.tra... | 32 | 861 |
mlflow | examples/transformers/sentence_transformer.py | .py | import torch
from transformers import BertModel, BertTokenizerFast, pipeline
import mlflow
sentence_transformers_architecture = "sentence-transformers/all-MiniLM-L12-v2"
task = "feature-extraction"
model = BertModel.from_pretrained(sentence_transformers_architecture)
tokenizer = BertTokenizerFast.from_pretrained(sen... | 55 | 1,836 |
mlflow | examples/transformers/whisper.py | .py | import requests
import transformers
import mlflow
# Acquire an audio file
resp = requests.get(
"https://github.com/mlflow/mlflow/raw/master/tests/datasets/apollo11_launch.wav"
)
resp.raise_for_status()
audio = resp.content
task = "automatic-speech-recognition"
architecture = "openai/whisper-tiny"
model = transf... | 57 | 2,046 |
mlflow | examples/prophet/train.py | .py | import numpy as np
import pandas as pd
from prophet import Prophet, serialize
from prophet.diagnostics import cross_validation, performance_metrics
import mlflow
SOURCE_DATA = (
"https://raw.githubusercontent.com/facebook/prophet/master/examples/example_retail_sales.csv"
)
np.random.seed(12345)
def extract_para... | 55 | 1,483 |
mlflow | examples/flower_classifier/train.py | .py | """
Example of image classification with MLflow using Keras to classify flowers from photos. The data is
taken from ``http://download.tensorflow.org/example_images/flower_photos.tgz`` and may be
downloaded during running this project if it is missing.
"""
import math
import os
import tarfile
import click
import keras... | 245 | 9,361 |
mlflow | examples/flower_classifier/image_pyfunc.py | .py | """
Example of a custom python function implementing image classifier with image preprocessing embedded
in the model.
"""
import base64
import importlib.metadata
import os
from io import BytesIO
from typing import Any
import keras
import numpy as np
import pandas as pd
import PIL
import tensorflow as tf
import yaml
f... | 194 | 6,708 |
mlflow | examples/flower_classifier/score_images_spark.py | .py | """
Example of scoring images with MLflow model produced by running this project in Spark.
The MLflow model is loaded to Spark using ``mlflow.pyfunc.spark_udf``. The images are read as binary
data and represented as base64 encoded string column and passed to the model. The results are
returned as a column with predict... | 98 | 2,997 |
mlflow | examples/flower_classifier/score_images_rest.py | .py | """
Example of scoring images with MLflow model deployed to a REST API endpoint.
The MLflow model to be scored is expected to be an instance of KerasImageClassifierPyfunc
(e.g. produced by running this project) and deployed with MLflow prior to invoking this script.
"""
import base64
import os
import click
import pa... | 72 | 1,922 |
mlflow | examples/agno/tracing.py | .py | import mlflow
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("AGNO Reasoning Finance Team")
mlflow.agno.autolog()
mlflow.anthropic.autolog()
mlflow.openai.autolog()
from agno.agent import Agent
from agno.models.anthropic import Claude
from agno.models.openai import OpenAIChat
from agno.team.t... | 77 | 2,781 |
mlflow | examples/llms/question_answering/question_answering.py | .py | import os
import openai
import pandas as pd
import mlflow
assert "OPENAI_API_KEY" in os.environ, (
"Please set the OPENAI_API_KEY environment variable to run this example."
)
def build_and_evaluate_model_with_prompt(system_prompt):
mlflow.start_run()
mlflow.log_param("system_prompt", system_prompt)
... | 71 | 2,486 |
mlflow | examples/llms/summarization/summarization.py | .py | import os
import pandas as pd
from langchain.chains import LLMChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
import mlflow
assert "OPENAI_API_KEY" in os.environ, (
"Please set the OPENAI_API_KEY environment variable to run this example."
)
def build_and_evaluate_model_with... | 81 | 3,635 |
mlflow | examples/mlflow-3/evaluate_example.py | .py | from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import mlflow
from mlflow.models import infer_signature
X, y = load_iris(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0... | 43 | 1,377 |
mlflow | examples/mlflow-3/load_model_from_runs_uri.py | .py | from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
import mlflow
from mlflow.models import infer_signature
X, y = load_iris(return_X_y=True, as_frame=True)
model = LogisticRegression().fit(X, y)
signature = infer_signature(X, model.predict(X))
with mlflow.start_run() as run:
... | 16 | 519 |
mlflow | examples/mlflow-3/proto_inputs_outputs.py | .py | import pandas as pd
from sklearn.model_selection import train_test_split
import mlflow
from mlflow.entities import (
DatasetInput,
LoggedModelInput,
LoggedModelOutput,
LoggedModelStatus,
Run,
)
client = mlflow.MlflowClient()
# Read the wine-quality csv file from the URL
csv_url = (
"https://r... | 47 | 1,785 |
mlflow | examples/mlflow-3/sklearn_autolog.py | .py | """
python examples/mlflow-3/sklearn_autolog.py
"""
import os
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
import mlflow
os.environ["MLFLOW_AUTOLOGGING_TESTING"] = "true"
mlflow.sklearn.autolog()
X, y ... | 41 | 996 |
mlflow | examples/mlflow-3/langchain_example.py | .py | from langchain_community.chat_models import ChatDatabricks
from langchain_core.prompts import ChatPromptTemplate
import mlflow
# Define the chain
chat_model = ChatDatabricks(
endpoint="databricks-llama-2-70b-chat",
temperature=0.1,
max_tokens=2000,
)
prompt = ChatPromptTemplate.from_messages([
(
... | 230 | 7,503 |
mlflow | examples/mlflow-3/register_model.py | .py | import json
from sklearn.linear_model import LinearRegression
import mlflow
client = mlflow.MlflowClient()
with mlflow.start_run():
model = LinearRegression().fit([[1], [2]], [3, 4])
model_info = mlflow.sklearn.log_model(
model,
name="model",
params={
"alpha": 0.5,
... | 71 | 2,072 |
mlflow | examples/mlflow-3/langchain_simple.py | .py | import mlflow
mlflow.langchain.autolog(log_models=True)
from langchain_core.runnables import RunnableLambda
with mlflow.start_run() as run:
r = RunnableLambda(lambda x: x + 1)
r.invoke(3)
trace = mlflow.search_traces(locations=[run.info.experiment_id], max_results=1).iloc[0]
assert "mlflow.modelId" in trace... | 20 | 559 |
mlflow | examples/mlflow-3/langchain_databricks_example.py | .py | """
python examples/mlflow-3/langchain_databricks_example.py
"""
from databricks.sdk import WorkspaceClient
from langchain_core.runnables import RunnableLambda
import mlflow
mlflow.langchain.autolog(log_models=True)
wc = WorkspaceClient()
mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(f"/Users/{wc.curr... | 21 | 498 |
mlflow | examples/mlflow-3/sklearn_example.py | .py | # ruff: noqa
"""
python examples/demo.py
"""
import logging
import tempfile
import numpy as np
import pandas as pd
from sklearn.linear_model import ElasticNet
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
import mlflow
# Read the ... | 127 | 3,666 |
mlflow | examples/uv-dependency-management/log_model.py | .py | """
Example: Using uv for dependency management with MLflow models.
This script demonstrates three ways to use uv lockfile-based dependencies
when logging MLflow models:
1. Auto-detection: MLflow detects uv.lock + pyproject.toml in the current
working directory and uses ``uv export`` to capture pinned dependencies... | 218 | 7,071 |
mlflow | examples/sktime/train.py | .py | import json
import flavor
import pandas as pd
from sktime.datasets import load_longley
from sktime.forecasting.model_selection import temporal_train_test_split
from sktime.forecasting.naive import NaiveForecaster
from sktime.performance_metrics.forecasting import (
mean_absolute_error,
mean_absolute_percentage... | 83 | 2,809 |
mlflow | examples/sktime/test_sktime_model_export.py | .py | import os
from pathlib import Path
from unittest import mock
import boto3
import flavor
import moto
import numpy as np
import pandas as pd
import pytest
from botocore.config import Config
from sktime.datasets import load_airline, load_longley
from sktime.datatypes import convert
from sktime.forecasting.arima import Au... | 388 | 15,194 |
mlflow | examples/sktime/score_model.py | .py | import pandas as pd
import requests
from sktime.datasets import load_longley
from sktime.forecasting.model_selection import temporal_train_test_split
y, X = load_longley()
y_train, y_test, X_train, X_test = temporal_train_test_split(y, X)
# Define local host and endpoint url
host = "127.0.0.1"
url = f"http://{host}:5... | 35 | 1,253 |
mlflow | examples/sktime/flavor.py | .py | """The ``flavor`` module provides an example for a custom model flavor for ``sktime`` library.
This module exports ``sktime`` models in the following formats:
sktime (native) format
This is the main flavor that can be loaded back into ``sktime``, which relies on pickle
internally to serialize a model.
No... | 546 | 23,456 |
mlflow | examples/virtualenv/project/entrypoint.py | .py | import argparse
import os
import sys
import numpy as np
import sklearn
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
import mlflow
parser = argparse.ArgumentParser()
parser.add_argument(
"--test",
action="store_true",
help="If spec... | 34 | 892 |
mlflow | examples/pmdarima/train.py | .py | import json
import numpy as np
from pmdarima import auto_arima, model_selection
from pmdarima.datasets import load_wineind
import mlflow
from mlflow.models import infer_signature
ARTIFACT_PATH = "model"
def calculate_cv_metrics(model, endog, metric, cv):
cv_metric = model_selection.cross_val_score(model, endog... | 64 | 1,842 |
mlflow | examples/crewai/tracing.py | .py | """
This is an example for leveraging MLflow's auto tracing capabilities for CrewAI.
Most codes are from https://github.com/crewAIInc/crewAI-examples/tree/main/trip_planner.
For more information about MLflow Tracing, see: https://mlflow.org/docs/latest/llms/tracing/index.html
Note that the following example works with... | 144 | 5,413 |
mlflow | examples/rapids/mlflow_project/src/rf_test/train.py | .py | """Hyperparameter optimization with cuML, hyperopt, and MLflow"""
import argparse
from functools import partial
from cuml.ensemble import RandomForestClassifier
from cuml.metrics.accuracy import accuracy_score
from cuml.preprocessing.model_selection import train_test_split
from hyperopt import STATUS_OK, Trials, fmin... | 132 | 3,980 |
mlflow | examples/rapids/mlflow_project/src/rf_test/train_simple.py | .py | """Simple example integrating cuML with MLflow"""
import argparse
from cuml.ensemble import RandomForestClassifier
from cuml.metrics.accuracy import accuracy_score
from cuml.preprocessing.model_selection import train_test_split
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
def load_... | 105 | 3,190 |
mlflow | examples/pip_requirements/pip_requirements.py | .py | """
This example demonstrates how to specify pip requirements using `pip_requirements` and
`extra_pip_requirements` when logging a model via `mlflow.*.log_model`.
"""
import tempfile
import sklearn
import xgboost as xgb
from sklearn.datasets import load_iris
import mlflow
from mlflow.artifacts import download_artifa... | 113 | 4,177 |
mlflow | examples/shap/multiclass_classification.py | .py | import os
import numpy as np
import shap
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import mlflow
from mlflow.artifacts import download_artifacts
from mlflow.tracking import MlflowClient
# prepare training data
X, y = load_iris(return_X_y=True, as_frame=True)
# train... | 38 | 1,050 |
mlflow | examples/shap/regression.py | .py | import os
import numpy as np
import shap
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
import mlflow
from mlflow.artifacts import download_artifacts
from mlflow.tracking import MlflowClient
# prepare training data
X, y = load_diabetes(return_X_y=True, as_frame=True)
X =... | 39 | 1,080 |
mlflow | examples/shap/binary_classification.py | .py | import os
import numpy as np
import shap
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
import mlflow
from mlflow.artifacts import download_artifacts
from mlflow.tracking import MlflowClient
# prepare training data
X, y = load_breast_cancer(return_X_y=True, as_fra... | 39 | 1,123 |
mlflow | examples/shap/explainer_logging.py | .py | import shap
import sklearn
from sklearn.datasets import load_diabetes
import mlflow
# prepare training data
X, y = load_diabetes(return_X_y=True, as_frame=True)
# train a model
model = sklearn.ensemble.RandomForestRegressor(n_estimators=100)
model.fit(X, y)
# create an explainer
explainer_original = shap.Explainer(... | 28 | 710 |
mlflow | examples/llama_index/autolog.py | .py | """
This is an example for leveraging MLflow's autologging capabilities for LlamaIndex.
For more information about MLflow LlamaIndex integration, see:
https://mlflow.org/docs/latest/llms/llama-index/index.html
"""
import os
from llama_index.agent.openai import OpenAIAgent
from llama_index.core import Document, Setti... | 80 | 2,386 |
mlflow | examples/llama_index/simple_index.py | .py | """
This is an example for logging a LlamaIndex index to MLflow and loading it back for querying
via specific engine types - query engine, chat engine, and retriever.
For more information about MLflow LlamaIndex integration, see:
https://mlflow.org/docs/latest/llms/llama-index/index.html
"""
import os
from llama_ind... | 80 | 3,043 |
mlflow | examples/llama_index/workflow/workflow/workflow.py | .py | import os
import qdrant_client
from llama_index.core import Settings, VectorStoreIndex
from llama_index.core.schema import NodeWithScore
from llama_index.core.workflow import Context, StartEvent, StopEvent, Workflow, step
from llama_index.postprocessor.rankgpt_rerank import RankGPTRerank
from llama_index.retrievers.bm... | 149 | 6,387 |
mlflow | examples/llama_index/workflow/workflow/model.py | .py | from workflow.workflow import HybridRAGWorkflow
import mlflow
# Get model config from ModelConfig singleton (specified via `model_config` parameter when logging the model)
model_config = mlflow.models.ModelConfig()
retrievers = model_config.get("retrievers")
# Create the workflow instance.
workflow = HybridRAGWorkfl... | 15 | 577 |
mlflow | examples/llama_index/workflow/workflow/prompts.py | .py | # Prompt to transform user query to the web search query format
TRANSFORM_QUERY_TEMPLATE = """\
Your task is to refine a query to ensure it is highly effective for retrieving relevant search results.
Analyze the given input to grasp the core semantic intent or meaning.
Original Query:
-------------------
{query}
Your... | 27 | 921 |
mlflow | examples/llama_index/workflow/workflow/events.py | .py | from typing import Literal
from llama_index.core.schema import NodeWithScore
from llama_index.core.workflow import Event
class VectorSearchRetrieveEvent(Event):
"""Event for triggering VectorStore index retrieval step."""
query: str
class BM25RetrieveEvent(Event):
"""Event for triggering BM25 retrieva... | 48 | 1,000 |
Qwen3 | eval/eval/arc_agi_1.py | .py | import json
import re
from collections import defaultdict
import numpy as np
def parse_model_output(output):
try:
return json.loads(output)
except json.JSONDecodeError:
json_match = re.findall(r"```(?:json|python)\s*(.*?)\s*```", output, re.DOTALL)
if json_match:
try:
... | 61 | 2,162 |
Qwen3 | eval/eval/eval.py | .py | import json
import argparse
from tqdm import tqdm
import os
import yaml
ALL_TASKS = {}
from arc_agi_1 import compute_scores_arc_agi_1
ALL_TASKS['arc_agi_1'] = compute_scores_arc_agi_1
def get_after_think(text):
parts = text.split("\n</think>\n\n", 1)
if len(parts) > 1:
return parts[1]
else:
... | 88 | 2,703 |
Qwen3 | eval/generate_api_answers/infer_multithread.py | .py | import json
import argparse
from tqdm import tqdm
import copy
import concurrent.futures
import threading
import os
import collections
import yaml
from utils_vllm import get_content
file_lock = threading.Lock()
def count_completed_samples(output_file):
prompt_counts = collections.defaultdict(int)
if os.path.... | 186 | 5,670 |
Qwen3 | eval/generate_api_answers/utils_vllm.py | .py | import os
import time
import random
import openai
import logging
from packaging.version import parse as parse_version
IS_OPENAI_V1 = parse_version(openai.__version__) >= parse_version("1.0.0")
if IS_OPENAI_V1:
from openai import APIError, APIConnectionError, RateLimitError
else:
from openai.error import APIEr... | 101 | 3,067 |
Qwen3 | docs/source/conf.py | .py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 121 | 3,798 |
Qwen3 | examples/demo/web_demo.py | .py | # Copyright (c) Alibaba Cloud.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""A simple web interactive chat demo based on gradio."""
from argparse import ArgumentParser
from threading import Thread
import gradio as gr
import torch
from tra... | 207 | 6,723 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.