add-function

작성자: microsoft

라이브러리에 새 함수를 추가하기 위한 가이드입니다. 새 API 래퍼나 유틸리티 함수를 구현할 때 사용하세요.

npx skills add https://github.com/microsoft/semantic-link-labs --skill add-function

Adding New Functions

This skill covers the workflow for adding new functions to the Semantic Link Labs library.

When to Use This Skill

Use this skill when you need to:

  • Add a new API wrapper function
  • Create a new utility function
  • Extend existing functionality with new features
  • Add functions to submodules (admin, report, lakehouse, etc.)

Function Categories

CategoryLocationPurpose
Top-level functionssrc/sempy_labs/_*.pyMain library exports
Admin functionssrc/sempy_labs/admin/Admin API operations
Report functionssrc/sempy_labs/report/Report operations
Lakehouse functionssrc/sempy_labs/lakehouse/Lakehouse operations
Direct Lake functionssrc/sempy_labs/directlake/Direct Lake model operations
TOM methodssrc/sempy_labs/tom/_model.pyTOMWrapper class methods

Step 0: Find the API Documentation

Before implementing an API wrapper, find the relevant API documentation:

# Use the API search tool
cd .claude/skills/rest-api-patterns/scripts
python search_public_api_doc.py "your search query"

# Examples:
python search_public_api_doc.py "workspace users" --source fabric
python search_public_api_doc.py "dataset refresh" --source powerbi

See the REST API Patterns skill for more details.


Step 1: Choose the Right Location

Top-Level Function

For general-purpose functions exported from sempy_labs:

# src/sempy_labs/_my_feature.py

Submodule Function

For functions belonging to a specific domain:

# src/sempy_labs/admin/_my_admin_function.py
# src/sempy_labs/lakehouse/_my_lakehouse_function.py
# src/sempy_labs/report/_my_report_function.py

Step 2: Create the Function

Required Imports

import pandas as pd
from typing import Optional, List
from uuid import UUID

# Logging decorator from sempy
from sempy._utils._log import log

# Helper functions
from sempy_labs._helper_functions import (
    resolve_workspace_name_and_id,
    resolve_workspace_id,
    _base_api,
    _create_dataframe,
)

# Icons for user messages
import sempy_labs._icons as icons

Function Template

@log
def my_new_function(
    item: str | UUID,
    workspace: Optional[str | UUID] = None,
    option: str = "default",
) -> pd.DataFrame:
    """
    Short description of what the function does.

    Extended description with more details about the function's behavior,
    use cases, and any important notes.

    This is a wrapper function for the following API: `API Name <https://learn.microsoft.com/rest/api/...>`_.

    Service Principal Authentication is supported (see `here <https://github.com/microsoft/semantic-link-labs/blob/main/notebooks/Service%20Principal.ipynb>`_ for examples).

    Parameters
    ----------
    item : str | uuid.UUID
        The name or ID of the item.
    workspace : str | uuid.UUID, default=None
        The Fabric workspace name or ID.
        Defaults to None which resolves to the workspace of the attached lakehouse
        or if no lakehouse attached, resolves to the workspace of the notebook.
    option : str, default="default"
        An option that controls function behavior.

    Returns
    -------
    pandas.DataFrame
        A pandas dataframe showing the results.
        Columns include: 'Column1', 'Column2', 'Column3'.

    Raises
    ------
    ValueError
        If the item does not exist.
    FabricHTTPException
        If the API request fails.
    """

    # Resolve workspace
    (workspace_name, workspace_id) = resolve_workspace_name_and_id(workspace)

    # Define result DataFrame structure
    columns = {
        "Column1": "string",
        "Column2": "string",
        "Column3": "int",
    }
    df = _create_dataframe(columns=columns)

    # Make API call
    responses = _base_api(
        request=f"/v1/workspaces/{workspace_id}/items",
        uses_pagination=True,
        client="fabric_sp",
    )

    # Process responses
    rows = []
    for r in responses:
        for item in r.get("value", []):
            rows.append({
                "Column1": item.get("id"),
                "Column2": item.get("name"),
                "Column3": item.get("count", 0),
            })

    if rows:
        df = pd.DataFrame(rows)

    return df

Step 3: Export the Function

From Module File

Add to the module's __init__.py:

# src/sempy_labs/admin/__init__.py (example for admin submodule)

from ._my_admin_function import my_new_function

__all__ = [
    ...,
    "my_new_function",
]

From Main Package

For top-level functions, add to src/sempy_labs/__init__.py:

