Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

Azure AI Fine-Tuning Sessions client library for Python

Preview client library for Programmed Training in Microsoft Foundry, supporting interactive supervised and reinforcement fine-tuning through fine-tuning sessions. Create sessions, submit training and sampling requests, and save checkpoints with synchronous or asynchronous Python clients.

For general background, see the Microsoft Foundry fine-tuning overview. Availability of fine-tuning sessions and individual features depends on your account, region, model, and service configuration.

Getting started

Install the package

python -m pip install --pre azure-ai-finetuningsessions
python -m pip install azure-identity

Prerequisites

  • Python 3.10 or later.
  • An Azure subscription.
  • A Foundry project with access to fine-tuning sessions and compatible capacity.
  • The project endpoint supplied for the service, for example https://<account>.services.ai.azure.com/api/projects/<project>.

Preview access does not grant approval for restricted operations. This guide covers service-side checkpoint saves, metadata inspection, and resume; additional allowlisted operations require separate explicit service approval.

Authenticate and create a session

Use an Azure Identity credential such as DefaultAzureCredential. Session creation requires an explicit LoRA configuration and adapter rank. Use a base model and configuration supported by your account.

from azure.ai.finetuningsessions import FineTuningSession, FineTuningSessionClient
from azure.ai.finetuningsessions.models import LoRAConfig
from azure.identity import DefaultAzureCredential

endpoint = "https://<account>.services.ai.azure.com/api/projects/<project>"

with DefaultAzureCredential() as credential:
    with FineTuningSessionClient(endpoint=endpoint, credential=credential) as client:
        session = FineTuningSession.create(
            client,
            base_model="<supported-base-model>",
            lora_config=LoRAConfig(rank=16),
            user_metadata={"experiment": "example"},
        )
        try:
            checkpoint = session.save_weights_for_sampler(
                sampling_session_seq_id=0,
                seq_id=0,
            )
            print(checkpoint.checkpoint_id)
        finally:
            session.close()

AzureKeyCredential is also supported when API-key authentication is enabled for the endpoint. Use HTTPS. Default API-key authentication sends credentials only to the configured origin. For local testing, allow_insecure_http=True allows HTTP only for the configured loopback endpoint; it does not permit remote plaintext authentication.

Key concepts

  • A session holds model and adapter state between requests.
  • A request is submitted and observed until its result is available. Successful submission does not mean the requested work has completed.
  • A checkpoint saves training state or sampler weights. Sampling requires a completed sampler checkpoint identifier.
  • A heartbeat refreshes an active session during gaps between requests. Convenience creation starts background heartbeats automatically.

training_type accepts TrainingType members or strings. Known values are GlobalStandard, DatazoneStandard, and DeveloperTier. If omitted, the SDK sends no tier and the service selects the default. Explicit choices remain subject to service eligibility and capacity; the SDK does not select a different tier when the requested one is unavailable.

Examples

Client and session lifetime

FineTuningSession.create(...) waits for initialization and returns a session wrapper. Its background heartbeat uses a thread. Calling session.close() stops that heartbeat and requests session unload. Closing the HTTP client alone does not unload the session or stop a synchronous wrapper's heartbeat.

The asynchronous client returns a session ID from await client.create_session(...). Its methods accept that ID:

from azure.ai.finetuningsessions.aio import FineTuningSessionClient
from azure.ai.finetuningsessions.models import LoRAConfig
from azure.identity.aio import DefaultAzureCredential

async def run():
    async with DefaultAzureCredential() as credential:
        async with FineTuningSessionClient(
            endpoint="https://<account>.services.ai.azure.com/api/projects/<project>",
            credential=credential,
        ) as client:
            session_id = await client.create_session(
                base_model="<supported-base-model>",
                lora_config=LoRAConfig(rank=16),
            )
            try:
                checkpoint_task = await client.save_weights_for_sampler_async(
                    session_id,
                    name="example-sampler",
                )
                checkpoint = await checkpoint_task
                print(checkpoint.checkpoint_id)
            finally:
                await client.close_session(session_id)

Closing the async client drains its completion observers and heartbeat tasks and closes the transport, but does not unload or delete remote sessions. Use close_session explicitly. Keep the event loop responsive so background heartbeats can run.

The async save_weights_for_sampler_async method returns a task after submission. Await both the method and its returned task before using the checkpoint, as shown above.

session.delete() and await async_client.delete_session(session_id) stop the associated heartbeat and request deletion of the session and its resources. They treat an already absent session as successfully deleted. Deletion differs from unloading and does not wait for background storage cleanup.

