add-function
作者: microsoft
向库中添加新函数的指南。在实现新的API封装或工具函数时使用。
npx skills add https://github.com/microsoft/semantic-link-labs --skill add-functionAdding 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
| Category | Location | Purpose |
|---|---|---|
| Top-level functions | src/sempy_labs/_*.py | Main library exports |
| Admin functions | src/sempy_labs/admin/ | Admin API operations |
| Report functions | src/sempy_labs/report/ | Report operations |
| Lakehouse functions | src/sempy_labs/lakehouse/ | Lakehouse operations |
| Direct Lake functions | src/sempy_labs/directlake/ | Direct Lake model operations |
| TOM methods | src/sempy_labs/tom/_model.py | TOMWrapper 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:
- ✅ Short description (one line)
- ✅ Extended description (if needed)
- ✅ API reference link (for wrapper functions)
- ✅ Service Principal note (if supported)
- ✅ All parameters documented with types
- ✅ Return value documented
- ✅ Exceptions documented (if applicable)
Checklist Before Committing
- Function follows naming conventions (
list_,get_,create_, etc.) -
@logdecorator 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 DataFrameupdate_workspace_user— Update function with parametersdelete_user_from_workspace— Delete function with confirmation message
API Documentation Resources
When wrapping REST APIs, reference the official documentation:
| API | Documentation |
|---|---|
| Fabric Core API | https://learn.microsoft.com/rest/api/fabric/core/ |
| Fabric Admin API | https://learn.microsoft.com/rest/api/fabric/admin/ |
| Power BI REST API | https://learn.microsoft.com/rest/api/power-bi/ |
| Azure Management API | https://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:搜索、语音、OpenAI、文档智能。支持搜索、向量/混合搜索、语音转文字、文字转语音、转录、OCR。适用场景:AI搜索、查询搜索、向量搜索、混合搜索、语义搜索、语音转文字、文字转语音、转录、OCR、文字转语音。
officialdevelopmentapi
azure-deploy
microsoft
对已准备好的应用程序执行Azure部署,这些程序需包含现有的.azure/deployment-plan.md和基础设施文件。当用户要求创建新应用程序时,请勿使用此技能——应改用azure-prepare。此技能运行azd up、azd deploy、terraform apply和az deployment命令,并内置错误恢复机制。需要来自azure-prepare的.azure/deployment-plan.md以及来自azure-validate的已验证状态。适用场景:"运行azd up"、"运行azd deploy"、"执行部署"...
officialdevopsaws
azure-storage
microsoft
Azure存储服务,包括Blob存储、文件共享、队列存储、表存储和Data Lake。解答关于存储访问层(热、冷、冷、归档)的问题,说明各层的使用场景及对比。提供对象存储、SMB文件共享、异步消息传递、NoSQL键值存储和大数据分析。包含生命周期管理。用途:Blob存储、文件共享、队列存储、表存储、Data Lake、上传文件、下载Blob、存储账户、访问层等。
officialdevelopmentdatabase
azure-diagnostics
microsoft
使用AppLens、Azure Monitor、资源健康和安全分类调试Azure生产问题。适用场景:调试生产问题、排查应用服务、应用服务CPU过高、应用服务部署失败、排查容器应用、排查函数、排查AKS、kubectl无法连接、kube-system/CoreDNS故障、Pod挂起、CrashLoop、节点未就绪、升级失败、分析日志、KQL、洞察、镜像拉取失败、冷启动问题、健康探测失败……
officialdevopsdevelopment
azure-prepare
microsoft
为Azure应用准备部署(基础设施Bicep/Terraform、azure.yaml、Dockerfile)。用于创建/现代化或创建+部署;不用于跨云迁移(使用azure-cloud-migrate)。请勿用于:copilot-sdk应用(使用azure-hosted-copilot-sdk)。适用场景:"创建应用"、"构建Web应用"、"创建API"、"创建无服务器HTTP API"、"创建前端"、"创建后端"、"构建服务"、"现代化应用"、"更新应用"、"添加身份验证"、"添加缓存"、"托管在Azure上"、"创建并...
officialdevelopmentdevops
azure-validate
microsoft
部署前对Azure就绪状态进行验证。对配置、基础设施(Bicep或Terraform)、RBAC角色分配、托管标识权限及先决条件进行深度检查,然后再部署。适用场景:验证我的应用、检查部署就绪状态、运行预检、验证配置、检查是否可部署、验证azure.yaml、验证Bicep、部署前测试、排查部署错误、验证Azure Functions、验证函数应用、验证无服务器...
officialdevopstesting