from ._my_feature import my_new_function

__all__ = [
    ...,
    "my_new_function",
]

Common Patterns

Functions That Modify Resources

@log
def create_item(
    name: str,
    workspace: Optional[str | UUID] = None,
) -> None:
    """
    Creates a new item.
    ...
    """
    (workspace_name, workspace_id) = resolve_workspace_name_and_id(workspace)

    payload = {
        "displayName": name,
    }

    _base_api(
        request=f"/v1/workspaces/{workspace_id}/items",
        method="post",
        payload=payload,
        status_codes=[201, 202],
        client="fabric_sp",
    )

    print(
        f"{icons.green_dot} The '{name}' item has been successfully created "
        f"in the '{workspace_name}' workspace."
    )

Functions That Delete Resources

@log
def delete_item(
    item: str | UUID,
    workspace: Optional[str | UUID] = None,
) -> None:
    """
    Deletes an item.
    ...
    """
    (workspace_name, workspace_id) = resolve_workspace_name_and_id(workspace)
    item_id = resolve_item_id(item=item, type="ItemType", workspace=workspace_id)

    _base_api(
        request=f"/v1/workspaces/{workspace_id}/items/{item_id}",
        method="delete",
        client="fabric_sp",
    )

    print(
        f"{icons.green_dot} The item has been successfully deleted "
        f"from the '{workspace_name}' workspace."
    )

Functions With Long-Running Operations

@log
def long_running_operation(
    item: str | UUID,
    workspace: Optional[str | UUID] = None,
) -> dict:
    """
    Performs a long-running operation.
    ...
    """
    workspace_id = resolve_workspace_id(workspace)
    item_id = resolve_item_id(item=item, type="ItemType", workspace=workspace_id)

    # lro_return_json handles polling for completion
    result = _base_api(
        request=f"/v1/workspaces/{workspace_id}/items/{item_id}/operation",
        method="post",
        lro_return_json=True,
        client="fabric_sp",
    )

    return result

Step 4: Add Tests

Create tests for the new function:

# tests/test_my_feature.py

import pytest
import pandas as pd


def test_my_new_function_returns_dataframe():
    """Test that my_new_function returns a DataFrame."""
    from sempy_labs import my_new_function

    # This might require mocking for unit tests
    result = my_new_function()

    assert isinstance(result, pd.DataFrame)


def test_my_new_function_with_workspace():
    """Test my_new_function with specific workspace."""
    from sempy_labs import my_new_function

    result = my_new_function(workspace="Test Workspace")

    assert isinstance(result, pd.DataFrame)

Step 5: Document the Function

Ensure the docstring follows numpydoc style:

  1. ✅ Short description (one line)
  2. ✅ Extended description (if needed)
  3. ✅ API reference link (for wrapper functions)
  4. ✅ Service Principal note (if supported)
  5. ✅ All parameters documented with types
  6. ✅ Return value documented
  7. ✅ Exceptions documented (if applicable)

Checklist Before Committing

  • Function follows naming conventions (list_, get_, create_, etc.)
  • @log decorator is applied
  • Complete docstring with numpydoc style
  • Type hints for all parameters and return value
  • Uses standard helper functions (_base_api, resolve_*, etc.)
  • Function exported in __init__.py
  • Tests written for the new function
  • Code formatted with black
  • No linting errors
  • Documentation builds without warnings

Example: Complete New Function

See _workspaces.py for well-implemented examples:

  • list_workspace_users — List function returning DataFrame
  • update_workspace_user — Update function with parameters
  • delete_user_from_workspace — Delete function with confirmation message

API Documentation Resources

When wrapping REST APIs, reference the official documentation:

APIDocumentation
Fabric Core APIhttps://learn.microsoft.com/rest/api/fabric/core/
Fabric Admin APIhttps://learn.microsoft.com/rest/api/fabric/admin/
Power BI REST APIhttps://learn.microsoft.com/rest/api/power-bi/
Azure Management APIhttps://learn.microsoft.com/rest/api/resources/

microsoft의 다른 스킬