Async connection pool sizing

The async client keeps Azure Core's default transport settings unless you pass connection_pool_limit=<positive integer> to its constructor. This sizes the default connection pool when it is opened; it does not change sampling or submission concurrency limits and does not guarantee a throughput improvement. The default async transport requires aiohttp; install it with python -m pip install aiohttp if it is not already available.

Boolean, non-integer, and non-positive limits are rejected. The option cannot be combined with a supplied transport, pipeline, or session. Without it, caller-supplied settings and ownership remain unchanged. Synchronous clients reject this async-only option.

Attach an existing session

For synchronous use, FineTuningSession(client, session_id) wraps an existing session and starts its heartbeat. Repeated wrappers own separate heartbeat threads, so manage their lifetimes explicitly.

For asynchronous use, call await async_client.attach_session(session_id). It registers one best-effort heartbeat per client/session and returns None. The first heartbeat is sent after 30 seconds; registration itself makes no HTTP request and does not verify existence, readiness, or access. Client close stops these tasks without unloading the remote session.

Training and sampling

Use the convenience methods for complete workflows:

Operation Synchronous API Asynchronous API
Forward/backward session.forward_backward(batch) await client.forward_backward(session_id, batch)
Forward only session.forward(batch) await client.forward(session_id, batch)
Optimizer step session.optim_step(adam_params) await client.optim_step(session_id, adam_params)
Save training state session.save_weights(path) await client.save_weights(session_id, path)
Sample session.sample(...) await client.sample(session_id, ...)

Forward-only passes do not accumulate gradients. Training and sampling helpers submit work, retrieve completed results, normalize them, and apply their documented batching and error-handling behavior.

ModelInput accepts ordered text and image chunks. ModelInputChunk(tokens=...) represents token IDs; ImageChunk accepts validated JPEG, PNG, or WebP data. Image validation checks the 10,000,000-byte limit, matching content and format, positive expected_tokens, and at most 64 images per example. Legacy token-only mappings remain accepted; unknown explicit chunk tags are not reclassified. Support for any particular chunk variant still depends on the service.

Set AZURE_AI_FINETUNING_MAX_CHUNK_BYTES before importing the SDK to override the approximate per-request chunk-size budget. Unset or invalid values retain the 5,000,000-byte default; invalid values log a warning. This does not change the service's request limits.

SamplingParams.response_format requests a response format from compatible models and providers. SamplingOperationResult is an alias for SampleOperationResult. Its read-only prompt_tokens reports the service's prompt count once per prompt, not once per sampled sequence. Missing or invalid counts remain None; the SDK does not estimate them from other data.

Experimental native losses

LossFn.TIS selects sum-reduced token-level truncated importance sampling. Its clip_high_threshold must be finite and at least 1; the service defaults to 2 when it is omitted. TIS is also accepted as "tis" for reference-based text-only training. Selecting it emits an experimental warning.

Native LossFn.SCORE_CENTERING and sampling head capture require an explicit client opt-in. Import ExperimentalSettings from azure.ai.finetuningsessions.experimental and pass experimental_settings=ExperimentalSettings(enable_score_centering=True) to either client constructor. This also emits an experimental warning when used; constructing the client alone does not warn.

SamplingParams.score_centering_head_size accepts 0 to disable capture or 1 through 128 to request decode-time top-K heads. Capture requires temperature=1, top_p=1, top_k=-1, and no response_format; it is not supported with text-only input. Native training accepts corresponding head tokens, log-probabilities and masks in LossFnInputs. TensorData.shape preserves multidimensional shapes while values remain flat on the wire. Returned SampledSequence objects preserve head data and capture provenance.

These features are under development and require compatible service support. The SDK opt-in does not enable service capabilities, grant authorization, or guarantee deployment availability. Existing losses are unchanged.

Completion-feed sampling

Synchronous and asynchronous convenience session creation advertise completion-feed support. Sampling uses server-sent events (SSE) only when the service negotiates the exact enablement value true. Missing or other values, older services, and attached sessions without that negotiation retain legacy polling. Raw operations, training, and session initialization keep their existing polling behavior.

session.sample() remains blocking, and await async_client.sample(...) returns the same result models as before. Notifications trigger retrieval of the persisted result or error; they are not generated tokens or final results. Stream reconnects preserve progress without resubmitting sampling. A persisted failure triggers resubmission only when the service authorizes it. Ordinary submission retries are unchanged and do not guarantee deduplication if a reply is lost. Typed sampling errors that include a session ID report the canonical session_ ID, even when requests use a different resource ID.

