### Run the mcp_demo example Source: https://docs.wandb.ai/weave/guides/integrations/mcp Clone the docs repository, navigate to the mcp_demo example, install the required dependencies (mcp[cli] and weave), and run the demo. The final command launches both the client and server, starting an interactive CLI. ```bash git clone https://github.com/wandb/docs cd docs/weave/examples/mcp_demo ``` ```bash pip install mcp[cli] weave ``` ```bash python example_client.py example_server.py ``` -------------------------------- ### Install dependencies and setup API keys Source: https://docs.wandb.ai/weave/cookbooks/Intro_to_Weave_Hello_Trace Installs the required SDKs and initializes the W&B project using environment variables for authentication. ```python !pip install wandb weave openai -q import json import os from getpass import getpass from openai import OpenAI import weave # πŸ”‘ Setup your API keys # Running this cell will prompt you for your API key with `getpass` and will not echo to the terminal. ##### print("---") print( "Create a W&B API key at: https://wandb.ai/settings#apikeys" ) os.environ["WANDB_API_KEY"] = getpass("Enter your W&B API key: ") print("---") print("You can generate your OpenAI API key here: https://platform.openai.com/api-keys") os.environ["OPENAI_API_KEY"] = getpass("Enter your OpenAI API key: ") print("---") ##### # 🏠 Enter your W&B project name weave_client = weave.init("MY_PROJECT_NAME") # 🐝 Your W&B project name ``` -------------------------------- ### Initialize and run SDXL pipeline in a notebook Source: https://docs.wandb.ai/models/integrations/diffusers This complete example shows the full setup including pipeline initialization, autologging, and experiment finalization within a notebook environment. ```python import torch from diffusers import StableDiffusionXLImg2ImgPipeline, StableDiffusionXLPipeline import wandb from wandb.integration.diffusers import autolog run = wandb.init() # initialize the SDXL base pipeline base_pipeline = StableDiffusionXLPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True, ) base_pipeline.enable_model_cpu_offload() # initialize the SDXL refiner pipeline refiner_pipeline = StableDiffusionXLImg2ImgPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-refiner-1.0", text_encoder_2=base_pipeline.text_encoder_2, vae=base_pipeline.vae, torch_dtype=torch.float16, use_safetensors=True, variant="fp16", ) refiner_pipeline.enable_model_cpu_offload() prompt = "a photo of an astronaut riding a horse on mars" negative_prompt = "static, frame, painting, illustration, sd character, low quality, low resolution, greyscale, monochrome, nose, cropped, lowres, jpeg artifacts, deformed iris, deformed pupils, bad eyes, semi-realistic worst quality, bad lips, deformed mouth, deformed face, deformed fingers, deformed toes standing still, posing" # Make the experiment reproducible by controlling randomness. # The seed would be automatically logged to WandB. seed = 42 generator_base = torch.Generator(device="cuda").manual_seed(seed) generator_refiner = torch.Generator(device="cuda").manual_seed(seed) # Call WandB Autolog for Diffusers. This would automatically log # the prompts, generated images, pipeline architecture and all # associated experiment configs to W&B, thus making your # image generation experiments easy to reproduce, share and analyze. autolog(init=dict(project="sdxl")) # Call the base pipeline to generate the latents image = base_pipeline( prompt=prompt, negative_prompt=negative_prompt, output_type="latent", generator=generator_base, ).images[0] # Call the refiner pipeline to generate the refined image image = refiner_pipeline( prompt=prompt, negative_prompt=negative_prompt, image=image[None, :], generator=generator_refiner, ).images[0] # Finish the experiment run.finish() ``` -------------------------------- ### Install and start Docker on EC2 Source: https://docs.wandb.ai/platform/launch/setup-launch-sagemaker Commands to update the system, install Docker, start the service, and add the current user to the docker group. ```bash sudo yum update -y && \ sudo yum install -y docker python3 && \ sudo systemctl start docker && \ sudo systemctl enable docker && \ sudo usermod -a -G docker ec2-user newgrp docker ``` -------------------------------- ### Install and start HiveMind daemon with install script (macOS/Linux) Source: https://docs.wandb.ai/hivemind Downloads and runs the HiveMind install script, then starts the daemon. On macOS, requires Apple Silicon; on Intel Macs use uv instead. On Apple Silicon Macs with Homebrew, installs the wandb-hivemind Homebrew cask; otherwise downloads a signed binary to ~/.local/bin. No sudo required. hivemind start handles terms of service, sign-in, and registers a background service (launchd on macOS, systemd on Linux). The daemon upgrades itself automatically. ```bash curl -fsSL https://hivemind.wandb.tools/install | sh hivemind start ``` -------------------------------- ### Install and start HiveMind daemon with uv (macOS/Linux) Source: https://docs.wandb.ai/hivemind Installs wandb-hivemind via uv and starts the daemon. uv automatically selects the correct binary for the OS; use this method on Intel Macs or Windows. hivemind start handles terms of service, sign-in, and registers a background service (launchd on macOS, systemd on Linux). Upgrade with uv tool upgrade wandb-hivemind. ```bash uv tool install wandb-hivemind hivemind start ``` -------------------------------- ### Install W&B and login in Jupyter Source: https://docs.wandb.ai/models/track/jupyter Install W&B and link your account in a Jupyter notebook. Run this at the start of your notebook. ```notebook !pip install wandb -qqq import wandb wandb.login() ``` -------------------------------- ### Setup Environment and Import CSV Data Source: https://docs.wandb.ai/weave/cookbooks/import_from_csv Installs required packages, imports libraries, writes sample CSV data to a file, and initializes the Weave client. ```python %pip install wandb weave pandas datetime --quiet python import os import pandas as pd import wandb from google.colab import userdata import weave ## Write samples file to disk with open("/content/import_cookbook_data.csv", "w") as f: f.write( "conversation_id,turn_index,start_time,user_input,ground_truth,answer_text\n" ) f.write( '1234,1,2024-09-04 13:05:39,This is the beginning, ["This was the beginning"], That was the beginning\n' ) f.write( "1235,1,2024-09-04 13:02:11,This is another trace,, That was another trace\n" ) f.write( "1235,2,2024-09-04 13:04:19,This is the next turn,, That was the next turn\n" ) f.write( "1236,1,2024-09-04 13:02:10,This is a 3 turn conversation,, Woah thats a lot of turns\n" ) f.write( '1236,2,2024-09-04 13:02:30,This is the second turn, ["That was definitely the second turn"], You are correct\n' ) f.write("1236,3,2024-09-04 13:02:53,This is the end,, Well good riddance!\n") os.environ["WANDB_API_KEY"] = userdata.get("WANDB_API_KEY") name_of_file = "/content/import_cookbook_data.csv" name_of_wandb_project = "import-weave-traces-cookbook" wandb.login() python weave_client = weave.init(name_of_wandb_project) ``` -------------------------------- ### ARIA response for setting up W&B Launch Source: https://docs.wandb.ai/aria/autoresearch Example ARIA response to the prompt "Can you help me set up W&B Launch?" It outlines choosing a compute backend (Kubernetes or Local Docker), creating a Launch queue in the W&B UI, and installing a Launch agent with Helm for Kubernetes. It warns against using a personal API key for the agent in a real setup. ```text ## 1. Decide where jobs will actually run Pick one: ### Option A β€” Kubernetes / cluster setup Use this if you want shared GPU/CPU infrastructure and a persistent Launch agent. Recommended for β€œreal” team usage. ### Option B β€” Local Docker setup Use this if you want jobs to run on your own machine, e.g. local workstation with Docker and possibly a GPU. Good for testing Launch quickly. I’d usually start with **Kubernetes** if you have cluster access. If not, start with **Local Docker**. ## 2. Create a Launch queue in the W&B UI Go to the Launch page for the entity: https://wandb.ai/wandb/launch Then: 1. Click **Create Queue**. 2. Select entity: `wandb`. 3. Give the queue a name. 4. Choose the queue resource type: - **Kubernetes** for cluster execution. - **Docker** for local execution. 5. Add the queue resource configuration. 6. Click **Create Queue**. ## 3. Kubernetes path: install a Launch agent with Helm If using Kubernetes, you need: - A Kubernetes cluster. - `kubectl` access to the cluster. - `helm` installed locally. - A W&B **service account API key**. - Permission to create/update/delete Kubernetes resources in the target namespace. Do **not** use your personal API key for the agent if this is a real setup. Use a W&B service account key. ``` -------------------------------- ### Stop local W&B server with wandb server stop Source: https://docs.wandb.ai/models/ref/cli/wandb-server/wandb-server-stop Stops the Docker container named 'wandb-local' that was started by 'wandb server start'. Requires Docker to be installed. The first block shows the command syntax, and the second block is a concrete example. ```bash stop [OPTIONS] ``` ```bash wandb server stop ``` -------------------------------- ### TypeScript OpenTelemetry setup and tracing example Source: https://docs.wandb.ai/weave/guides/tracking/otel TypeScript example that configures the OTLP exporter to send traces to Weave, sets up a NodeTracerProvider with resource attributes, and demonstrates creating a span with input/output attributes for an OpenAI call. Requires setting the WANDB_API_KEY environment variable and installing OpenTelemetry packages. ```typescript import OpenAI from "openai"; import { trace } from "@opentelemetry/api"; import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node"; import { BatchSpanProcessor, ConsoleSpanExporter } from "@opentelemetry/sdk-trace-base"; import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"; import { Resource } from "@opentelemetry/resources"; const OPENAI_API_KEY = "YOUR_OPENAI_API_KEY"; const WANDB_BASE_URL = "https://trace.wandb.ai"; const ENTITY = ""; const PROJECT = ""; const WEAVE_OTLP_ENDPOINT = `${WANDB_BASE_URL}/otel/v1/traces`; // Create an API key at https://wandb.ai/settings const WANDB_API_KEY = process.env.WANDB_API_KEY!; const exporter = new OTLPTraceExporter({ url: WEAVE_OTLP_ENDPOINT, headers: { "wandb-api-key": WANDB_API_KEY }, }); const provider = new NodeTracerProvider({ resource: new Resource({ "wandb.entity": ENTITY, "wandb.project": PROJECT, }), spanProcessors: [ new BatchSpanProcessor(exporter), // Optionally, print the spans to the console. new BatchSpanProcessor(new ConsoleSpanExporter()), ], }); provider.register(); // Creates a tracer from the global tracer provider const tracer = trace.getTracer("my-app"); async function myFunction() { const span = tracer.startSpan("outer_span"); try { const client = new OpenAI({ apiKey: OPENAI_API_KEY }); const inputMessages = [ { role: "user" as const, content: "Describe OTel in a single sentence." }, ]; // This will only appear in the side panel span.setAttribute("input.value", JSON.stringify(inputMessages)); // This follows conventions and will appear in the dashboard span.setAttribute("gen_ai.system", "openai"); const stream = await client.chat.completions.create({ model: "gpt-3.5-turbo", messages: inputMessages, max_tokens: 20, stream: true, }); let output = ""; for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content; if (content) { output += content; } } // This will only appear in the side panel span.setAttribute("output.value", JSON.stringify({ content: output })); } finally { span.end(); } } myFunction(); ``` ```bash npx ts-node opentelemetry_example.ts ``` -------------------------------- ### Start local preview server Source: https://docs.wandb.ai/weave/development Navigate to the directory containing docs.json and start the local preview server. ```bash mintlify dev ``` -------------------------------- ### Python OpenTelemetry setup and tracing example Source: https://docs.wandb.ai/weave/guides/tracking/otel Python example that configures the OTLP exporter to send traces to Weave, sets up a tracer provider with resource attributes, and demonstrates creating a span with input/output attributes for an OpenAI call. Requires setting environment variables for WANDB_API_KEY and installing OpenTelemetry packages. ```python OPENAI_API_KEY = "YOUR_OPENAI_API_KEY" WANDB_BASE_URL = "https://trace.wandb.ai" ENTITY = "" PROJECT = "" WEAVE_OTLP_ENDPOINT = f"{WANDB_BASE_URL}/otel/v1/traces" # Create an API key at https://wandb.ai/settings WANDB_API_KEY = os.environ["WANDB_API_KEY"] # Configure the OTLP exporter exporter = OTLPSpanExporter( endpoint=WEAVE_OTLP_ENDPOINT, headers={"wandb-api-key": WANDB_API_KEY}, ) tracer_provider = trace_sdk.TracerProvider(resource=Resource({ "wandb.entity": ENTITY, "wandb.project": PROJECT, })) tracer_provider.add_span_processor(BatchSpanProcessor(exporter)) # Optionally, print the spans to the console. tracer_provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter())) # Set the tracer provider trace.set_tracer_provider(tracer_provider) # Create a tracer from the global tracer provider tracer = trace.get_tracer(__name__) def my_function(): with tracer.start_as_current_span("outer_span") as outer_span: client = openai.OpenAI() input_messages = [{"role": "user", "content": "Describe OTel in a single sentence."}] outer_span.set_attribute("input.value", json.dumps(input_messages)) outer_span.set_attribute("gen_ai.system", "openai") response = client.chat.completions.create( model="gpt-3.5-turbo", messages=input_messages, max_tokens=20, stream=True, stream_options={"include_usage": True}, ) out = "" for chunk in response: if chunk.choices and (content := chunk.choices[0].delta.content): out += content outer_span.set_attribute("output.value", json.dumps({"content": out})) if __name__ == "__main__": my_function() ``` ```bash python opentelemetry_example.py ``` -------------------------------- ### wandb.setup(settings: 'Settings | None' = None) Source: https://docs.wandb.ai/models/ref/python/functions/setup Prepares W&B for use in the current process and its children. Can be called explicitly to improve performance when using wandb in multiple processes. Accepts optional global settings that can be overridden by subsequent wandb.init() calls. ```APIDOC ## wandb.setup(settings: 'Settings | None' = None) ### Description Prepares W&B for use in the current process and its children. You can usually ignore this as it is implicitly called by `wandb.init()`. When using wandb in multiple processes, calling `wandb.setup()` in the parent process before starting child processes may improve performance and resource utilization. Note that `wandb.setup()` modifies `os.environ`, and it is important that child processes inherit the modified environment variables. See also `wandb.teardown()`. ### Function Signature ```python def setup(settings: 'Settings | None' = None) -> None ``` ### Parameters - **settings** (Settings | None) - Optional - Configuration settings to apply globally. These can be overridden by subsequent `wandb.init()` calls. ### Returns None ### Examples ```python import multiprocessing import wandb def run_experiment(params): with wandb.init(config=params): # Run experiment pass if __name__ == "__main__": # Start backend and set global config wandb.setup(settings={"project": "my_project"}) # Define experiment parameters experiment_params = [ {"learning_rate": 0.01, "epochs": 10}, {"learning_rate": 0.001, "epochs": 20}, ] # Start multiple processes, each running a separate experiment processes = [] for params in experiment_params: p = multiprocessing.Process(target=run_experiment, args=(params,)) p.start() processes.append(p) # Wait for all processes to complete for p in processes: p.join() # Optional: Explicitly shut down the backend wandb.teardown() ``` ### Related Functions - `wandb.init()` - implicitly calls `wandb.setup()` - `wandb.teardown()` - explicitly shuts down the backend ``` -------------------------------- ### Start a conversation with agentName Source: https://docs.wandb.ai/weave/reference/typescript-sdk/functions/startconversation Example of starting a conversation with a custom agent name. ```typescript // @noErrors weave.startConversation({agentName: 'research-bot'}); ``` -------------------------------- ### Clone the W&B examples repository Source: https://docs.wandb.ai/models/sweeps/existing-project Download the example repository containing the training script and dataset. ```bash git clone https://github.com/wandb/examples.git ``` -------------------------------- ### Example script: fork a run and log metrics from step 200 Source: https://docs.wandb.ai/models/runs/forking This example script first initializes a run and logs metrics, then forks from that run at step 200 and continues logging metrics with a spikey pattern after step 250. Replace `` and `` with your own values. ```python import wandb import math # Initialize the first run and log some metrics with wandb.init( project="", entity="" ) as run1: for i in range(300): run1.log({"metric": i}) # Fork from the first run at a specific step and log the # metric starting from step 200 with wandb.init( project="", entity="", fork_from=f"{run1.id}?_step=200" ) as run2: # Continue logging in the new run # For the first few steps, log the metric as is from run1 # After step 250, start logging the spikey pattern for i in range(200, 300): if i < 250: # Continue logging from run1 without spikes metric_value = i else: # Introduce the spikey behavior starting from step 250 metric_value = i + (2 * math.sin(i / 3.0)) # Apply a subtle spikey pattern # Log both metrics in a single call to ensure they're # logged at the same step run2.log({ "metric": metric_value, "additional_metric": i * 1.1 }) ``` -------------------------------- ### Start SubAgent with name Source: https://docs.wandb.ai/weave/reference/typescript-sdk/functions/startsubagent Minimal example that starts a SubAgent span with only a name. ```ts weave.startSubagent({name: 'critic'}); ``` -------------------------------- ### Start SubAgent with options Source: https://docs.wandb.ai/weave/reference/typescript-sdk/functions/startsubagent Example that starts a SubAgent span with additional options: model, system instructions, and start time. ```ts weave.startSubagent({ name: 'critic', model: 'gpt-4o', systemInstructions: ['Critique the proposed plan.'], startTime: new Date('2026-05-29T10:00:00.000Z'), }); ``` -------------------------------- ### Configure audio streams and start main loop Source: https://docs.wandb.ai/weave/guides/integrations/openai-realtime-audio Sets up PyAudio input and output streams, handles device capabilities, and initializes the audio output queue for the real-time session. ```python # Open audio streams, start a Realtime session, and run the send/receive loop. async def main(*, input_device_index: int | None = None, output_device_index: int | None = None): p = pyaudio.PyAudio() if input_device_index is None: input_device_index = int(p.get_default_input_device_info()['index']) if output_device_index is None: output_device_index = int(p.get_default_output_device_info()['index']) # Clamp channel count to device capabilities to avoid pyaudio errors. input_info = p.get_device_info_by_index(input_device_index) output_info = p.get_device_info_by_index(output_device_index) input_channels = min(int(input_info['maxInputChannels']), MAX_INPUT_CHANNELS) output_channels = min(int(output_info['maxOutputChannels']), MAX_OUTPUT_CHANNELS) mic = p.open( format=FORMAT, channels=input_channels, rate=RATE, input=True, output=False, frames_per_buffer=CHUNK, input_device_index=input_device_index, start=False, ) speaker = p.open( format=FORMAT, channels=output_channels, rate=RATE, input=False, output=True, frames_per_buffer=CHUNK, output_device_index=output_device_index, start=False, ) mic.start_stream() speaker.start_stream() # Buffer audio through a queue so in-flight playback can be flushed on interrupt. audio_output_queue = queue.Queue() threading.Thread( target=play_audio, args=(speaker, audio_output_queue), daemon=True ).start() ``` -------------------------------- ### Start a conversation with full options Source: https://docs.wandb.ai/weave/reference/typescript-sdk/functions/startconversation Example of starting a conversation with agentName, conversationId, and custom attributes. ```typescript // @noErrors weave.startConversation({ agentName: 'research-bot', conversationId: '019efa53-8a65-711c-b4c1-7c1cb72c0bb7', attributes: {'myagent.version': '1.23'}, }); ``` -------------------------------- ### Install, log in, and run a command in a Serverless Sandbox Source: https://docs.wandb.ai/sandboxes Install the W&B Python SDK with serverless sandbox dependencies, log in to W&B with the CLI, then create a sandbox, run a command inside it, and print the output. The sandbox automatically stops when the context manager exits. ```bash pip install wandb[sandbox] ``` ```bash wandb login ``` ```python from wandb.sandbox import Sandbox with Sandbox.run() as sandbox: process = sandbox.exec(["echo", "Hello from Serverless Sandboxes!"]).result() print(process.stdout) ``` -------------------------------- ### Basic startLLM example Source: https://docs.wandb.ai/weave/reference/typescript-sdk/functions/startllm Starts an LLM span with a model and provider name. This is the minimal usage example. ```typescript // @noErrors weave.startLLM({model: 'gpt-4o-mini', providerName: 'openai'}); ``` -------------------------------- ### Initialize and Log with Accelerate Source: https://docs.wandb.ai/models/integrations/accelerate Configure the Accelerator to use W&B, initialize trackers with project settings, log metrics, and end the training session. ```python from accelerate import Accelerator # Tell the Accelerator object to log with wandb accelerator = Accelerator(log_with="wandb") # Initialise your wandb run, passing wandb parameters and any config information accelerator.init_trackers( project_name="my_project", config={"dropout": 0.1, "learning_rate": 1e-2}, init_kwargs={"wandb": {"entity": "my-wandb-team"}} ) ... # Log to wandb by calling accelerator.log(); step is optional accelerator.log({"train_loss": 1.12, "valid_loss": 0.8}, step=global_step) # Make sure that the wandb tracker finishes correctly accelerator.end_training() ``` -------------------------------- ### Log in to W&B with example domain Source: https://docs.wandb.ai/platform/hosting/self-managed/operator Example login command using a sample domain. ```bash wandb login --host=https://wandb.company-name.com ``` -------------------------------- ### Customized Keeper Installation Name Hostnames Source: https://docs.wandb.ai/weave/guides/platform/weave-self-managed Example of Keeper hostnames when the installation name is customized to 'myweave'. ```text chk-myweave-keeper-0-0.clickhouse.svc.cluster.local chk-myweave-keeper-0-1.clickhouse.svc.cluster.local chk-myweave-keeper-0-2.clickhouse.svc.cluster.local ``` -------------------------------- ### Get reports for a project Source: https://docs.wandb.ai/models/ref/python/public-api/api Example of getting reports for a project path. Calls Api.reports with the path 'entity/project'. ```python import wandb wandb.Api.reports("entity/project") ``` -------------------------------- ### Navigate to the example directory Source: https://docs.wandb.ai/models/sweeps/existing-project Change the working directory to the location of the PyTorch CNN Fashion example. ```bash cd examples/pytorch/pytorch-cnn-fashion ``` -------------------------------- ### Usage: start [OPTIONS] Source: https://docs.wandb.ai/models/ref/cli/wandb-beta/wandb-beta-core/wandb-beta-core-start Shows the command-line usage for `wandb beta core start`. The command starts a detached wandb-core service. ```bash start [OPTIONS] ``` -------------------------------- ### Set up environment: install packages, login, and initialize Weave Source: https://docs.wandb.ai/weave/cookbooks/custom_model_cost Install required packages, set WANDB_API_KEY, log in with wandb.login(), and initialize a Weave client with weave.init(). The project name can be in the format {team_name}/{project_name}. ```python %pip install wandb weave datetime --quiet python import os import wandb from google.colab import userdata import weave os.environ["WANDB_API_KEY"] = userdata.get("WANDB_API_KEY") name_of_wandb_project = "custom-cost-model" wandb.login() python weave_client = weave.init(name_of_wandb_project) ``` -------------------------------- ### Extended startLLM example with system instructions and start time Source: https://docs.wandb.ai/weave/reference/typescript-sdk/functions/startllm Starts an LLM span with additional options including system instructions and a custom start time. ```typescript // @noErrors weave.startLLM({ model: 'gpt-4o-mini', providerName: 'openai', systemInstructions: ['You are a helpful weather bot.'], startTime: new Date('2026-05-29T10:00:00.000Z'), }); ``` -------------------------------- ### Install W&B and run YOLOv5 training Source: https://docs.wandb.ai/models/integrations/yolov5 Install the W&B Python SDK and clone the YOLOv5 repository, then run training as usual. After running, follow the links W&B prints to standard out to view the experiment dashboard. ```bash pip install wandb git clone https://github.com/ultralytics/yolov5.git python yolov5/train.py # train a small network on a small dataset ``` -------------------------------- ### Spawn process with wandb.setup() Source: https://docs.wandb.ai/models/track/log/distributed-training Use wandb.setup() in the main function when initiating a run within a spawned process. ```python import multiprocessing as mp def do_work(n): with wandb.init(config=dict(n=n)) as run: run.log(dict(this=n * n)) def main(): wandb.setup() pool = mp.Pool(processes=4) pool.map(do_work, range(4)) if __name__ == "__main__": main() ``` -------------------------------- ### Start a conversation with startConversation (basic) Source: https://docs.wandb.ai/weave/reference/typescript-sdk/variables/startsession Starts a new conversation with an agent name. This is the replacement for the deprecated startSession. The example uses the weave.startConversation method. ```TypeScript weave.startConversation({agentName: 'research-bot'}); ``` -------------------------------- ### Create a team and add a service account Source: https://docs.wandb.ai/models/ref/python/public-api/team Example showing how to create a new team and provision a service account for it. ```python import wandb api = wandb.Api() team = api.create_team("my-team") team.create_service_account("CI service account") ``` -------------------------------- ### Launch a W&B project with launch() Source: https://docs.wandb.ai/platform/launch/launch-library/launch Demonstrates how to launch a W&B job with specific parameters using the launch function. This example creates a reproducible docker environment on a local host. ```python from wandb.sdk.launch import launch job = "wandb/jobs/Hello World:latest" params = {"epochs": 5} # Run W&B project and create a reproducible docker environment # on a local host api = wandb.apis.internal.Api() launch(api, job, parameters=params) ``` -------------------------------- ### Authenticate and Initialize a W&B Run Source: https://docs.wandb.ai/models/ref/python/functions This example demonstrates the standard workflow of authenticating with W&B, initializing a run with configuration parameters, and logging metrics during a training loop. ```python import wandb # Authenticate with W&B wandb.login() # Hyperparameters and metadata config = { "learning_rate": 0.01, "epochs": 10, } # Project that the run is recorded to project = "my-awesome-project" # Initialize a new run with wandb.init(project=project, config=config) as run: # Your training code here... # Log values to W&B run.log({"accuracy": 0.9, "loss": 0.1}) ``` -------------------------------- ### Get the starting time for a run Source: https://docs.wandb.ai/models/track/public-api-guide This code snippet retrieves the time at which the run was created. ```python import wandb api = wandb.Api() run = api.run("entity/project/run_id") start_time = run.created_at ``` -------------------------------- ### Install Verifiers from source Source: https://docs.wandb.ai/weave/guides/integrations/verifiers Install the Verifiers library from source. Clones the repository, enters the directory, and installs all extras plus flash-attn without build isolation. ```bash git clone https://github.com/willccbb/verifiers cd verifiers uv sync --all-extras && uv pip install flash-attn --no-build-isolation ``` -------------------------------- ### startSession Source: https://docs.wandb.ai/weave/reference/typescript-sdk/variables/startsession Starts a new Conversation and installs it as the current conversation. Deprecated, use startConversation instead. ```APIDOC ## startSession ### Description Starts a new Conversation and installs it as the current conversation. Subsequent calls to startTurn will pick it up automatically. Pass attributes to propagate custom (non-semconv) attributes to every span the conversation emits. Deprecated: Use startConversation instead. ### Signature `const startSession: (opts) => Conversation` ### Parameters - **opts** (ConversationInit = {}) - Optional - See ConversationInit. ### Returns - **Conversation** - The newly started conversation. ### Examples ```ts weave.startConversation({agentName: 'research-bot'}); ``` ```ts weave.startConversation({ agentName: 'research-bot', conversationId: '019efa53-8a65-711c-b4c1-7c1cb72c0bb7', attributes: {'myagent.version': '1.23'}, }); ``` ```