oss-growth
microsoft
OSS 성장 해커 페르소나
official
microsoft-foundry
microsoft
Foundry 에이전트를 엔드투엔드로 배포, 평가 및 관리: Docker 빌드, ACR 푸시, 호스팅/프롬프트 에이전트 생성, 컨테이너 시작, 배치 평가, 지속적 평가, 프롬프트 최적화 워크플로, agent.yaml, 트레이스에서 데이터셋 큐레이션. 용도: Foundry에 에이전트 배포, 호스팅 에이전트, 에이전트 생성, 에이전트 호출, 에이전트 평가, 배치 평가 실행, 지속적 평가, 지속적 모니터링, 지속적 평가 상태, 프롬프트 최적화, 프롬프트 개선, 프롬프트 최적화 도구, 에이전트 지침 최적화, 에이전트 개선...
officialdevelopmentdevops
azure-ai
microsoft
Azure AI: Search, Speech, OpenAI, Document Intelligence에 사용됩니다. 검색, 벡터/하이브리드 검색, 음성-텍스트 변환, 텍스트-음성 변환, 전사, OCR을 지원합니다. 사용 시점: AI Search, 쿼리 검색, 벡터 검색, 하이브리드 검색, 의미 검색, 음성-텍스트 변환, 텍스트-음성 변환, 전사, OCR, 텍스트를 음성으로 변환.
officialdevelopmentapi
azure-deploy
microsoft
이미 준비된 애플리케이션에 대해 기존 .azure/deployment-plan.md 및 인프라 파일이 있는 경우 Azure 배포를 실행합니다. 사용자가 새 애플리케이션 생성을 요청할 때는 이 스킬을 사용하지 말고 azure-prepare를 사용하세요. 이 스킬은 azd up, azd deploy, terraform apply, az deployment 명령을 내장된 오류 복구 기능과 함께 실행합니다. azure-prepare의 .azure/deployment-plan.md와 azure-validate의 검증 상태가 필요합니다. 사용 시점: "run azd up", "run azd deploy", "execute deployment",...
officialdevopsaws
azure-storage
microsoft
Azure Storage Services는 Blob Storage, File Shares, Queue Storage, Table Storage, Data Lake를 포함합니다. 스토리지 액세스 계층(hot, cool, cold, archive), 각 계층 사용 시기 및 계층 비교에 대한 질문에 답변합니다. 객체 스토리지, SMB 파일 공유, 비동기 메시징, NoSQL 키-값, 빅데이터 분석을 제공합니다. 수명 주기 관리를 포함합니다. 사용 용도: blob 스토리지, 파일 공유, 큐 스토리지, 테이블 스토리지, 데이터 레이크, 파일 업로드, blob 다운로드, 스토리지 계정, 액세스 계층,...
officialdevelopmentdatabase
azure-diagnostics
microsoft
Azure에서 AppLens, Azure Monitor, 리소스 상태 및 안전한 트라이지를 사용하여 Azure 프로덕션 문제를 디버그합니다. 사용 시기: 프로덕션 문제 디버그, 앱 서비스 문제 해결, 앱 서비스 높은 CPU, 앱 서비스 배포 실패, 컨테이너 앱 문제 해결, 함수 문제 해결, AKS 문제 해결, kubectl 연결 불가, kube-system/CoreDNS 오류, pod 보류 중, crashloop, 노드 준비 안 됨, 업그레이드 실패, 로그 분석, KQL, 인사이트, 이미지 풀 실패, 콜드 스타트 문제, 상태 프로브 실패,...
officialdevopsdevelopment
azure-prepare
microsoft
Azure 앱을 배포용으로 준비합니다(인프라 Bicep/Terraform, azure.yaml, Dockerfiles). 생성/현대화 또는 생성+배포에 사용하며, 크로스 클라우드 마이그레이션에는 사용하지 않습니다(azure-cloud-migrate 사용). 다음에는 사용하지 마십시오: copilot-sdk 앱(azure-hosted-copilot-sdk 사용). 사용 시점: "앱 생성", "웹 앱 빌드", "API 생성", "서버리스 HTTP API 생성", "프론트엔드 생성", "백엔드 생성", "서비스 빌드", "애플리케이션 현대화", "애플리케이션 업데이트", "인증 추가", "캐싱 추가", "Azure에 호스팅", "생성 및...
officialdevelopmentdevops
azure-validate
microsoft
Azure 배포 전 준비 상태 검증. 구성, 인프라(Bicep 또는 Terraform), RBAC 역할 할당, 관리 ID 권한, 사전 요구 사항에 대한 심층 점검을 실행합니다. 사용 시점: 내 앱 검증, 배포 준비 상태 확인, 사전 점검 실행, 구성 확인, 배포 가능 여부 확인, azure.yaml 검증, Bicep 검증, 배포 전 테스트, 배포 오류 문제 해결, Azure Functions 검증, 함수 앱 검증, 서버리스 검증...
officialdevopstesting