Short socket timeouts in the synchronous observer apply only to completion streams and acknowledgements. Sample submission and result retrieval use their normal request timeouts. Missed notifications are recovered by checking for a result after 10 minutes, then 5 minutes after each pending response. Feed outages keep that sparse schedule rather than switching to frequent polling. Existing heartbeats continue independently.

When sampling becomes idle, an open stream can finish its current bounded window and be reused by new sampling in that window. Client close stops observation and drains owned tasks before closing the transport. If a synchronous close times out waiting for observation or its workers, it reports that shutdown is still in progress. Cleanup continues on the observer thread after outstanding requests finish, and repeated calls wait for the same cleanup. Caller-owned transport resources and credentials must remain available until cleanup finishes. A synchronous observation cleanup error does not replace an exception already raised in the client's with block. The close timeout cannot stop blocking I/O or guarantee that Python exits by a deadline. Canceling a local sampling call or closing the client does not cancel service-side inference or unload the session.

Use one logical consuming client per session. Observation progress is held in client memory; cross-process acknowledgement sharing and restoration after process restart are not supported. INFO progress updates count cumulative final sampling-call outcomes for each session on that client, not notifications or intermediate retries. Totals survive reconnects and idle periods and start fresh with a new client.

Opt-in text-only operations

Sampling and training convenience methods accept text_only_input instead of token-native inputs. Sampling accepts public system, user, assistant, and tool messages and optional function definitions. Only function tools are supported. Training accepts opaque sample_ref values and finite scalar advantages without exposing underlying token evidence.

Text-only sampling results contain valid assistant choices or safely classified invalid choices. Invalid choices have no public message but can still have trainable references; they are not automatically operation failures. Keep references opaque and use the exact returned value for subsequent training. Reference training exposes scalar metrics rather than private per-token output.

For compatible models, reasoning_effort accepts "low", "medium", "high", or None. Omission or None preserves the model default. Unsupported values are rejected before submission. Text-only sampling does not support prompt log-probabilities, caller-selected stopping criteria, or response_format. Installing the SDK does not enable these capabilities or grant model access.

Checkpoint status and publication

Checkpoint listings can include pending or failed save reservations as well as completed checkpoints. checkpoint.time is a datetime or None; handle None before formatting, comparing, or sorting timestamps. status describes the save, not approval for deployment.

publication contains typed CheckpointPublicationState metadata. publication_required and deployment_eligible describe separate deployment requirements. Metadata omitted by older services remains None and must not be treated as deployment approval.

Raw operations and convenience methods

The raw operation groups provide lower-level access with explicit request models and per-call API versions. Generated requests use canonical /fine_tuning_sessions routes. Some maintained convenience paths retain compatibility routes using /fine_tuning/sessions; use a service endpoint that supports the operations you call rather than manually rewriting URLs.

Raw create methods return submission results without waiting for initialization. Default raw begin_* methods return pollers that accept HTTP 200 submissions and poll the returned request ID. They do not start a heartbeat. Use poller.result() or await poller.result() to obtain completion. Explicit custom polling or polling=False retains the chosen strategy's semantics; disabling polling does not confirm that work completed.

Raw client.training.forward and client.sessions.delete methods are not provided in this preview. Use their session/convenience equivalents.

Troubleshooting

Training engine interruptions

TrainingEngineError (also available as EngineDeadError) with code engine_dead or worker_crashed indicates a terminal interruption. Resume in a new session from the latest completed training checkpoint using FineTuningSession.create_from_checkpoint(...) or await async_client.create_session_from_checkpoint(...).

Keep the source base model and LoRA configuration. Restore the dataset cursor and client-side learning-rate schedule separately; the SDK does not restore them. Progress after the checkpoint is not recovered. Without a completed training checkpoint, restart from the base model.

Do not resubmit training on the interrupted session. Terminal interruption errors remain terminal even if a response includes a retry hint. session.close() and await async_client.close_session(session_id) also preserve known typed service errors and the canonical session ID. An engine_dead HTTP 409 raises TrainingEngineError; it does not confirm unload. Unrecognized conflicts and malformed error bodies remain HTTP errors rather than being inferred as engine death. engine_oom and engine_timeout do not by themselves mean the trainer is terminally interrupted; follow the error's guidance, such as reducing batch size or sequence length for an out-of-memory error.

Transport, retries, and logging

