"""Utility functions for LangChain Azure AI package."""importdataclassesimportjsonfromtypingimportAny,Tuple,Unionfromazure.core.credentialsimportAzureKeyCredential,TokenCredentialfrompydanticimportBaseModel
[docs]classJSONObjectEncoder(json.JSONEncoder):"""Custom JSON encoder for objects in LangChain."""
[docs]defdefault(self,o:Any)->Any:"""Serialize the object to JSON string. Args: o (Any): Object to be serialized. """ifisinstance(o,dict):if"callbacks"ino:delo["callbacks"]returnoifdataclasses.is_dataclass(o):returndataclasses.asdict(o)# type: ignoreifhasattr(o,"to_json"):returno.to_json()ifisinstance(o,BaseModel)andhasattr(o,"model_dump_json"):returno.model_dump_json()returnsuper().default(o)
[docs]defget_endpoint_from_project(project_connection_string:str,credential:TokenCredential)->Tuple[str,Union[AzureKeyCredential,TokenCredential]]:"""Retrieves the default inference endpoint and credentials from a project. It uses the Azure AI project's connection string to retrieve the inference defaults. The default connection of type Azure AI Services is used to retrieve the endpoint and credentials. Args: project_connection_string (str): Connection string for the Azure AI project. credential (TokenCredential): Azure credential object. Credentials must be of type `TokenCredential` when using the `project_connection_string` parameter. Returns: Tuple[str, Union[AzureKeyCredential, TokenCredential]]: Endpoint URL and credentials. """try:fromazure.ai.projectsimportAIProjectClient# type: ignore[import-untyped]fromazure.ai.projects.modelsimport(# type: ignore[import-untyped]ConnectionType,)exceptImportError:raiseImportError("The `azure.ai.projects` package is required to use the ""`project_connection_string` parameter. Please install it with ""`pip install azure-ai-projects`.")project=AIProjectClient.from_connection_string(conn_str=project_connection_string,credential=credential,)connection=project.connections.get_default(connection_type=ConnectionType.AZURE_AI_SERVICES,include_credentials=True)ifnotconnection:raiseValueError("No Azure AI Services connection found in the project. See ""https://aka.ms/azureai/modelinference/connection for more ""information.")ifconnection.endpoint_url.endswith("/models"):endpoint=connection.endpoint_urlelifconnection.endpoint_url.endswith("/"):endpoint=connection.endpoint_url+"models"else:endpoint=connection.endpoint_url+"/models"returnendpoint,connection.keyorconnection.token_credential