|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +from typing import Any, ClassVar |
| 4 | + |
| 5 | +from agent_framework import use_chat_middleware, use_function_invocation |
| 6 | +from agent_framework._pydantic import AFBaseSettings |
| 7 | +from agent_framework.exceptions import ServiceInitializationError |
| 8 | +from agent_framework.observability import use_instrumentation |
| 9 | +from agent_framework.openai._chat_client import OpenAIBaseChatClient |
| 10 | +from foundry_local import FoundryLocalManager |
| 11 | +from foundry_local.models import DeviceType |
| 12 | +from openai import AsyncOpenAI |
| 13 | + |
| 14 | +__all__ = [ |
| 15 | + "FoundryLocalClient", |
| 16 | +] |
| 17 | + |
| 18 | + |
| 19 | +class FoundryLocalSettings(AFBaseSettings): |
| 20 | + """Foundry local model settings. |
| 21 | +
|
| 22 | + The settings are first loaded from environment variables with the prefix 'FOUNDRY_LOCAL_'. |
| 23 | + If the environment variables are not found, the settings can be loaded from a .env file |
| 24 | + with the encoding 'utf-8'. If the settings are not found in the .env file, the settings |
| 25 | + are ignored; however, validation will fail alerting that the settings are missing. |
| 26 | +
|
| 27 | + Attributes: |
| 28 | + model_id: The name of the model deployment to use. |
| 29 | + (Env var FOUNDRY_LOCAL_MODEL_ID) |
| 30 | + Parameters: |
| 31 | + env_file_path: If provided, the .env settings are read from this file path location. |
| 32 | + env_file_encoding: The encoding of the .env file, defaults to 'utf-8'. |
| 33 | + """ |
| 34 | + |
| 35 | + env_prefix: ClassVar[str] = "FOUNDRY_LOCAL_" |
| 36 | + |
| 37 | + model_id: str |
| 38 | + |
| 39 | + |
| 40 | +@use_function_invocation |
| 41 | +@use_instrumentation |
| 42 | +@use_chat_middleware |
| 43 | +class FoundryLocalClient(OpenAIBaseChatClient): |
| 44 | + """Foundry Local Chat completion class.""" |
| 45 | + |
| 46 | + def __init__( |
| 47 | + self, |
| 48 | + model_id: str | None = None, |
| 49 | + *, |
| 50 | + bootstrap: bool = True, |
| 51 | + timeout: float | None = None, |
| 52 | + prepare_model: bool = True, |
| 53 | + device: DeviceType | None = None, |
| 54 | + env_file_path: str | None = None, |
| 55 | + env_file_encoding: str = "utf-8", |
| 56 | + **kwargs: Any, |
| 57 | + ) -> None: |
| 58 | + """Initialize a FoundryLocalClient. |
| 59 | +
|
| 60 | + Keyword Args: |
| 61 | + model_id: The Foundry Local model ID or alias to use. If not provided, |
| 62 | + it will be loaded from the FoundryLocalSettings. |
| 63 | + bootstrap: Whether to start the Foundry Local service if not already running. |
| 64 | + Default is True. |
| 65 | + timeout: Optional timeout for requests to Foundry Local. |
| 66 | + This timeout is applied to any call to the Foundry Local service. |
| 67 | + prepare_model: Whether to download the model into the cache, and load the model into |
| 68 | + the inferencing service upon initialization. Default is True. |
| 69 | + If false, the first call to generate a completion will load the model, |
| 70 | + and might take a long time. |
| 71 | + device: The device type to use for model inference. |
| 72 | + The device is used to select the appropriate model variant. |
| 73 | + If not provided, the default device for your system will be used. |
| 74 | + The values are in the foundry_local.models.DeviceType enum. |
| 75 | + env_file_path: If provided, the .env settings are read from this file path location. |
| 76 | + env_file_encoding: The encoding of the .env file, defaults to 'utf-8'. |
| 77 | + kwargs: Additional keyword arguments, are passed to the OpenAIBaseChatClient. |
| 78 | + This can include middleware and additional properties. |
| 79 | +
|
| 80 | + Examples: |
| 81 | +
|
| 82 | + .. code-block:: python |
| 83 | +
|
| 84 | + # Create a FoundryLocalClient with a specific model ID: |
| 85 | + from agent_framework_foundry_local import FoundryLocalClient |
| 86 | +
|
| 87 | + client = FoundryLocalClient(model_id="phi-4-mini") |
| 88 | +
|
| 89 | + agent = client.create_agent( |
| 90 | + name="LocalAgent", |
| 91 | + instructions="You are a helpful agent.", |
| 92 | + tools=get_weather, |
| 93 | + ) |
| 94 | + response = await agent.run("What's the weather like in Seattle?") |
| 95 | +
|
| 96 | + # Or you can set the model id in the environment: |
| 97 | + os.environ["FOUNDRY_LOCAL_MODEL_ID"] = "phi-4-mini" |
| 98 | + client = FoundryLocalClient() |
| 99 | +
|
| 100 | + # A FoundryLocalManager is created and if set, the service is started. |
| 101 | + # The FoundryLocalManager is available via the `manager` property. |
| 102 | + # For instance to find out which models are available: |
| 103 | + for model in client.manager.list_catalog_models(): |
| 104 | + print(f"- {model.alias} for {model.task} - id={model.id}") |
| 105 | +
|
| 106 | + # Other options include specifying the device type: |
| 107 | + from foundry_local.models import DeviceType |
| 108 | +
|
| 109 | + client = FoundryLocalClient( |
| 110 | + model_id="phi-4-mini", |
| 111 | + device=DeviceType.GPU, |
| 112 | + ) |
| 113 | + # and choosing if the model should be prepared on initialization: |
| 114 | + client = FoundryLocalClient( |
| 115 | + model_id="phi-4-mini", |
| 116 | + prepare_model=False, |
| 117 | + ) |
| 118 | + # Beware, in this case the first request to generate a completion |
| 119 | + # will take a long time as the model is loaded then. |
| 120 | + # Alternatively, you could call the `download_model` and `load_model` methods |
| 121 | + # on the `manager` property manually. |
| 122 | + client.manager.download_model(alias_or_model_id="phi-4-mini", device=DeviceType.CPU) |
| 123 | + client.manager.load_model(alias_or_model_id="phi-4-mini", device=DeviceType.CPU) |
| 124 | +
|
| 125 | + # You can also use the CLI: |
| 126 | + `foundry model load phi-4-mini --device Auto` |
| 127 | +
|
| 128 | + Raises: |
| 129 | + ServiceInitializationError: If the specified model ID or alias is not found. |
| 130 | + Sometimes a model might be available but if you have specified a device |
| 131 | + type that is not supported by the model, it will not be found. |
| 132 | +
|
| 133 | + """ |
| 134 | + settings = FoundryLocalSettings( |
| 135 | + model_id=model_id, # type: ignore |
| 136 | + env_file_path=env_file_path, |
| 137 | + env_file_encoding=env_file_encoding, |
| 138 | + ) |
| 139 | + manager = FoundryLocalManager(bootstrap=bootstrap, timeout=timeout) |
| 140 | + model_info = manager.get_model_info( |
| 141 | + alias_or_model_id=settings.model_id, |
| 142 | + device=device, |
| 143 | + ) |
| 144 | + if model_info is None: |
| 145 | + message = ( |
| 146 | + f"Model with ID or alias '{settings.model_id}:{device.value}' not found in Foundry Local." |
| 147 | + if device |
| 148 | + else f"Model with ID or alias '{settings.model_id}' for your current device not found in Foundry Local." |
| 149 | + ) |
| 150 | + raise ServiceInitializationError(message) |
| 151 | + if prepare_model: |
| 152 | + manager.download_model(alias_or_model_id=model_info.id, device=device) |
| 153 | + manager.load_model(alias_or_model_id=model_info.id, device=device) |
| 154 | + |
| 155 | + super().__init__( |
| 156 | + model_id=model_info.id, |
| 157 | + client=AsyncOpenAI(base_url=manager.endpoint, api_key=manager.api_key), |
| 158 | + **kwargs, |
| 159 | + ) |
| 160 | + self.manager = manager |
0 commit comments