Default transport policies do not retry POST requests, including heartbeats. Convenience operations have separate bounded recovery for supported service responses. An explicit retry_policy remains caller-owned; the SDK does not guarantee deduplication or exactly-once execution. Default raw pollers disable transport retries and redirects for their own submission and polling requests.

Default API-key authentication is removed on cross-origin redirects. Callers supplying custom policies or pipelines are responsible for their authentication, retry, and redirect configuration.

Normal INFO logs contain progress and identifiers rather than complete request or response bodies. FINETUNING_VERBOSE_HTTP=1 enables body logging; do not enable it for sensitive data. Avoid logging credentials, training inputs, generated messages, or checkpoint contents.

Compatibility and migration

The distribution is azure-ai-finetuningsessions and imports use azure.ai.finetuningsessions, including its aio namespace. If an older azure-ai-finetuning-sessions distribution is installed, uninstall it before installing this package and update dependency/import declarations.

Creation and checkpoint-resume calls require lora_config=LoRAConfig(rank=...). No implicit rank or empty LoRA configuration is supplied.

The obsolete FoundryFeaturesOptInKeys.AGENT_INSIGHTS_V1_PREVIEW constant is removed in b2 because Agent Insights no longer requires that preview opt-in. Explicit references must be removed. Fine-tuning continues using the unchanged Foundry-Features: FineTuningSessions=V1Preview value.

Next steps

Review the Microsoft Foundry fine-tuning overview for service guidance. For questions or bug reports, use the Azure SDK for Python issue tracker.

Contributing

See the Azure SDK for Python contribution guide and Microsoft Open Source Code of Conduct.

Release History

1.0.0b3 (2026-12-01)

Features Added

  • Add capability-negotiated completion-feed observation for synchronous and asynchronous convenience sampling. Notifications trigger authoritative result retrieval; services and sessions without exact enablement retain legacy polling.
  • Add the async-only connection_pool_limit client option to size the default connection pool without changing sampling concurrency or caller-supplied transports.
  • Expose checkpoint save status, typed CheckpointPublicationState, publication requirements, and deployment eligibility when returned by the service.
  • Add experimental native TIS loss, including reference-based text-only training, with an experimental warning when selected.
  • Add explicitly opted-in native score centering, decode-time sampling head capture, multidimensional tensor shapes, and head/provenance metadata. These require compatible service support and do not enable service capabilities.

Breaking Changes

  • Checkpoint.time can be None for pending or failed checkpoint saves. Handle missing completion timestamps before formatting, comparing, or sorting checkpoints. Completed saves retain their timestamps.

Bugs Fixed

  • Preserve completion-feed cursor progress across reconnects, honor bounded server retry hints, and recover missed notifications through sparse result retrieval.
  • Drain completion observers during client shutdown and let idle streams finish their bounded window so newly submitted sampling work can reuse the stream.
  • Preserve normal synchronous sampling submission and result timeouts when completion feeds are enabled. If a close call times out, finish the shared cleanup after the workers drain.
  • Report the canonical session ID on sampling submission and result errors without changing request routing or retry behavior.
  • Report cumulative final sampling-call totals per client/session across reconnects and idle periods, rather than resetting counts or counting notifications and retry attempts.
  • Preserve typed terminal errors and canonical session identifiers when session close fails, including engine_dead and worker_crashed HTTP 409 responses. Conflicting, malformed, or nonterminal codes and generic busy/deadline messages remain HTTP errors rather than being inferred as engine death.

Other Changes

  • Refresh generation source references and archived tooling to match the current shared SDK toolchain without changing generated APIs or runtime behavior.

1.0.0b2 (2026-11-12)

Features Added

  • Add opt-in text-only sampling with public conversation messages and function tools, plus reference-based training using opaque sample references and scalar advantages.
  • Support optional model-specific text-only reasoning_effort values low, medium, and high. Omission or None preserves the model default.
  • Add async FineTuningSessionClient.attach_session(session_id) to start a heartbeat for an existing session without creating or loading it.
  • Add synchronous and asynchronous local checkpoint downloads. These prepare the export, validate the complete inventory, and stream files into an empty or absent destination with exact ETag and byte-count checks. Failures retain partial output without automatic resume, deletion, or overwrite; model eligibility and authorization remain enforced by the service.

Breaking Changes

  • Remove FoundryFeaturesOptInKeys.AGENT_INSIGHTS_V1_PREVIEW because Agent Insights no longer requires the obsolete preview opt-in. Remove explicit references to that constant. The fine-tuning preview header is unchanged.

