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/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 |
wandb | hatch_build.py | .py | import dataclasses
import importlib.util
import os
import pathlib
import platform
import re
import shutil
import sys
import sysconfig
from typing import Any
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
from typing_extensions import override
# A small hack to allow importing build scripts f... | 324 | 10,929 |
wandb | noxfile.py | .py | from __future__ import annotations
import os
import pathlib
import platform
import re
import shutil
import subprocess
import textwrap
import time
from collections.abc import Callable
from contextlib import contextmanager
from typing import Any
import nox
nox.options.default_venv_backend = "uv"
_SUPPORTED_PYTHONS = ... | 870 | 27,721 |
wandb | xpu/hatch.py | .py | """Builds the wandb-xpu binary for monitoring hardware accelerators."""
import json
import pathlib
import subprocess
class WandbXpuBuildError(Exception):
"""Raised when building wandb-xpu service fails."""
def build_wandb_xpu(
cargo_binary: pathlib.Path,
output_path: pathlib.Path,
target_triple: st... | 71 | 2,404 |
wandb | tools/wandb_export_history.py | .py | #!/usr/bin/env python
"""Export W&B run history.
This module uses the W&B public api to download unsampled history to a
sqlite database.
Usage:
./wandb_export_history --run entity/project/run_id --db_file save.db
or:
```python
import wandb_export_history
wandb_export_history(run="entity/project/run_... | 109 | 2,887 |
wandb | tools/changelog.py | .py | import contextlib
import os
from datetime import datetime
import click
@click.command()
@click.option(
"--version",
required=True,
help="The version being released.",
)
def main(version: str):
"""Update CHANGELOG files for a new release."""
changes = _cut_unreleased()
_insert_changelog(versio... | 62 | 1,611 |
wandb | tools/local_wandb_server.py | .py | """Commands for using a local-testcontainer for testing."""
from __future__ import annotations
import contextlib
import dataclasses
import json
import pathlib
import pprint
import re
import shlex
import subprocess
import sys
import time
import traceback
from collections.abc import Generator
import click
import filel... | 480 | 13,372 |
wandb | tools/inspect_tool.py | .py | # /// script
# requires-python = ">=3.8"
# dependencies = [
# "fire",
# "wandb",
# ]
# ///
import fire
import wandb
from wandb.proto import wandb_internal_pb2
from wandb.sdk.internal import datastore
def inspect_wandb_transaction_log(wandb_file: str, pause: bool = False) -> None:
"""Inspect a wandb transacti... | 65 | 1,873 |
wandb | tools/telemetry-tool.py | .py | #!/usr/bin/env python
"""Generate dbt files for telemetry.
Data directory for telemetry records:
https://github.com/wandb/analytics/tree/master/dbt/data
Usage:
./wandb/tools/telemetry-tool.py --output-dir analytics/dbt/seeds/
"""
import argparse
import csv
import os
from typing import Any
from wandb.proto i... | 72 | 2,370 |
wandb | tools/generate-tool.py | .py | #!/usr/bin/env python
"""Generate code for wandb SDK.
Usage:
./tools/generate-tool.py --generate
./tools/generate-tool.py --check
./tools/generate-tool.py --generate --check
./tools/generate-tool.py --generate --check wandb/sdk/lib/_wburls_generated.py
"""
import argparse
import contextlib
import file... | 120 | 3,449 |
wandb | tools/generate_stubs.py | .py | r"""Generate and verify stubs for public APIs in the wandb module.
This script automates the process of creating and validating type stub files
for the wandb module's public APIs. It performs the following steps:
1. Generate stubs:
- Read the __init__.template.pyi file, which contains signatures of public APIs
... | 247 | 8,591 |
wandb | tools/graphql_codegen/plugin_utils.py | .py | """Custom helper functions for the GraphQL codegen plugin."""
from __future__ import annotations
import ast
from collections.abc import Iterable
from typing import Any, TypeGuard
from pydantic import BaseModel, Field, field_validator
def imported_names(stmt: ast.Import | ast.ImportFrom) -> list[str]:
"""Return... | 136 | 5,168 |
wandb | tools/graphql_codegen/plugin.py | .py | """Plugin module to customize GraphQL-to-Python code generation.
NOTE: As this is a dev-only tool, Python 3.10+ is required.
For more info, see:
- https://github.com/mirumee/ariadne-codegen/blob/main/PLUGINS.md
- https://github.com/mirumee/ariadne-codegen/blob/main/ariadne_codegen/plugins/base.py
"""
from __future__... | 509 | 21,113 |
wandb | tools/perf/scripts/test_case_helper.py | .py | import logging
import time
from pathlib import Path
from typing import Literal
from .bench_run_log import Experiment
from .process_sar_helper import capture_sar_metrics, process_sar_files
logger = logging.getLogger(__name__)
def run_perf_tests(
loop_count: int,
num_steps_options: list[int],
num_metrics_... | 72 | 2,570 |
wandb | tools/perf/scripts/setup_helper.py | .py | import logging
from . import _PACKAGE_LOGGER
def setup_package_logger() -> None:
"""Configure the package logger to write to a file and to the screen."""
_PACKAGE_LOGGER.setLevel(logging.DEBUG)
# Create handlers for screen (console) and file logging
console_handler = logging.StreamHandler()
file... | 28 | 918 |
wandb | tools/perf/scripts/process_sar_helper.py | .py | import argparse
import json
import logging
import subprocess
from pathlib import Path
logger = logging.getLogger(__name__)
def pre_process_network_sar_log(log_dir: str) -> str:
"""This helper function pre-processes the network.dev.log.
Parse out the metrics of the device we are interested in. i.e. eth0.
... | 265 | 8,967 |
wandb | tools/perf/scripts/__init__.py | .py | import logging
_PACKAGE_LOGGER = logging.getLogger(__name__)
| 4 | 62 |
wandb | tools/perf/scripts/bench_run_log.py | .py | from __future__ import annotations
import argparse
import json
import logging
import multiprocessing as mp
import random
import string
import time
from datetime import datetime
from typing import Literal
import numpy as np
import wandb
from .setup_helper import setup_package_logger
logger = logging.getLogger(__name... | 734 | 24,301 |
wandb | tools/perf/scripts/run_load_tests.py | .py | from __future__ import annotations
import argparse
import datetime
import logging
import os
import time
from dataclasses import dataclass
from typing import Literal
from .setup_helper import setup_package_logger
from .test_case_helper import run_perf_tests
logger = logging.getLogger(__name__)
@dataclass
class Argu... | 208 | 6,762 |
wandb | tools/perf/scripts/push_perf_results_helper.py | .py | import argparse
import json
import logging
import os
import re
import wandb
logger = logging.getLogger(__name__)
def log_to_wandb(args: argparse.Namespace) -> None:
# Initialize a W&B run
with wandb.init(
project=args.project, name=args.run_name, job_type="performance_test"
) as run:
# L... | 76 | 2,126 |
wandb | tools/bench/_timing.py | .py | #!/usr/bin/env python
from __future__ import annotations
import csv
import dataclasses
import time
@dataclasses.dataclass(frozen=True)
class FunctionTiming:
function_name: str
runtime_seconds: float
def timeit(
timings: list[FunctionTiming],
):
"""Timing decorator.
Args:
timings: list ... | 57 | 1,363 |
wandb | tools/bench/_load_profiles.py | .py | #!/usr/bin/env python
import itertools
VARIANTS = {
"mode=online": {},
"mode=offline": {
"mode": "offline",
},
"core=false": {},
"core=true": {
"core": "true",
},
}
ALL_VARIANTS = {
"mode": ("offline", "online"),
"core": ("false", "true"),
}
PROFILES = {
"v1-empty... | 80 | 2,028 |
wandb | tools/bench/bench.py | .py | #!/usr/bin/env python
import argparse
import multiprocessing
import _load_profiles
import _timing
import numpy
import wandb
VERSION: str = "v1-2024-04-11-0"
BENCH_OUTFILE: str = "bench.csv"
BENCH_FIELDS: tuple[str] = (
"test_name",
"test_profile",
"test_variant",
"client_version",
"client_type",
... | 133 | 4,033 |
wandb | wandb/wandb_agent.py | .py | from __future__ import annotations
import contextlib
import enum
import logging
import multiprocessing
import os
import platform
import queue
import re
import signal
import socket
import subprocess
import sys
import time
import traceback
from collections.abc import Callable
from typing import Any
import wandb
from wa... | 835 | 31,764 |
wandb | wandb/wandb_controller.py | .py | """Sweep controller.
This module implements the sweep controller.
On error an exception is raised:
ControllerError
Example:
import wandb
#
# create a sweep controller
#
# There are three different ways sweeps can be created:
# (1) create with sweep id from `wandb sweep` command
sweep... | 715 | 24,708 |
wandb | wandb/_iterutils.py | .py | from __future__ import annotations
from collections.abc import Hashable, Iterable
from typing import TYPE_CHECKING, Any, TypeVar, overload
if TYPE_CHECKING:
T = TypeVar("T")
HashableT = TypeVar("HashableT", bound=Hashable)
ClassInfo = type[T] | tuple[type[T], ...]
@overload
def always_list(obj: Iterable... | 74 | 2,726 |
wandb | wandb/_analytics.py | .py | from __future__ import annotations
from collections.abc import Callable
from contextvars import ContextVar
from dataclasses import dataclass, field
from functools import wraps
from typing import Final, TypeVar
from uuid import UUID, uuid4
from typing_extensions import ParamSpec
from wandb._strutils import nameof
P ... | 67 | 2,013 |
wandb | wandb/data_types.py | .py | """This module defines data types for logging rich, interactive visualizations to W&B.
Data types include common media types, like images, audio, and videos,
flexible containers for information, like tables and HTML, and more.
For more on logging media, see [our guide](https://docs.wandb.ai/models/track/log/media)
F... | 69 | 2,338 |
wandb | wandb/trigger.py | .py | """Module to facilitate adding hooks to wandb actions.
Usage:
import trigger
trigger.register('on_something', func)
trigger.call('on_something', *args, **kwargs)
trigger.unregister('on_something', func)
"""
from collections.abc import Callable
from typing import Any
_triggers = {}
def reset():
... | 31 | 642 |
wandb | wandb/util.py | .py | from __future__ import annotations
import colorsys
import contextlib
import dataclasses
import enum
import importlib
import importlib.util
import json
import logging
import math
import numbers
import os
import pathlib
import platform
import queue
import random
import re
import secrets
import shlex
import socket
import... | 1,729 | 54,735 |
wandb | wandb/__main__.py | .py | from wandb.cli import cli
cli.cli(prog_name="python -m wandb")
| 4 | 64 |
wandb | wandb/__init__.py | .py | """Use wandb to track machine learning work.
Train and fine-tune models, manage models from experimentation to production.
For guides and examples, see https://docs.wandb.ai.
For scripts and interactive notebooks, see https://github.com/wandb/examples.
For reference documentation, see https://docs.wandb.ai/models/r... | 215 | 5,914 |
wandb | wandb/sklearn.py | .py | from wandb.integration.sklearn import (
plot_calibration_curve,
plot_class_proportions,
plot_classifier,
plot_clusterer,
plot_confusion_matrix,
plot_elbow_curve,
plot_feature_importances,
plot_learning_curve,
plot_outlier_candidates,
plot_precision_recall,
plot_regressor,
... | 36 | 803 |
wandb | wandb/_strutils.py | .py | from __future__ import annotations
from base64 import b64decode, b64encode
from collections.abc import Iterable
from typing import Any
def ensureprefix(s: str, prefix: str) -> str:
"""Ensures the string has the given prefix prepended."""
return s if s.startswith(prefix) else f"{prefix}{s}"
def nameof(obj: ... | 41 | 1,279 |
wandb | wandb/env.py | .py | """All of W&B's environment variables.
Getters and putters for all of them should go here. That way it'll be easier to
avoid typos with names and be consistent about environment variables' semantics.
Environment variables are not the authoritative source for these values in many
cases.
"""
from __future__ import ann... | 536 | 13,994 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.