### Python Logging Configuration Example Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Provides an example of configuring the root logger in Python to set the logging level and format. This setup ensures consistent log output across the application. ```python import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) ``` -------------------------------- ### Install Skill using Packaging Script Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md Recommended method for installing the skill using the provided packaging script. ```bash python3 package_skill_proper.py ``` -------------------------------- ### Verify Installation Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md Commands to check the installed files and test the Python import. ```bash # Check files ls ~/.config/agents/skills/kingdee-skill-publisher/ # Test import python3 -c "from scripts import KingdeeSkillPublisher; print('✓ Installation successful')" ``` -------------------------------- ### Install Skill Manually Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md Manual installation by unzipping the skill file into the agents skills directory. ```bash unzip dist/kingdee-skill-publisher.skill -d ~/.config/agents/skills/kingdee-skill-publisher ``` -------------------------------- ### Install Skill by Direct Copy (Development) Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md For development purposes, directly copy the necessary files to the skills directory. ```bash cp -r scripts references tests ~/.config/agents/skills/kingdee-skill-publisher/ cp SKILL.md LICENSE.txt ~/.config/agents/skills/kingdee-skill-publisher/ ``` -------------------------------- ### Initialize and Setup KingdeeSkillPublisher Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/SKILL.md Initializes the KingdeeSkillPublisher and sets up authentication credentials for API interactions. ```python from scripts import KingdeeSkillPublisher publisher = KingdeeSkillPublisher() publisher.setup_credentials( server_url=server_url, app_id=app_id, app_secret=app_secret, account_id=account_id, user=user ) ``` -------------------------------- ### Use KingdeeSkillPublisher in Python Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md Example of how to use the KingdeeSkillPublisher class in Python to set up credentials, search APIs, get API details, and create a skill. ```python from scripts import KingdeeSkillPublisher # Create publisher instance publisher = KingdeeSkillPublisher() # Configure credentials result = publisher.setup_credentials( server_url="https://xxx.kingdee.com/ierp", app_id="your_app_id", app_secret="your_app_secret", account_id="your_account_id" ) # Search APIs apis = publisher.search_apis( appid_number="basedata", keyword="凭证" ) # Get API details detail = publisher.get_api_detail(api_id="123456") # Create Skill result = publisher.create_skill_from_api_id( api_id="123456", skill_name="my-api-skill" ) ``` -------------------------------- ### Python Docstring Example (Google Style) Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Demonstrates the Google style docstring format for Python methods, including descriptions for arguments and return values. Use this for documenting functions and methods. ```python def method(self, param: str) -> Dict[str, Any]: """ 方法描述 Args: param: 参数说明 Returns: 返回值说明 """ ``` -------------------------------- ### Python Logging Example Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Demonstrates basic logging configuration and usage in Python using the `logging` module. Avoid using `print` statements for logging in production code. ```python import logging logger = logging.getLogger(__name__) logger.info("操作成功") logger.warning("警告信息") logger.error("错误信息") ``` -------------------------------- ### Batch Create Skills for Query APIs Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md Shows how to retrieve all APIs for the current application and create skills specifically for APIs whose codes contain 'get', indicating they are query-type APIs. ```python # 场景:为当前应用中的查询类API创建多个Skill # 获取当前应用的所有API ar_apis = publisher.search_apis(page_size=100) # 为每个重要API创建Skill for api in ar_apis: if "get" in api['apiCode'].lower(): # 只创建查询类API result = publisher.create_skill_from_api( api_info=api, skill_name=f"ar-{api['apiCode'].lower()}" ) print(f"创建Skill: {result['skill_name']}") ``` -------------------------------- ### Project Structure Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md Overview of the project directory structure for both development and installed skill locations. ```text kingdee-skill-publisher/ # Project root directory (development) ├── SKILL.md # Skill definition (required) ├── LICENSE.txt # License ├── scripts/ # Python modules │ ├── __init__.py │ ├── api_client.py │ └── skill_generator.py ├── references/ # Reference documents ├── tests/ # Test files ├── dist/ # Packaged output │ └── kingdee-skill-publisher.skill └── package_skill_proper.py # Packaging script ~/.config/agents/skills/ # Local skills directory (after installation) └── kingdee-skill-publisher/ # Installed skill ├── SKILL.md ├── LICENSE.txt ├── scripts/ ├── references/ └── tests/ ``` -------------------------------- ### Python Type Hinting Example Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Illustrates the use of Python type hints for function parameters and return values. Ensure all functions include type annotations for better code clarity and static analysis. ```python from typing import Dict, Any, Optional, List def func(param: str) -> Optional[Dict[str, Any]]: ... ``` -------------------------------- ### Development Workflow Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md Steps involved in the development workflow: modifying code, local testing, repacking, and verifying installation. ```text 1. Modify code → Edit files under `scripts/` 2. Local test → Run test scripts directly 3. Repackage → Run `package_skill_proper.py` 4. Verify installation → Check `~/.config/agents/skills/` ``` -------------------------------- ### API Error Handling Example Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md Provides an example of how to handle potential errors returned from an API search, specifically checking for '401' (unauthorized) and '429' (rate limit exceeded) error messages. ```python result = publisher.search_apis(keyword="凭证") if not result['success']: if "401" in result['message']: print("Token已过期,请重新配置凭证") publisher.setup_credentials(...) elif "429" in result['message']: print("请求过于频繁,请稍后再试") import time time.sleep(5) else: print(f"搜索失败: {result['message']}") ``` -------------------------------- ### Python f-string Formatting Example Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Illustrates the use of f-strings for efficient and readable string formatting in Python. Prefer f-strings over older formatting methods. ```python message = f"找到 {count} 个API" ``` -------------------------------- ### Create Skill from API ID (Supply Chain Example) Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/SKILL.md Generates a skill for a supply chain order detail query using a specific API ID. ```python result = publisher.create_skill_from_api_id( api_id=selected_api['id'], skill_name="purchase-order-detail", skill_description="查询采购订单详情" ) ``` -------------------------------- ### Python Module Template Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md A template for new Python modules, including standard imports, logger setup, and a basic class structure with method documentation. Use this as a starting point for new Python files. ```python """ 模块描述 """ import logging from typing import Dict, Any, Optional logger = logging.getLogger(__name__) class NewClass: """类描述""" def __init__(self): pass def method(self) -> Dict[str, Any]: """ 方法描述 Returns: 返回值说明 """ pass ``` -------------------------------- ### Get API List with Custom Pagination Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md Demonstrates how to retrieve API lists with custom page numbers and sizes, and how to combine results from multiple pages. ```APIDOC ## Custom Page Size and Pagination ### Description This section explains how to control the pagination when fetching API lists, allowing you to specify the page number and the number of items per page. It also shows how to merge results from different pages. ### Method `publisher.client.get_api_list(page_no: int, page_size: int)` ### Parameters - **page_no** (int) - Required - The page number to retrieve. - **page_size** (int) - Required - The number of items per page. ### Response - **apis** (list) - A list of dictionaries, each containing information about an API. ### Request Example ```python # 获取第一页(每页100条) result1 = publisher.client.get_api_list( page_no=1, page_size=100 ) # 获取第二页 result2 = publisher.client.get_api_list( page_no=2, page_size=100 ) # 合并结果 all_apis = result1['apis'] + result2['apis'] ``` ``` -------------------------------- ### Explore Available APIs by Module Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md Illustrates how to fetch all published APIs and group them by their URL prefix (module) to provide a statistical overview of available APIs per module. ```python # 场景:发现系统中有哪些API可用 # 获取所有已发布的API all_apis = publisher.client.get_all_apis(page_size=100) # 按 URL 前缀做近似分组 from collections import defaultdict apis_by_module = defaultdict(list) for api in all_apis: module = api.get('urlformat', 'unknown').split('/')[1] if api.get('urlformat') else 'unknown' apis_by_module[module].append(api) # 显示模块统计 for module, apis in sorted(apis_by_module.items()): print(f"{module}: {len(apis)} 个API") ``` -------------------------------- ### Search for APIs and Create a Skill Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md Demonstrates how to search for APIs related to '凭证' (vouchers) and then create a skill from the first found API. ```python publisher = KingdeeSkillPublisher() publisher.setup_credentials(...) # 搜索凭证相关的API result = publisher.search_apis(keyword="凭证") # 从结果中选择需要的API for api in result['apis']: print(f"{api['apiCode']}: {api['apiName']}") # 选择ar_getBillDetail来创建Skill # 创建Skill selected_api = result['apis'][0] publisher.create_skill_from_api(selected_api) ``` -------------------------------- ### login.do请求体 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md 用于获取访问令牌(access_token)的 `login.do` 接口的请求体。 ```json { "user": "${config.user}", "appId": "${config.appId}", "appSecret": "${config.appSecret}", "accountId": "${config.accountId}" } ``` -------------------------------- ### Best Practice: Control Data Volume with Pagination Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md Demonstrates the best practice for handling large datasets by using pagination. Instead of loading all data at once, fetch data in smaller, manageable pages. ```python # ✗ 一次加载所有数据 result = get_all_records() # ✓ 应该分页查询 for page in range(1, total_pages + 1): result = get_records(page_no=page, page_size=100) ``` -------------------------------- ### Package Skill File Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/QUICK_START.md This is the standard .skill file format, which is a zip archive containing skill definition, license, scripts, references, and tests. ```text dist/kingdee-skill-publisher.skill ``` -------------------------------- ### API Query Optimization: Pagination vs. Full Load Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/kingdee_api_spec.md Demonstrates the difference between loading all data at once and using pagination for efficient data retrieval. Use pagination to avoid overwhelming the API and client with large datasets. ```HTTP // 不好的做法 - 一次性加载所有数据 GET /kapi/v2/.../getList 响应: 100000条记录 // 良好的做法 - 分页查询 GET /kapi/v2/.../getList?pageNo=1&pageSize=100 响应: 100条记录 ``` -------------------------------- ### Create Skill from API Info with Detail Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/SKILL.md Creates a skill by providing API information and setting `use_detail=True` to automatically fetch full details. ```python result = publisher.create_skill_from_api( api_info=selected_api, skill_name="ar-bill-detail-query", skill_description="查询应收凭证详情", use_detail=True # 自动调用 getDetail 获取完整详情 ) ``` -------------------------------- ### 根据应用编码查询API列表 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 使用 `queryByApp` 接口,按应用编码获取可用API列表。支持分页查询。 ```APIDOC ## GET /ierp/kapi/v2/open/openapi_apilist/queryByApp ### Description 根据应用编码查询API列表,支持分页。 ### Method GET ### Endpoint https://xxx.kingdee.com/ierp/kapi/v2/open/openapi_apilist/queryByApp ### Query Parameters - **appid_number** (String) - Required - 所属应用编码 - **pageNo** (Integer) - Required - 页码,从1开始,默认10 - **pageSize** (Integer) - Required - 每页数量,建议50-100 ### Response #### Success Response (200) - **status** (Boolean) - 指示请求是否成功 - **data** (Object) - 包含查询结果的数据对象 - **filter** (String) - 查询过滤器 - **lastPage** (Boolean) - 是否为最后一页 - **pageNo** (Integer) - 当前页码 - **pageSize** (Integer) - 每页数量 - **rows** (Array) - API列表 - **number** (String) - API编码 - **name** (Object) - API名称 (例如: {"zh_CN": "采购订单查询"}) - **discription** (Object) - API描述 (例如: {"zh_CN": "查询采购订单"}) - **httpmethod** (String) - HTTP方法代码 - **urlformat** (String) - API的URL格式 - **totalCount** (Integer) - 总记录数 - **errorCode** (String) - 错误代码 (成功时为 "0") - **message** (null) - 消息 (成功时为 null) #### Response Example ```json { "status": true, "data": { "filter": "[appid.number = 'your_app_id']", "lastPage": true, "pageNo": 1, "pageSize": 20, "rows": [ { "number": "pm_queryOrder", "name": {"zh_CN": "采购订单查询"}, "discription": {"zh_CN": "查询采购订单"}, "httpmethod": "0", "urlformat": "/kapi/v2/kingdee/your_app_id/order/query" } ], "totalCount": 1 }, "errorCode": "0", "message": null } ``` #### Failure Response ```json { "success": false, "errorCode": 400, "errorMessage": "参数无效" } ``` ``` -------------------------------- ### Python: 按关键词搜索API (便利方法) Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 使用KingdeeSkillPublisher客户端的便利方法query_api_by_keyword,按关键词和应用编码搜索API,并打印结果。 ```Python # 便利方法:按关键词搜索 apis = publisher.client.query_api_by_keyword("凭证", appid_number="basedata", page_size=50) for api in apis: print(f"{api['apiCode']}: {api['apiName']}") ``` -------------------------------- ### Enhanced Token Authentication Request Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/SKILL.md Example JSON payload for obtaining a token using enhanced OAuth2 authentication. Requires client ID, client secret, username, account ID, and optionally language. Nonce and timestamp are auto-generated. ```json { "client_id": "${config.client_id}", "client_secret": "${config.client_secret}", "username": "${config.username}", "accountId": "${config.accountId}", "nonce": "{{自动生成UUID}}", "timestamp": "{{自动生成当前时间,格式:yyyy-MM-dd HH:mm:ss}}", "language": "${config.language}" } ``` -------------------------------- ### Cache API List to JSON Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md Demonstrates how to fetch all APIs, cache them into a JSON file for subsequent use, and then load them from the cache. ```python import json # 第一次查询后缓存 all_apis = publisher.client.get_all_apis(page_size=100) with open('api_cache.json', 'w') as f: json.dump(all_apis, f) # 后续使用缓存 with open('api_cache.json', 'r') as f: all_apis = json.load(f) ``` -------------------------------- ### Python: 初始化并配置KingdeeSkillPublisher Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 使用Python SDK初始化KingdeeSkillPublisher并配置服务器URL、应用ID、应用密钥和账户ID以进行API调用。 ```Python from scripts import KingdeeSkillPublisher # 初始化发布器 publisher = KingdeeSkillPublisher() # 配置凭证 publisher.setup_credentials( server_url="https://xxx.kingdee.com/ierp", app_id="your_app_id", app_secret="your_app_secret", account_id="your_account_id" ) ``` -------------------------------- ### Search APIs and Create Skill Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md Demonstrates searching for APIs, selecting one (e.g., purchase order details), and then creating a skill from the selected API ID. The skill automatically includes full API request/response definitions. ```python # 1. 搜索采购订单API apis = publisher.search_apis( appid_number="basedata", keyword="采购订单" ) # 2. ⚠️ 在对话框中展示API列表并询问用户选择 # 必须等待用户明确选择一个API后才能继续 # 3. 选择采购订单详情查询(用户选择后,获取包含id的api_info) api_info = [api for api in apis if "详情" in api['api_name']][0] # 4. 使用API ID直接创建Skill(自动获取完整详情并封装) result = publisher.create_skill_from_api_id( api_id=api_info['id'], skill_name="purchase-order-detail", skill_description=f"{api_info['api_name']} - {api_info.get('api_description', '')}" ) # 5. 获取生成的Skill路径 if result['success']: skill_path = result['skill_path'] print(f"Skill已生成: {skill_path}") print(f"包含完整的API请求头、请求参数、返回参数定义") ``` -------------------------------- ### 使用API客户端直接查询(分页) Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md 演示了如何通过`publisher.client`直接调用API,特别是`get_api_list`方法,以获取更详细的分页信息。适用于需要精确控制分页参数或直接与API交互的场景。 ```python # 获取API客户端 client = publisher.client # 直接调用get_api_list(获取更详细的分页信息) result = client.get_api_list( appid_number="basedata", search_keyword="凭证", page_no=10, page_size=20 ) print(f"当前页: {result['pageNo']}") print(f"总数: {result['total']}") print(f"API数: {len(result['apis'])}") # 获取下一页 result2 = client.get_api_list( appid_number="basedata", search_keyword="凭证", page_no=11, page_size=20 ) ``` -------------------------------- ### Python: api_client.py - get_api_list 实现 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 展示了api_client.py文件中get_api_list方法的实现细节,包括请求URL、JSON参数和响应处理。 ```Python def get_api_list(self, search_keyword: str = None, module: str = None, page_no: int = 1, page_size: int = 20) -> Dict[str, Any]: """查询金蝶开放平台的API列表""" response = requests.post( f"{self.server_url}/kapi/v2/open/openapi_apilist/queryByApp", json={ "appid_number": self.app_id, "pageNo": page_no, "pageSize": min(page_size, 100), }, headers={ "Content-Type": "application/json", "accesstoken": token, } ) # 处理响应... return { 'success': result.get('success', False), 'total': result.get('data', {}).get('total', 0), 'pageNo': result.get('data', {}).get('pageNo', page_no), 'apis': result.get('data', {}).get('apis', []), 'message': result.get('error_msg', '查询成功') } ``` -------------------------------- ### 配置金蝶服务器凭证 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/SKILL.md 配置金蝶服务器的连接信息,包括服务器URL、App ID、App Secret、Account ID和用户。支持经典认证和增强型Token认证两种方式。 ```bash cd /path/to/kingdee-skill-publisher && python3 -c " from scripts import KingdeeSkillPublisher publisher = KingdeeSkillPublisher() publisher.setup_credentials(server_url='YOUR_SERVER_URL', app_id='YOUR_APP_ID', app_secret='YOUR_APP_SECRET', account_id='YOUR_ACCOUNT_ID', user='YOUR_USER') result = publisher.search_apis(appid_number='xxx', keyword='yyy') print(result) " ``` -------------------------------- ### Secure Credential Management (Environment Variable) Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Demonstrates the correct way to handle sensitive information like `app_secret` by using environment variables instead of hardcoding. Always use `os.getenv` for secrets. ```python # 错误 app_secret = "my_secret" # 正确 app_secret = os.getenv('KINGDEE_APP_SECRET') ``` -------------------------------- ### Python: 使用API客户端自动分页获取所有API Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 利用API客户端的get_all_apis方法,自动处理分页逻辑,获取指定应用下的所有API。 ```Python # 自动获取所有API(自动处理分页) all_apis = client.get_all_apis(appid_number="basedata", page_size=100) print(f"获取了 {len(all_apis)} 个API") ``` -------------------------------- ### Create Skill for Specific Function Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md Demonstrates how to create a Skill for a specific function, such as 'Financial Report Query'. It involves searching for relevant APIs, selecting one, and then creating the skill with a name and description. ```python # 场景:创建一个"财务报表查询"Skill publisher.setup_credentials(...) # 搜索报表相关API result = publisher.search_apis(keyword="报表", page_size=50) print(f"找到 {result['total']} 个报表相关API:") for api in result['apis']: print(f" - {api['apiCode']}: {api['apiName']}") # 用户选择特定的API selected_api = result['apis'][0] # 创建Skill skill_result = publisher.create_skill_from_api( api_info=selected_api, skill_name="report-query", skill_description="财务报表查询工具" ) if skill_result['success']: print(f"\n✓ Skill创建成功!") print(f"路径: {skill_result['skill_path']}") print(f"名称: {skill_result['skill_name']}") ``` -------------------------------- ### Custom Page Size and Pagination Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md Shows how to retrieve API lists with custom page sizes and fetch subsequent pages. Useful for handling large datasets efficiently. ```python # 获取第一页(每页100条) result1 = publisher.client.get_api_list( page_no=1, page_size=100 ) # 获取第二页 result2 = publisher.client.get_api_list( page_no=2, page_size=100 ) # 合并结果 all_apis = result1['apis'] + result2['apis'] ``` -------------------------------- ### Initialize Kingdee API Client Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md Initializes the Kingdee API client with server URL, user credentials, and application details. These parameters are typically set via environment variables. ```python client = KingdeeAPIClient( server_url="https://server.com:1026", # 服务器URL user="admin", # 操作用户 app_id="app_id", # 应用ID app_secret="app_secret", # 应用密钥 account_id="account_id" # 账套ID ) ``` -------------------------------- ### 配置金蝶凭证 - 环境变量 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md 推荐使用环境变量方式配置金蝶云苍穹服务器的访问凭证。 ```bash export KINGDEE_SERVER_URL="https://xxx.kingdee.com/ierp" export KINGDEE_USER="your_user" export KINGDEE_APP_ID="your_app_id" export KINGDEE_APP_SECRET="your_app_secret" export KINGDEE_ACCOUNT_ID="your_account_id" ``` -------------------------------- ### Best Practice: Reuse Token and Auto-Refresh Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md Illustrates the best practice for token management. Instead of fetching a new token every time, reuse the client's cached token, which will automatically refresh when expired. ```python # ✗ 不要每次都获取新Token token = get_token() # ✓ 应该复用客户端缓存,并在失效时自动重取 token = client.get_token() ``` -------------------------------- ### 必需的环境变量 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md 列出了运行金蝶云苍穹业务Skill发布器所需的必需环境变量,包括服务器URL、应用ID、应用密钥、账户ID和用户。 ```bash export KINGDEE_SERVER_URL="https://xxx.kingdee.com/ierp" export KINGDEE_APP_ID="your_app_id" export KINGDEE_APP_SECRET="your_app_secret" export KINGDEE_ACCOUNT_ID="your_account_id" export KINGDEE_USER="admin" # 可选,默认admin ``` -------------------------------- ### Best Practice: Avoid Hardcoding Secrets Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md Demonstrates the recommended practice of using environment variables to manage sensitive information like API secrets, rather than hardcoding them directly in the code. ```python # ✗ 不要这样做 app_secret = "my_secret" # ✓ 应该这样做 import os app_secret = os.getenv('KINGDEE_APP_SECRET') ``` -------------------------------- ### Python: 使用API客户端分页获取API列表 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 通过API客户端直接获取API列表,支持完整的请求分页信息,并打印第一页的结果。 ```Python # 使用API客户端直接获取(支持完整的分页信息) client = publisher.client # 获取第一页 result = client.get_api_list(appid_number="basedata", page_no=10, page_size=100) print(f"总共 {result['total']} 个API") print(f"第 {result['pageNo']} 页,每页 {result['pageSize']} 条") ``` -------------------------------- ### 场景2:探索系统中的所有API并按模块分组 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md 展示了如何获取系统中所有的API,并使用`defaultdict`将它们按模块进行分组。适用于需要全面了解系统API结构和分布的场景。 ```python # 发现系统中有哪些API可用 publisher.setup_credentials(...) # 假设凭证已配置 # 获取所有API并按模块分组 from collections import defaultdict all_apis = publisher.client.get_all_apis(page_size=100) apis_by_module = defaultdict(list) for api in all_apis: module = api.get('module', 'unknown') apis_by_module[module].append(api) ``` -------------------------------- ### 自动获取所有API并按功能分类 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md 展示了如何使用`get_all_apis`方法自动处理分页来获取应用中的所有API,并根据API编码的关键词(如'get', 'save', 'delete')进行分类。适用于需要全面了解系统API或进行批量处理的场景。 ```python # 自动处理分页,获取所有API all_apis = publisher.client.get_all_apis(page_size=100) print(f"当前应用共有 {len(all_apis)} 个API") # 按功能分类 query_apis = [api for api in all_apis if "get" in api['apiCode'].lower()] save_apis = [api for api in all_apis if "save" in api['apiCode'].lower()] delete_apis = [api for api in all_apis if "delete" in api['apiCode'].lower()] print(f"查询类: {len(query_apis)}") print(f"保存类: {len(save_apis)}") print(f"删除类: {len(delete_apis)}") ``` -------------------------------- ### Search and Create Skill from API Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md This snippet demonstrates how to search for APIs related to a keyword and then create a new skill based on a selected API. ```APIDOC ## Create Skill from API ### Description This process involves searching for APIs based on a keyword, selecting a specific API, and then creating a skill associated with that API. ### Method `publisher.setup_credentials(...)` `publisher.search_apis(keyword: str, page_size: int)` `publisher.create_skill_from_api(api_info: dict, skill_name: str, skill_description: str)` ### Parameters #### `search_apis` - **keyword** (str) - Required - The keyword to search for APIs. - **page_size** (int) - Optional - The number of results per page. #### `create_skill_from_api` - **api_info** (dict) - Required - Information about the selected API. - **skill_name** (str) - Required - The name for the new skill. - **skill_description** (str) - Optional - A description for the new skill. ### Response #### `search_apis` Success Response - **total** (int) - Total number of matching APIs found. - **apis** (list) - A list of dictionaries, each containing information about an API. #### `create_skill_from_api` Success Response - **success** (bool) - Indicates if the skill creation was successful. - **skill_path** (str) - The path to the created skill. - **skill_name** (str) - The name of the created skill. ### Request Example ```python # 搜索报表相关API result = publisher.search_apis(keyword="报表", page_size=50) print(f"找到 {result['total']} 个报表相关API:") for api in result['apis']: print(f" - {api['apiCode']}: {api['apiName']}") # 用户选择特定的API selected_api = result['apis'][0] # 创建Skill skill_result = publisher.create_skill_from_api( api_info=selected_api, skill_name="report-query", skill_description="财务报表查询工具" ) if skill_result['success']: print(f"\n✓ Skill创建成功!") print(f"路径: {skill_result['skill_path']}") print(f"名称: {skill_result['skill_name']}") ``` ``` -------------------------------- ### Display Module Statistics Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md Prints a summary of APIs by module, including the count and the first API name for each module. Useful for understanding API distribution. ```python print("金蝶云苍穹 API 统计\n") print("模块\tAPI数\t首个API") print("-" * 40) for module in sorted(apis_by_module.keys()): apis = apis_by_module[module] first_api = apis[0]['apiName'] if apis else '-' print(f"{module}\t{len(apis)}\t{first_api}") total = sum(len(apis) for apis in apis_by_module.values()) print(f"\n总计: {total} 个API") ``` -------------------------------- ### API列表查询接口认证头 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md 查询API列表接口时,需要使用特定的认证头 `accesstoken`。 ```http Content-Type: application/json accesstoken: ${access_token} ``` -------------------------------- ### Create Skill from API Details Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md Encapsulates a skill from API details, automatically including request headers and parameter definitions. Use `use_detail=True` to automatically call `getDetail` for complete details. ```python result = publisher.create_skill_from_api( api_info=api_info, # 传入基本信息 skill_name="ar-bill-detail-query", skill_description="查询应收凭证的详细信息", use_detail=True # 自动调用getDetail获取完整详情 ) ``` -------------------------------- ### Running Specific Python Unit Test File Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Command to run a specific test file, such as `test_api_client_token.py`. This is useful for targeted testing during development. ```bash # 运行特定测试 python -m unittest tests.test_api_client_token ``` -------------------------------- ### Optimize API Fetching with Page Size Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md Shows how to optimize API fetching by setting a larger page size (e.g., 100) to reduce the number of requests needed to retrieve all APIs. ```python # 一次查询获取100条(而不是多次查询20条) result = publisher.search_apis(keyword="", page_size=100) # 自动获取所有API all_apis = publisher.client.get_all_apis(page_size=100) ``` -------------------------------- ### Create Skill from API ID (Convenience Method) Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md A convenience method to create a skill directly using an API ID. This method automatically fetches complete details. ```python result = publisher.create_skill_from_api_id( api_id=api_info['id'], skill_name="ar-bill-detail-query", skill_description="查询应收凭证的详细信息" ) ``` -------------------------------- ### Python: 按关键词本地过滤API Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 先按应用编码获取当前应用下的API,再通过关键词在本地进行过滤。 ```Python # 先按应用编码获取当前应用下的API,再按关键词本地过滤 result = publisher.search_apis(appid_number="basedata", keyword="订单", page_size=100) ``` -------------------------------- ### Running All Python Unit Tests Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Command to execute all unit tests within the project using the `unittest` module. Ensure tests are run regularly to maintain code quality. ```bash # 运行所有测试 python -m unittest discover tests/ ``` -------------------------------- ### API Query Response Parameters Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md Illustrates the structure of the response from the `queryByApp` API, including status, pagination details, and a list of API rows with their number, name, description, and URL format. ```json { "status": true, "data": { "pageNo": 1, "pageSize": 20, "totalCount": 1, "rows": [ { "number": "pm_queryOrder", "name": {"zh_CN": "采购订单查询"}, "discription": {"zh_CN": "查询采购订单"}, "urlformat": "/kapi/v2/kingdee/your_app_id/order/query" } ] } } ``` -------------------------------- ### Token Management: Efficient Token Refresh Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/kingdee_api_spec.md Compares a naive approach of fetching a new token on every call with an improved method that caches the token and only refreshes it when it's invalid. This reduces unnecessary token requests. ```Python # 不好做法 class API: def call(self): token = get_new_token() # 每次调用都获取新Token return request(token) # 良好做法 class API: def __init__(self): self.token = None self.expires = None def call(self): if not self._is_token_valid(): self.token = get_new_token() return request(self.token) ``` -------------------------------- ### 处理搜索结果:遍历和解析API信息 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md 展示了如何解析`search_apis`返回的结果,包括总数、API列表、请求参数和返回参数。适用于需要详细了解API信息并进行后续处理的场景。 ```python result = publisher.search_apis(keyword="凭证") if result['success']: # 总结果数 print(f"找到 {result['total']} 个API") # 遍历API列表 for i, api in enumerate(result['apis'], 1): print(f"\n{i}. {api['apiName']}") print(f" 编码: {api['apiCode']}") print(f" 方法: {api['method']}") print(f" 模块: {api['module']}") print(f" 版本: {api.get('version', 'v2')}") print(f" 描述: {api['apiDescription']}") # 显示请求参数 if api.get('requestParams'): print(f" 请求参数:") for param in api['requestParams']: required = "必填" if param.get('required') else "可选" print(f" - {param['name']} ({param.get('type', 'String')}) {required}") # 显示返回参数 if api.get('returnParams'): print(f" 返回参数:") for param in api['returnParams'][:3]: # 只显示前3个 print(f" - {param['name']} ({param.get('type', 'String')})") ``` -------------------------------- ### Cache API List for Performance Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md Shows how to cache the API list locally to improve performance by avoiding repeated network requests. ```APIDOC ## Cache API List for Performance ### Description This example demonstrates how to cache the list of APIs locally to speed up subsequent requests. If a cache file exists, it's used; otherwise, the API list is fetched from the server and then saved to the cache. ### Method `publisher.setup_credentials(...)` `publisher.client.get_all_apis(page_size: int)` ### Parameters - **page_size** (int) - Optional - The number of items per page when fetching all APIs. ### Request Example ```python import json import os cache_file = 'api_cache.json' # 检查缓存 if os.path.exists(cache_file): with open(cache_file, 'r') as f: apis_cache = json.load(f) print("使用缓存的API列表") else: # 从服务器获取 publisher.setup_credentials(...) all_apis = publisher.client.get_all_apis(page_size=100) # 保存缓存 with open(cache_file, 'w') as f: json.dump(all_apis, f, ensure_ascii=False, indent=2) print(f"已保存 {len(all_apis)} 个API的缓存") ``` ``` -------------------------------- ### 依赖安装 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md 提供了使用pip安装金蝶云苍穹业务Skill发布器所需Python依赖的命令。 ```bash pip install requests python-dotenv PyYAML ``` -------------------------------- ### 生成Skill结构 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md 展示了每个生成的Skill项目所包含的文件和目录结构。 ```text my-skill/ ├── SKILL.md # Skill定义(用于Claude识别) ├── README.md # 使用说明 ├── LICENSE.txt # 许可证 ├── scripts/ │ ├── __init__.py │ ├── api_call.py # API调用主逻辑 │ ├── api_client.py # API客户端(Token管理) │ └── utils.py # 工具函数 └── references/ ├── api_schema.json # API参数定义 ├── error_codes.json # 错误码对照表 ├── examples.json # 使用示例 └── kingdee_api_spec.md # 规范参考 ``` -------------------------------- ### 场景1:为模块下的查询类API批量创建Skill Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/USAGE_WITH_OFFICIAL_API.md 演示了如何为一个应用下的所有查询类API(特别是详情查询API)批量创建Skill。适用于需要快速为一组相似功能的API生成Skill的场景。 ```python # 为当前应用下的查询类API创建Skill publisher.setup_credentials(...) # 假设凭证已配置 # 获取当前应用的所有API ar_apis = publisher.search_apis(page_size=100) # 为每个查询类API创建Skill created_skills = [] for api in ar_apis['apis']: if "getDetail" in api['apiCode']: # 只创建详情查询API skill_result = publisher.create_skill_from_api( api_info=api, skill_name=f"ar-{api['apiCode'].lower()}" ) if skill_result['success']: created_skills.append(skill_result) print(f"✓ 创建Skill: {api['apiName']}") print(f"\n共创建了 {len(created_skills)} 个Skill") ``` -------------------------------- ### Python: 使用Publisher搜索API Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 通过KingdeeSkillPublisher的search_apis方法,按应用编码和关键词搜索API,并打印搜索结果。 ```Python # 搜索API result = publisher.search_apis(appid_number="basedata", keyword="凭证") if result['success']: print(f"找到 {result['total']} 个API") for api in result['apis']: print(f" {api['apiCode']}: {api['apiName']}") else: print(f"搜索失败: {result['message']}") ``` -------------------------------- ### KingdeeAPIClient 认证流程 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md 展示了KingdeeAPIClient与金蝶OpenAPI交互的认证流程,包括服务器连通性验证、Token获取和业务调用时的请求头设置。 ```text 1. 通过 `HEAD {baseUrl}/kapi` 验证服务器连通性 2. 调用 `POST {baseUrl}/api/login.do` 获取 `data.access_token` 3. 业务调用使用 `Authorization: Bearer {token}` 请求头 4. API列表查询使用 `accesstoken: {token}` 请求头 ``` -------------------------------- ### Module-Level API List Caching Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md Illustrates caching the API list for the current application and saving it to a JSON file with specific formatting (ensure_ascii=False, indent=2). ```python # 为当前应用缓存API列表 import json api_cache = publisher.search_apis(page_size=100)['apis'] # 保存缓存 with open('api_cache.json', 'w') as f: json.dump(api_cache, f, ensure_ascii=False, indent=2) ``` -------------------------------- ### Python: 本地过滤查询API Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/references/API_QUERY_GUIDE.md 通过search_apis方法,结合关键词和page_size参数,获取当前应用下的特定类型API(如订单相关)。 ```Python # 获取当前应用的订单相关API order_apis = publisher.search_apis(keyword="订单", page_size=100) ``` -------------------------------- ### 完整工作流程 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md 概述了使用金蝶云苍穹业务Skill发布器的完整工作流程,包括配置凭证、搜索API、创建Skill和发布Skill的步骤。 ```text 1. 配置凭证 └── setup_credentials() ├── 验证服务器连接 ├── 获取Token └── 验证权限 2. 搜索API └── search_apis(appid_number, keyword) ├── 调用get_api_list() │ └── GET /kapi/v2/open/openapi_apilist/queryByApp └── 本地过滤结果 3. 创建Skill └── create_skill_from_api(api_info) └── SkillGenerator.generate_skill() ├── 生成SKILL.md ├── 生成scripts/api_call.py ├── 生成scripts/api_client.py ├── 生成references/*.json ├── 生成README.md └── 生成LICENSE.txt 4. 发布Skill └── publish_skill(skill_dir) ├── 验证文件完整性 └── 返回发布指引 ``` -------------------------------- ### 配置金蝶凭证 - 代码配置 Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/README.md 可以通过Python代码设置环境变量来配置金蝶云苍穹服务器的访问凭证。 ```python import os os.environ['KINGDEE_SERVER_URL'] = 'https://your-server.com:1026' os.environ['KINGDEE_USER'] = 'your_user' os.environ['KINGDEE_APP_ID'] = 'your_app_id' os.environ['KINGDEE_APP_SECRET'] = 'your_app_secret' os.environ['KINGDEE_ACCOUNT_ID'] = 'your_account_id' ``` -------------------------------- ### Python Error Handling with Try-Except Source: https://github.com/kingdee/kingdee-skill-publisher/blob/master/AGENTS.md Shows how to implement error handling using try-except blocks in Python. This pattern should be used for API calls to catch exceptions and return structured error messages. ```python try: result = api_call() return {'success': True, 'data': result} except Exception as e: logger.error(f"操作失败: {e}") return {'success': False, 'message': str(e)} ```