Bugs Fixed

  • Provide actionable checkpoint-resume guidance for terminal training-engine interruptions while preserving error codes and diagnostic identifiers.
  • Preserve out-of-memory and timeout guidance for nonterminal engine errors.
  • Retry sampling responses missing request_id within a bounded fault budget, then raise MalformedResponseError.
  • Improve polling budgets, sampling limits, heartbeat shutdown, and scalar serialization while preserving protected-training replay safeguards.
  • Use canonical /fine_tuning_sessions routes in generated operations while retaining existing Python convenience APIs.
  • Preserve POSIX ownership across checkpoint directory creation and opening using protected staging and atomic no-replace publication. Reject unsupported staging explicitly and retain partial output without adopting or overwriting concurrent directories.

Other Changes

  • Clarify session lifecycle, service-selected training tiers, checkpoint preparation limits, and differences between raw operations and convenience methods.
  • Improve generated request-model documentation without changing supported message roles, function-only tools, or request payloads.
  • Restore the standard README sections and include public test sources in source distributions while keeping archived review material excluded.
  • Synchronize generation metadata with the updated public TypeSpec source without changing the Python API or runtime.

1.0.0b1 (2026-09-24)

Features Added

  • Initial preview of interactive fine-tuning sessions with synchronous and asynchronous Python clients.
  • Support forward/backward training, forward-only requests, sampling, optimizer steps, checkpoint save/resume, session unload and deletion.
  • Support text/image input chunks, vision/projector LoRA configuration, JSON-valued session metadata, and training-tier selection.
  • Add optional structured sampling responses, prompt log-probabilities, and read-only prompt-token counts when reported by the service.
  • Add SamplingOperationResult as an alias for SampleOperationResult.
  • Support the import-time AZURE_AI_FINETUNING_MAX_CHUNK_BYTES override for the approximate request chunk-size budget.

Breaking Changes

  • Require Python 3.10 or later.
  • Use distribution name azure-ai-finetuningsessions and import namespace azure.ai.finetuningsessions. Uninstall the older azure-ai-finetuning-sessions distribution before migrating.
  • Require explicit LoRA configuration, including LoRAConfig.rank, for session creation and checkpoint resume.
  • Remove the obsolete AGENTS_OPTIMIZATION_V2_PREVIEW feature constant.

Bugs Fixed

  • Scope default credentials and request-context headers to the configured endpoint and preserve credential protections during redirects.
  • Disable automatic POST transport retries by default and support HTTP 200 request-ID polling in raw begin_* operations.
  • Drain async heartbeat tasks during shutdown and bound synchronous heartbeat cleanup.
  • Validate empty batches, sampler identifiers, image content, malformed error responses, and retry hints before accepting results or replaying operations.

Metadata

Release files for azure-ai-finetuningsessions 1.0.0b3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for azure-ai-finetuningsessions 1.0.0b3
File Size Uploaded Provenance Actions
azure_ai_finetuningsessions-1.0.0b3.tar.gz 349.1 kB Without provenance Details for azure_ai_finetuningsessions-1.0.0b3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for azure-ai-finetuningsessions 1.0.0b3
File Interpreter ABI Platform Actions
azure_ai_finetuningsessions-1.0.0b3-py3-none-any.whl Python 3 none any Details for azure_ai_finetuningsessions-1.0.0b3-py3-none-any.whl

Total release size: 550.5 kB

Release files / azure_ai_finetuningsessions-1.0.0b3.tar.gz

Download URL azure_ai_finetuningsessions-1.0.0b3.tar.gz
Size 349.1 kB
Tags Source
SHA-256 checksum
How to use checksums
e7b9b46b8e84c44cd1066626a4bb2284e39e28665cd886f7373788d78cc312a6
BLAKE2b-256 checksum
How to use checksums
4768a595377dfba5dd8cf55decadbef919b93db49e3d8181fe75a8c3b77dd2e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0

Release files / azure_ai_finetuningsessions-1.0.0b3-py3-none-any.whl

Download URL azure_ai_finetuningsessions-1.0.0b3-py3-none-any.whl
Size 201.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
78de1774f8bba42d3acaf17110ab8c83d56f61be378d616c8b108ea57759fb33
BLAKE2b-256 checksum
How to use checksums
c073cdb6e6dfb46998b45e6493a0cbff66fb57a785f8e326d7757e0aa74c348b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via RestSharp/106.13.0.0

Security for azure-ai-finetuningsessions 1.0.0b3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page