
Alibabacloud Analyticdb Postgresql Knowledgebase Ops
- 127 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
Operate Alibaba Cloud AnalyticDB PostgreSQL knowledge bases for AI workloads, including provisioning, tuning, scaling, and troubleshooting analytic query pipelines.
About
Provides Alibaba Cloud AIOps guidance for operating AnalyticDB PostgreSQL knowledge bases, covering provisioning, scaling, monitoring, query optimization, and incident response for analytics-backed AI and retrieval workloads.
- AnalyticDB PostgreSQL ops
- Knowledge-base provisioning
- Performance tuning guidance
- Alibaba Cloud AIOps patterns
- Production troubleshooting playbooks
Alibabacloud Analyticdb Postgresql Knowledgebase Ops by the numbers
- 127 all-time installs (skills.sh)
- Ranked #527 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-analyticdb-postgresql-knowledgebase-opsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 127 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Operate Alibaba Cloud AnalyticDB PostgreSQL knowledge bases for AI workloads, including provisioning, tuning, scaling, and troubleshooting analytic query pipelines.
Files
ADBPG Knowledge Base Management
Build enterprise knowledge bases in three steps: Create Knowledge Base → Upload Documents → Search & Q&A
The system automatically handles document parsing, chunking, vectorization, and index building. Users only need to focus on business logic.
Architecture: ADBPG Instance + Namespace + DocumentCollection + Vector Index + LLM Service
Core Concepts
- Knowledge Base: Container for documents, automatically manages vector indexes (corresponds to DocumentCollection in API)
- Document: Files uploaded to the knowledge base, supports PDF/Word/Markdown/HTML/JSON/CSV/images, etc.
- Q&A: Intelligent conversation based on knowledge base + large language model
---
Environment Setup
[MUST] CLI User-Agent — Every aliyun CLI command invocation must include: --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops
[MUST] Enable AI-Mode — AI-mode is required for Agent Skill execution.
Run the following commands before any CLI invocation:
```bash
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops"
```
[MUST] Disable AI-Mode at EVERY exit point — Before delivering the final response for ANY reason, always disable AI-mode first. This applies to ALL exit paths: workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed.
AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running.
```bash
aliyun configure ai-mode disable
```
Pre-check: Aliyun CLI >= 3.3.3 required
Run aliyun version to verify >= 3.3.3. If not installed or version too low,run curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash to install/update,or see references/cli-installation-guide.md for installation instructions.
Then [MUST] run aliyun configure set --auto-plugin-install true to enable automatic plugin installation.Then [MUST] run aliyun plugin update to ensure that any existing plugins on your local machine are always up-to-date.Pre-check: Alibaba Cloud Credentials Required
>
Security Rules:
- NEVER read, echo, or print credential material (including environment-based secrets)
- NEVER ask the user to paste long-lived secrets directly in the conversation or command line
- NEVER use aliyun configure set with literal credential values- ONLY use aliyun configure list to check credential status>
```bash
aliyun configure list
```
Check the output for a valid profile (AK, STS, or OAuth identity).
>
If no valid profile exists, STOP here.
1. Obtain credentials from Alibaba Cloud Console
2. Configure credentials outside of this session (via aliyun configure in terminal or environment variables in shell profile)3. Return and re-run after aliyun configure list shows a valid profileVerify CLI Credentials
aliyun gpdb describe-regions --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsScript dependencies (Python)
`scripts/upload_document_local.py` uses the Alibaba Cloud Python SDK. Declare dependencies in `requirements.txt`. Install before running the script:
pip install -r requirements.txtRequires Python 3.7+ (same baseline as Alibaba Cloud SDK for Python).
---
RAM Permissions
[MUST] RAM Permission Pre-check: Before executing operations, verify current user has required permissions.
Use ram-permission-diagnose skill to check permissions, then compare against references/ram-policies.md.If any permission is missing, abort and prompt user.
---
Parameter Confirmation
IMPORTANT: Parameter Confirmation — Before executing any command or API call,
ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks,
passwords, domain names, resource specifications, etc.) MUST be confirmed with the
user. Do NOT assume or use default values without explicit user approval.
| Parameter | Required/Optional | Description | Default Value |
|---|---|---|---|
| biz-region-id | Required | Region ID | cn-hangzhou |
| db-instance-id | Required | Instance ID (format: gp-xxxxx) | - |
| manager-account | Required | Manager account name | - |
| manager-account-password | Required | Manager account password | - |
| namespace | Optional | Namespace name | public |
| namespace-password | Required | Namespace password | - |
| collection | Required | Knowledge base name | - |
| embedding-model | Optional | Embedding model | text-embedding-v4 |
| dimension | Optional | Vector dimension | 1024 |
Note: If the knowledge base is created in a custom namespace, all subsequent operations must specify the same namespace parameter.
For interaction guidelines, smart defaults, and best practices, see references/interaction-guidelines.md.
Documentation placeholders: CLI examples use strings like<manager-account-password>and<namespace-password>. Replace them with real values from the user; never commit or log real passwords in docs, tickets, or chat.
---
Timeout Configuration
Timeout Rules: All operations must complete within reasonable time limits.
>
- Standard operations: ≤10 seconds (create/list/query)
- Upload document async: No timeout limit (async job, poll every 5-10s)
CLI Timeout Settings:
# Add --ConnectTimeout and --ReadTimeout to all commands
aliyun gpdb create-document-collection \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--namespace ns_my_knowledge_base \
--collection my_knowledge_base \
--embedding-model text-embedding-v4 \
--dimension 1024 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops \
--ConnectTimeout 10 \
--ReadTimeout 10Python SDK (default credential chain + timeouts + User-Agent):
Use CredentialClient() with no arguments so the SDK resolves credentials via the default chain (same sources as the CLI). Do not parse credential files or pass raw keys in skill code. Set user_agent and HTTP timeouts on Config (milliseconds).
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_gpdb20160503.client import Client
from alibabacloud_tea_openapi.models import Config
client = Client(Config(
credential=CredentialClient(),
region_id='cn-hangzhou',
endpoint='gpdb.aliyuncs.com',
connect_timeout=10000,
read_timeout=10000,
user_agent='AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops',
))---
Core Workflow
1. Knowledge Base Management
Create Knowledge Base
Pre-checks (run in order; not silent idempotency):
- Duplicate names: If a create step is run again when the resource already exists, the API returns a clear error (e.g. conflict / already exists). Do not create duplicate resources; interpret already-exists-style errors as “this step is satisfied” only when the response clearly indicates the resource is present, then continue the workflow.
- Retries / ClientToken: For network-level retries (e.g. timeout), use ClientToken when the API or
aliyun gpdbexposes it for that subcommand—checkaliyun gpdb <subcommand> --help. The examples below omit it when the plugin does not list it globally.
# 1. Initialize vector database
aliyun gpdb init-vector-database \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops
# 2. Create namespace (naming rule: ns_{collection}, public is forbidden)
aliyun gpdb create-namespace \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsImportant: CreateNamespace MUST be executed before CreateDocumentCollection
Create knowledge base:
# 3. Create knowledge base (in the previously created namespace)
aliyun gpdb create-document-collection \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--namespace ns_my_knowledge_base \
--collection my_knowledge_base \
--embedding-model text-embedding-v4 \
--dimension 1024 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsList Knowledge Bases
aliyun gpdb list-document-collections \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsList Namespaces
aliyun gpdb list-namespaces \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops---
2. Document Management
Upload Document (Public URL)
aliyun gpdb upload-document-async \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--file-name "user_manual.pdf" \
--file-url "https://example.com/user_manual.pdf" \
--document-loader-name ADBPGLoader \
--chunk-size 500 \
--chunk-overlap 50 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsUpload Document (Local File - SDK)
Local files use Python SDK upload_document_async_advance. Do not paste multi-line Python into the skill; use the packaged script only (default credential chain, user_agent, Config timeouts, and RuntimeOptions timeouts — see scripts/upload_document_local.py).
python3 scripts/upload_document_local.py \
--region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--file /path/to/local/file.pdfSee scripts/upload_document_local.py.
Poll Upload Progress
aliyun gpdb get-upload-document-job \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--job-id "job-xxxxx" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsList Documents
aliyun gpdb list-documents \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops---
3. Search & Q&A
Search Knowledge Base
aliyun gpdb query-content \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--content "How to configure database parameters?" \
--topk 10 \
--rerank-factor 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsKnowledge Base Q&A
aliyun gpdb chat-with-knowledge-base \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--model-params '{"Model":"qwen-max","Messages":[{"Role":"user","Content":"User question"}]}' \
--knowledge-params '{"SourceCollection":[{"Collection":"my_knowledge_base","Namespace":"ns_my_knowledge_base","NamespacePassword":"<namespace-password>","QueryParams":{"TopK":10}}]}' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops---
Reference Links
| Document | Content |
|---|---|
| references/cli-installation-guide.md | CLI Installation Guide |
| references/ram-policies.md | RAM Permissions List |
| references/related-apis.md | Related APIs |
| references/interaction-guidelines.md | Interaction Guidelines & Best Practices |
| references/verification-method.md | Verification Method |
| references/acceptance-criteria.md | Acceptance Criteria |
| references/SKILL.zh-CN.md | Chinese Version |
| requirements.txt | Python deps for scripts/ |
Acceptance Criteria - ADBPG Knowledge Base Management
Scenario: ADBPG Knowledge Base Management Skill Purpose: Skill testing acceptance criteria
Table of Contents
- 1. CLI Command Pattern Verification
- 2. Python SDK Code Pattern Verification
- 3. Workflow Verification
- 4. Parameter Verification
- 5. Security Checks
- 6. Error Handling Checks
- Checklist
---
1. CLI Command Pattern Verification
1.1 Product Name Verification
✅ CORRECT
aliyun gpdb describe-regions
aliyun gpdb init-vector-database
aliyun gpdb create-document-collection❌ INCORRECT
# Wrong: Product name should be gpdb, not adbpg
aliyun adbpg describe-regions
# Wrong: Product name should be lowercase
aliyun GPDB describe-regions1.2 Command Format Verification (Plugin Mode)
✅ CORRECT - Plugin mode (lowercase with hyphens)
aliyun gpdb describe-regions
aliyun gpdb init-vector-database
aliyun gpdb create-namespace
aliyun gpdb create-document-collection
aliyun gpdb upload-document-async
aliyun gpdb query-content❌ INCORRECT - Traditional API mode (CamelCase)
# Wrong: Should use plugin mode with lowercase hyphens
aliyun gpdb DescribeRegions
aliyun gpdb InitVectorDatabase
aliyun gpdb CreateNamespace
aliyun gpdb CreateDocumentCollection1.3 Parameter Name Format Verification
✅ CORRECT - Lowercase with hyphens
aliyun gpdb create-document-collection \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin \
--manager-account-password 'pass' \
--collection my_kb \
--embedding-model text-embedding-v4 \
--dimension 1024❌ INCORRECT - CamelCase parameter names
# Wrong: Parameter names should be lowercase with hyphens
aliyun gpdb create-document-collection \
--RegionId cn-hangzhou \
--DBInstanceId gp-xxxxx \
--ManagerAccount admin1.4 User-Agent Must Be Present
✅ CORRECT
aliyun gpdb describe-regions --user-agent AlibabaCloud-Agent-Skills
aliyun gpdb query-content --content "test" --user-agent AlibabaCloud-Agent-Skills❌ INCORRECT
# Wrong: Missing --user-agent parameter
aliyun gpdb describe-regions
aliyun gpdb query-content --content "test"---
2. Python SDK Code Pattern Verification
2.1 Import Paths
✅ CORRECT
from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions❌ INCORRECT
# Wrong: Incorrect package name
from alibabacloud_gpdb.client import Client
from alibabacloud_adbpg.client import Client
# Wrong: Incorrect version number
from alibabacloud_gpdb20200101.client import Client2.2 Credential Reading Method
✅ CORRECT - Default credential chain (SDK)
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_gpdb20160503.client import Client
from alibabacloud_tea_openapi.models import Config
client = Client(Config(
credential=CredentialClient(),
region_id='cn-hangzhou',
endpoint='gpdb.aliyuncs.com',
connect_timeout=10000,
read_timeout=10000,
user_agent='AlibabaCloud-Agent-Skills',
))Do not parse ~/.aliyun/config.json or pass raw access_key_id / access_key_secret from files in skill code; rely on CredentialClient() default resolution.
❌ INCORRECT - Hardcoded credentials
# Wrong: Never hardcode AK/SK
client = Client(Config(
access_key_id='LTAI5tXXXXXXXXXX',
access_key_secret='8dXXXXXXXXXXXXXXXXXXXX',
))2.3 Local File Upload
✅ CORRECT - Packaged script (recommended)
Use scripts/upload_document_local.py: default credential chain, user_agent='AlibabaCloud-Agent-Skills', and HTTP timeouts on Config.
✅ CORRECT - Use Advance method (inline pattern)
with open(file_path, 'rb') as f:
request = models.UploadDocumentAsyncAdvanceRequest(
region_id='cn-hangzhou',
dbinstance_id='gp-xxxxx',
namespace='ns_my_kb',
namespace_password='<namespace-password>',
collection='my_kb',
file_name=os.path.basename(file_path),
file_url_object=f, # Pass file stream
document_loader_name='ADBPGLoader',
)
response = client.upload_document_async_advance(request, RuntimeOptions())❌ INCORRECT - Regular upload method doesn't support local files
# Wrong: Regular upload_document_async doesn't support local file streams
request = models.UploadDocumentAsyncRequest(
file_url_object=f, # This parameter doesn't exist in regular request
)---
3. Workflow Verification
3.1 Knowledge Base Creation Order
✅ CORRECT - Correct order
1. InitVectorDatabase (re-run may error if already initialized; handle per SKILL pre-checks)
2. CreateNamespace (MUST be before CreateDocumentCollection)
3. CreateDocumentCollection❌ INCORRECT - Wrong order
# Wrong: Creating Collection before Namespace will fail
1. CreateDocumentCollection
2. CreateNamespace
# Error: role "knowledgebasepub" does not exist3.2 Namespace Rules
✅ CORRECT
# Namespace name: ns_{collection}
--namespace ns_my_knowledge_base
--namespace ns_product_docs❌ INCORRECT
# Wrong: public namespace is forbidden
--namespace public
# Wrong: Namespace should have ns_ prefix
--namespace my_knowledge_base---
4. Parameter Verification
4.1 Required Parameter Check
Create Knowledge Base Required Parameters
| Parameter | Required |
|---|---|
| biz-region-id | ✅ |
| db-instance-id | ✅ |
| manager-account | ✅ |
| manager-account-password | ✅ |
| collection | ✅ |
| embedding-model | ✅ |
| dimension | ✅ |
Upload Document Required Parameters
| Parameter | Required |
|---|---|
| biz-region-id | ✅ |
| db-instance-id | ✅ |
| namespace-password | ✅ |
| collection | ✅ |
| file-name | ✅ |
| file-url | ✅ |
4.2 Parameter Value Formats
✅ CORRECT
# Instance ID format
--db-instance-id gp-bp1234567890
# Vector dimension (number)
--dimension 1024
# JSON format parameters
--entity-types '["Person","Organization"]'
--model-params '{"Model":"qwen-max","Messages":[...]}'❌ INCORRECT
# Wrong: Instance ID format error
--db-instance-id bp1234567890
# Wrong: Dimension is not a number
--dimension "1024"
# Wrong: JSON format error
--entity-types [Person,Organization]---
5. Security Checks
5.1 Credential Security
✅ CORRECT
# Only check credential status, don't output sensitive values
aliyun configure list❌ INCORRECT
# Wrong: Never output AK/SK values
echo $ALIBABA_CLOUD_ACCESS_KEY_ID
cat ~/.aliyun/config.json | grep access_key
# Wrong: Never pass AK directly in command line
aliyun configure set --access-key-id LTAI5tXXX --access-key-secret 8dXXX5.2 Sensitive Information Prompts
✅ CORRECT
- Prompt user "Password will be used for subsequent operations, please keep it safe"
- Don't display password in plaintext in logs or output
❌ INCORRECT
- Display password in plaintext in output
- Write password to files or logs
---
6. Error Handling Checks
6.1 Common Error Responses
| Error | Correct Handling |
|---|---|
| Instance.NotSupportVector | Prompt user to upgrade instance or enable vector engine |
| role "knowledgebasepub" does not exist | Prompt to execute CreateNamespace first |
| Collection.NotFound | Prompt to check if knowledge base name is correct |
| Namespace.PasswordInvalid | Prompt to check namespace password |
6.2 Retry Strategy
✅ CORRECT
- Auto-poll upload progress after uploading document, query every 5-10 seconds
- Maximum 30 polls (about 5 minutes)
❌ INCORRECT
- Don't poll upload progress, user can't know if upload completed
- Poll interval too short (< 3 seconds), may trigger rate limiting
---
Checklist
- [ ] CLI commands use plugin mode (lowercase with hyphens)
- [ ] All CLI commands include
--user-agent AlibabaCloud-Agent-Skills - [ ] Python SDK uses correct import paths
- [ ] Python SDK uses
CredentialClient()default chain (no~/.aliyun/config.jsonparsing in skill code) - [ ] Python SDK
Configsetsuser_agent='AlibabaCloud-Agent-Skills'and reasonableconnect_timeout/read_timeout - [ ] Local file upload uses scripts/upload_document_local.py or equivalent pattern
- [ ] No hardcoded AK/SK
- [ ] Knowledge base creation follows correct order
- [ ] Namespace name uses
ns_prefix - [ ] public namespace is forbidden
- [ ] Sensitive information not output in plaintext
Aliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
Table of Contents
- Installation
- Configuration
- Verification
- Security Best Practices
- Troubleshooting
- Advanced Configuration
- Next Steps
- References
Aliyun CLI 3.3.3+: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
Installation
macOS
Using Homebrew (Recommended)
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun versionUsing Binary
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionLinux
Debian/Ubuntu
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionCentOS/RHEL
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionARM64 Architecture
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/Windows
Using Binary 1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip 2. Extract the ZIP file 3. Add the directory to your PATH environment variable 4. Open new Command Prompt or PowerShell 5. Verify: aliyun version
Using PowerShell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun versionConfiguration
Quick Start
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhouAll aliyun configure commands support non-interactive flags, which is the recommended approach — it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.
Where to Get Access Keys
1. Log in to Aliyun Console: https://ram.console.aliyun.com/ 2. Navigate to: AccessKey Management 3. Create a new AccessKey pair 4. Save the secret immediately — it's only shown once
Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhouConfiguration is stored in ~/.aliyun/config.json:
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhouUse cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhouUse cases: cross-account resource access, temporary elevated privileges, role-based access control.
4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhouRequirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhouEnvironment Variables
Highest priority - overrides config file
Access Key Mode
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhouSTS Token Mode
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhouECS RAM Role Mode
export ALIBABA_CLOUD_ECS_METADATA=role_nameUse Case:
- CI/CD pipelines
- Docker containers
- Temporary credential override
Managing Multiple Profiles
Create Named Profiles
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghaiUse Specific Profile
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectAList and Switch Profiles
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profileCredential Priority
Credentials are loaded in this order (first found wins):
1. Command-line flag: --profile <name> 2. Environment variable: ALIBABA_CLOUD_PROFILE 3. Environment credentials: ALIBABA_CLOUD_ACCESS_KEY_ID, etc. 4. Configuration file: ~/.aliyun/config.json (current profile) 5. ECS Instance RAM Role: If running on ECS with attached role
Verification
Test Authentication
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regionsIf successful, you'll see:
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}If failed, you'll see error messages:
InvalidAccessKeyId.NotFound- Wrong Access Key IDSignatureDoesNotMatch- Wrong Access Key SecretInvalidSecurityToken.Expired- STS token expired (for StsToken mode)Forbidden.RAM- Insufficient permissions
Debug Configuration
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get modeSecurity Best Practices
1. Use RAM Users (Not Root Account)
❌ Don't: Use Aliyun root account credentials ✅ Do: Create RAM users with specific permissions
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys2. Principle of Least Privilege
Grant only the minimum permissions needed:
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess3. Rotate Access Keys Regularly
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console4. Use STS Tokens for Temporary Access
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou5. Use ECS RAM Roles When Possible
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou6. Never Commit Credentials
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead7. Secure Config File
# Restrict permissions
chmod 600 ~/.aliyun/config.jsonTroubleshooting
Issue: Command Not Found
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATHIssue: Authentication Failed
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is activeIssue: Permission Denied
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operationsIssue: STS Token Expired
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhouIssue: Wrong Region
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghaiAdvanced Configuration
Custom Endpoint
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.comProxy Settings
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.comTimeout Settings
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30Next Steps
After installation and configuration:
1. Install plugins for services you need (v3.3.3+ supports all published product plugins):
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote2. Explore commands:
aliyun ecs --help
aliyun fc --help3. Read documentation:
- Command Syntax Guide
- Global Flags Reference
- Common Scenarios
References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
Interaction Guidelines - ADBPG Knowledge Base Management
Table of Contents
---
AskUserQuestion Usage Principles
AskUserQuestion should only be used for limited option selections, not for free-form input:
| Scenario | Usage |
|---|---|
| Chunking strategy selection (General/Technical/FAQ/Legal) | AskUserQuestion |
| Yes/No confirmation | AskUserQuestion |
| Guiding when user intent is unclear | AskUserQuestion |
| File paths, URLs, passwords, instance IDs, knowledge base names | Collect via text conversation, not AskUserQuestion |
Anti-pattern: Don't put "Let me input" as an AskUserQuestion option. Users cannot enter free-form text in options. For free-form input, simply ask in your reply text.
---
Information Collection Strategy
When Creating a Knowledge Base
Collect via text conversation:
Please provide the following information:
1. Instance ID (format: gp-bp1234567890)
2. Manager account name
3. Manager account password
4. Namespace password (needed for upload/search/Q&A, recommend different from manager password)
5. Knowledge base name (lowercase letters and underscores)When Uploading Documents
Collect via text conversation:
Please provide the file source:
- Public URL: Give me the link directly
- Local file: Give me the file path, e.g., /Users/xxx/docs/manual.pdf
- Local directory: Give me the directory path, e.g., /Users/xxx/docs/, I'll scan supported files---
Smart Defaults
Text Knowledge Base
| Parameter | Default Value | Description |
|---|---|---|
| Namespace | ns_{collection} | Prefixed with collection name, public is forbidden |
| EmbeddingModel | text-embedding-v4 | Recommended for text, 1024 dimensions |
| Dimension | 1024 | Vector dimension (text) |
| Metrics | cosine | Cosine similarity |
| TopK | 10 | Return 10 results |
| RerankFactor | 5 | Rerank factor, maximize retrieval precision |
| DocumentLoaderName | ADBPGLoader | Most format support |
| ChunkSize | 500 | Chunk size, works with reranker for precision |
| ChunkOverlap | 50 | Chunk overlap, ~10% of ChunkSize |
| Model (Q&A) | qwen-max | Qwen model |
Image Knowledge Base
| Parameter | Value | Description |
|---|---|---|
| EmbeddingModel | qwen3-vl-embedding | Multimodal vision model |
| Dimension | 2560 | Vision model default dimension |
Note: Image and text knowledge bases cannot share the same Collection due to different EmbeddingModel and Dimension. Create them separately.
Chunking Strategies
| Scenario | ChunkSize | ChunkOverlap | Suitable Documents |
|---|---|---|---|
| General (default) | 500 | 50 | Most documents |
| Technical docs | 800 | 100 | Manuals, API docs |
| FAQ / Short text | 256 | 30 | Q&A pairs, knowledge entries |
| Legal / Contracts | 1024 | 200 | Strong clause correlation |
---
Best Practices
1. Focus on user goals, don't expose underlying concepts (namespaces, vector dimensions, HNSW params, etc.) unless user asks 2. Execute query operations directly without confirmation 3. Show key parameters for modification operations and confirm before execution, don't show all parameters 5. Execute in sequence when creating knowledge base: InitVectorDatabase → CreateNamespace → CreateDocumentCollection; duplicate creates return explicit errors—handle per SKILL.md Create Knowledge Base pre-checks (not silent idempotency); keep transparent to the user where possible 6. Collect namespace password when creating knowledge base, needed for upload/search/Q&A later, don't wait to ask 7. Auto-poll upload progress after uploading, query every 5-10 seconds, notify user when complete 8. Use SDK for local file uploads, auto-handles OSS transfer, transparent to user 9. Remember parameters within session: DBInstanceId, ManagerAccount, NamespacePassword etc., provide once, reuse throughout 10. Auto-assemble JSON for Q&A: User only provides question text, agent constructs ModelParams/KnowledgeParams 11. Free-form input via text conversation, limited choices via AskUserQuestion: paths, URLs, passwords should not use AskUserQuestion 12. Password parameters involve sensitive info, remind user about security 13. All CLI commands MUST include --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops
---
Quick Guide
| User Intent | Action |
|---|---|
| "I want to create a knowledge base" | → Collect all info in one round → Auto init + create namespace + create knowledge base |
| "Upload a document" | → Collect file source via text → URL uses CLI / Local uses SDK → Auto-poll progress |
| "Search for xxx" | → Search knowledge base |
| "Ask about xxx" | → Knowledge base Q&A |
| "What's in the knowledge base" | → List documents |
---
Auto-Create Instance When None Available
When user has no available ADBPG instance (or instance reports Instance.NotSupportVector):
1. Look for a skill that can create instances (keywords: ADBPG or AnalyticDB PostgreSQL) 2. If found, invoke that skill to create instance with recommended config:
- Version: 7.0
- Spec: 4C16G
- Type: HighAvailability
- Enable vector optimization
3. Wait for instance to be available, then continue knowledge base operations
RAM Policies - ADBPG Knowledge Base Management
This document lists the RAM permissions required for ADBPG Knowledge Base Management.
Minimum Permission Policy
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"gpdb:DescribeRegions",
"gpdb:DescribeDBInstances",
"gpdb:InitVectorDatabase",
"gpdb:CreateNamespace",
"gpdb:CreateDocumentCollection",
"gpdb:UploadDocumentAsync",
"gpdb:GetUploadDocumentJob",
"gpdb:CancelUploadDocumentJob",
"gpdb:ListDocuments",
"gpdb:DescribeDocument",
"gpdb:UpsertChunks",
"gpdb:QueryContent",
"gpdb:QueryKnowledgeBasesContent",
"gpdb:ChatWithKnowledgeBase"
],
"Resource": "*"
}
]
}Permission Descriptions
| API | Permission Action | Description |
|---|---|---|
| DescribeRegions | gpdb:DescribeRegions | Query available regions |
| DescribeDBInstances | gpdb:DescribeDBInstances | Query instance list |
| InitVectorDatabase | gpdb:InitVectorDatabase | Initialize vector database |
| CreateNamespace | gpdb:CreateNamespace | Create namespace |
| ListNamespaces | gpdb:ListNamespaces | List namespaces |
| CreateDocumentCollection | gpdb:CreateDocumentCollection | Create knowledge base |
| ListDocumentCollections | gpdb:ListDocumentCollections | List knowledge bases |
| UploadDocumentAsync | gpdb:UploadDocumentAsync | Upload document |
| GetUploadDocumentJob | gpdb:GetUploadDocumentJob | Query upload progress |
| CancelUploadDocumentJob | gpdb:CancelUploadDocumentJob | Cancel upload job |
| ListDocuments | gpdb:ListDocuments | List documents |
| DescribeDocument | gpdb:DescribeDocument | View document details |
| UpsertChunks | gpdb:UpsertChunks | Upload custom chunks |
| QueryContent | gpdb:QueryContent | Search knowledge base |
| QueryKnowledgeBasesContent | gpdb:QueryKnowledgeBasesContent | Cross-knowledge base search |
| ChatWithKnowledgeBase | gpdb:ChatWithKnowledgeBase | Knowledge base Q&A |
Permissions by Function
Basic Query (Read-only)
{
"Effect": "Allow",
"Action": [
"gpdb:DescribeRegions",
"gpdb:DescribeDBInstances",
"gpdb:ListDocumentCollections",
"gpdb:ListDocuments",
"gpdb:DescribeDocument",
"gpdb:QueryContent",
"gpdb:QueryKnowledgeBasesContent",
"gpdb:ChatWithKnowledgeBase",
"gpdb:GetUploadDocumentJob"
],
"Resource": "*"
}Knowledge Base Management (Read-Write)
{
"Effect": "Allow",
"Action": [
"gpdb:InitVectorDatabase",
"gpdb:CreateNamespace",
"gpdb:ListNamespaces",
"gpdb:CreateDocumentCollection"
],
"Resource": "*"
}Document Management (Read-Write)
{
"Effect": "Allow",
"Action": [
"gpdb:UploadDocumentAsync",
"gpdb:CancelUploadDocumentJob",
"gpdb:UpsertChunks"
],
"Resource": "*"
}Additional Permissions for SDK Local File Upload
If you need to upload local files via SDK (SDK internally uses OSS for transfer), you also need the following OSS permissions:
{
"Effect": "Allow",
"Action": [
"oss:PutObject",
"oss:GetObject"
],
"Resource": "acs:oss:*:*:gpdb-*"
}Permission Verification
Use the following commands to verify current user has required permissions:
# Test basic permissions
aliyun gpdb describe-regions --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops
# Test instance query permission
aliyun gpdb describe-dbinstances --region cn-hangzhou --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsReference Documentation
Related APIs - ADBPG Knowledge Base Management
This document lists all APIs and CLI commands involved in ADBPG Knowledge Base Management.
API List
| Product | CLI Command | API Action | Description |
|---|---|---|---|
| GPDB | aliyun gpdb describe-regions | DescribeRegions | Query available regions |
| GPDB | aliyun gpdb describe-dbinstances | DescribeDBInstances | Query instance list |
| GPDB | aliyun gpdb init-vector-database | InitVectorDatabase | Initialize vector database |
| GPDB | aliyun gpdb create-namespace | CreateNamespace | Create namespace |
| GPDB | aliyun gpdb list-namespaces | ListNamespaces | List namespaces |
| GPDB | aliyun gpdb create-document-collection | CreateDocumentCollection | Create knowledge base |
| GPDB | aliyun gpdb list-document-collections | ListDocumentCollections | List knowledge bases |
| GPDB | aliyun gpdb upload-document-async | UploadDocumentAsync | Upload document (async) |
| GPDB | aliyun gpdb get-upload-document-job | GetUploadDocumentJob | Query upload progress |
| GPDB | aliyun gpdb cancel-upload-document-job | CancelUploadDocumentJob | Cancel upload job |
| GPDB | aliyun gpdb list-documents | ListDocuments | List documents |
| GPDB | aliyun gpdb describe-document | DescribeDocument | View document details |
| GPDB | aliyun gpdb upsert-chunks | UpsertChunks | Upload custom chunks |
| GPDB | aliyun gpdb query-content | QueryContent | Search knowledge base |
| GPDB | aliyun gpdb query-knowledge-bases-content | QueryKnowledgeBasesContent | Cross-knowledge base search |
| GPDB | aliyun gpdb chat-with-knowledge-base | ChatWithKnowledgeBase | Knowledge base Q&A |
Grouped by Function
Instance Management
| CLI Command | API Action | Description |
|---|---|---|
aliyun gpdb describe-regions | DescribeRegions | Query available regions |
aliyun gpdb describe-dbinstances | DescribeDBInstances | Query instance list |
aliyun gpdb init-vector-database | InitVectorDatabase | Initialize vector database |
Namespace Management
| CLI Command | API Action | Description |
|---|---|---|
aliyun gpdb create-namespace | CreateNamespace | Create namespace |
aliyun gpdb list-namespaces | ListNamespaces | List namespaces |
Knowledge Base Management
| CLI Command | API Action | Description |
|---|---|---|
aliyun gpdb create-document-collection | CreateDocumentCollection | Create knowledge base |
aliyun gpdb list-document-collections | ListDocumentCollections | List knowledge bases |
Document Management
| CLI Command | API Action | Description |
|---|---|---|
aliyun gpdb upload-document-async | UploadDocumentAsync | Upload document (async) |
aliyun gpdb get-upload-document-job | GetUploadDocumentJob | Query upload progress |
aliyun gpdb cancel-upload-document-job | CancelUploadDocumentJob | Cancel upload job |
aliyun gpdb list-documents | ListDocuments | List documents |
aliyun gpdb describe-document | DescribeDocument | View document details |
aliyun gpdb upsert-chunks | UpsertChunks | Upload custom chunks |
Search & Q&A
| CLI Command | API Action | Description |
|---|---|---|
aliyun gpdb query-content | QueryContent | Search knowledge base |
aliyun gpdb query-knowledge-bases-content | QueryKnowledgeBasesContent | Cross-knowledge base search |
aliyun gpdb chat-with-knowledge-base | ChatWithKnowledgeBase | Knowledge base Q&A |
Common Parameters
General Parameters
| Parameter | Type | Description |
|---|---|---|
--biz-region-id | String | Region ID, e.g., cn-hangzhou |
--db-instance-id | String | Instance ID, format: gp-xxxxx |
--user-agent | String | User agent identifier, must be set to AlibabaCloud-Agent-Skills |
Authentication Parameters
| Parameter | Type | Description |
|---|---|---|
--manager-account | String | Manager account name |
--manager-account-password | String | Manager account password |
--namespace | String | Namespace name |
--namespace-password | String | Namespace password |
Knowledge Base Parameters
| Parameter | Type | Description |
|---|---|---|
--collection | String | Knowledge base name |
--embedding-model | String | Embedding model name |
--dimension | Integer | Vector dimension |
--metrics | String | Similarity algorithm: cosine/l2/ip |
Document Parameters
| Parameter | Type | Description |
|---|---|---|
--file-name | String | File name |
--file-url | String | File URL |
--document-loader-name | String | Document loader name |
--chunk-size | Integer | Chunk size |
--chunk-overlap | Integer | Chunk overlap |
Search Parameters
| Parameter | Type | Description |
|---|---|---|
--content | String | Search content |
--topk | Integer | Number of results to return |
--rerank-factor | Integer | Rerank factor |
--filter | String | SQL WHERE format filter condition |
CLI Help Commands
# View product help
aliyun gpdb --help
# View specific command help
aliyun gpdb create-document-collection --help
aliyun gpdb upload-document-async --help
aliyun gpdb query-content --helpReference Documentation
ADBPG 知识库管理
三步构建企业知识库:创建知识库 → 上传文档 → 检索问答
系统自动处理文档解析、切片、向量化、索引构建,用户只需关注业务。
Architecture: ADBPG Instance + Namespace + DocumentCollection + Vector Index + LLM Service
英文版见 SKILL.md。
核心概念
- 知识库: 文档的容器,自动管理向量索引(对应 API 中的 DocumentCollection)
- 文档: 上传到知识库的文件,支持 PDF/Word/Markdown/HTML/JSON/CSV/图片等
- 问答: 基于知识库 + 大模型的智能对答
---
环境准备
[MUST] CLI User-Agent — Every aliyun CLI command invocation must include: --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops
[MUST] Enable AI-Mode — AI-mode is required for Agent Skill execution.
Run the following commands before any CLI invocation:
```bash
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops"
```
[MUST] Disable AI-Mode at EVERY exit point — Before delivering the final response for ANY reason, always disable AI-mode first. This applies to ALL exit paths: workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed.
AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running.
```bash
aliyun configure ai-mode disable
```
Pre-check: Aliyun CLI >= 3.3.3 required
Run aliyun version to verify >= 3.3.3. If not installed or version too low,run curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash to install/update,or see cli-installation-guide.md for installation instructions.
Then [MUST] run aliyun configure set --auto-plugin-install true to enable automatic plugin installation.Then [MUST] run aliyun plugin update to ensure that any existing plugins on your local machine are always up-to-date.Pre-check: Alibaba Cloud Credentials Required
>
Security Rules:
- NEVER read, echo, or print credential material(含基于环境变量的密钥)
- NEVER ask the user to paste long-lived secrets directly in the conversation or command line
- NEVER use aliyun configure set with literal credential values- ONLY use aliyun configure list to check credential status>
```bash
aliyun configure list
```
Check the output for a valid profile (AK, STS, or OAuth identity).
>
If no valid profile exists, STOP here.
1. Obtain credentials from Alibaba Cloud Console
2. Configure credentials outside of this session (via aliyun configure in terminal or environment variables in shell profile)3. Return and re-run after aliyun configure list shows a valid profile验证 CLI 凭证
aliyun gpdb describe-regions --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops脚本依赖(Python)
`scripts/upload_document_local.py` 依赖阿里云 Python SDK。依赖声明见仓库根目录 `requirements.txt`。运行脚本前安装:
pip install -r requirements.txt需要 Python 3.7+(与阿里云 Python SDK 一致)。
---
RAM 权限
[MUST] RAM Permission Pre-check: Before executing operations, verify current user has required permissions.
Use ram-permission-diagnose skill to check permissions, then compare against ram-policies.md.If any permission is missing, abort and prompt user.
---
参数确认
IMPORTANT: Parameter Confirmation — Before executing any command or API call,
ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks,
passwords, domain names, resource specifications, etc.) MUST be confirmed with the
user. Do NOT assume or use default values without explicit user approval.
| 参数 | 必需/可选 | 说明 | 默认值 |
|---|---|---|---|
| biz-region-id | 必需 | 地域 ID | cn-hangzhou |
| db-instance-id | 必需 | 实例 ID(格式 gp-xxxxx) | - |
| manager-account | 必需 | 管理账号 | - |
| manager-account-password | 必需 | 管理账号密码 | - |
| namespace | 可选 | 命名空间名称 | public |
| namespace-password | 必需 | 命名空间密码 | - |
| collection | 必需 | 知识库名称 | - |
| embedding-model | 可选 | 向量模型 | text-embedding-v4 |
| dimension | 可选 | 向量维度 | 1024 |
注意:如果知识库创建在自定义命名空间,后续所有操作必须指定相同的命名空间参数。
交互规范、智能默认值和最佳实践详见 interaction-guidelines.md。
文档占位符: 命令示例中的<manager-account-password>、<namespace-password>须替换为用户真实口令;禁止在文档、工单或对话中粘贴或长期保存明文密码。
---
超时配置
超时规则: 所有操作必须在合理的时间内完成。
>
- 标准操作: ≤10 秒(创建/列表/查询)
- 异步上传文档: 无超时限制(异步任务,每 5-10 秒轮询)
CLI 超时设置:
# 为所有命令添加 --ConnectTimeout 和 --ReadTimeout
aliyun gpdb create-document-collection \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--namespace ns_my_knowledge_base \
--collection my_knowledge_base \
--embedding-model text-embedding-v4 \
--dimension 1024 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops \
--ConnectTimeout 10 \
--ReadTimeout 10Python SDK(默认凭证链 + 超时 + User-Agent):
使用无参 CredentialClient(),由 SDK 按默认凭证链解析(与 CLI 一致);不要在技能代码中解析凭证文件或传入明文密钥。在 Config 上设置 user_agent 与 HTTP 超时(毫秒)。
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_gpdb20160503.client import Client
from alibabacloud_tea_openapi.models import Config
client = Client(Config(
credential=CredentialClient(),
region_id='cn-hangzhou',
endpoint='gpdb.aliyuncs.com',
connect_timeout=10000,
read_timeout=10000,
user_agent='AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops',
))---
核心工作流
一、知识库管理
创建知识库
前置检查(按顺序执行;并非静默幂等):
- 重名: 若资源已存在再次执行创建,接口通常返回明确错误(冲突、已存在等)。不得重复创建同名资源;仅当响应明确表明资源已存在时,可将该错误视为本步已满足并继续后续流程,否则须排查。
- 重试与 ClientToken: 针对网络超时等重试,若 API 或
aliyun gpdb该子命令支持 ClientToken,应使用(见aliyun gpdb <子命令> --help)。若插件未列出该参数,则以下示例不强行写死;以错误处理与帮助为准。
# 1. 初始化向量数据库
aliyun gpdb init-vector-database \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops
# 2. 创建命名空间(命名规则:ns_{collection},禁止使用 public)
aliyun gpdb create-namespace \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops关键:CreateNamespace 必须在 CreateDocumentCollection 之前执行
创建知识库:
# 3. 创建知识库(在先前创建的命名空间下)
aliyun gpdb create-document-collection \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--namespace ns_my_knowledge_base \
--collection my_knowledge_base \
--embedding-model text-embedding-v4 \
--dimension 1024 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops查看知识库列表
aliyun gpdb list-document-collections \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops查看命名空间列表
aliyun gpdb list-namespaces \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops---
二、文档管理
上传文档(公网 URL)
aliyun gpdb upload-document-async \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--file-name "user_manual.pdf" \
--file-url "https://example.com/user_manual.pdf" \
--document-loader-name ADBPGLoader \
--chunk-size 500 \
--chunk-overlap 50 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops上传文档(本地文件 - SDK)
本地文件使用 Python SDK upload_document_async_advance。不要在技能中粘贴多行 Python;仅使用封装脚本(默认凭证链、user_agent、Config 与 RuntimeOptions 超时,见 scripts/upload_document_local.py):
python3 ../scripts/upload_document_local.py \
--region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--file /path/to/local/file.pdf见 scripts/upload_document_local.py。
轮询上传进度
aliyun gpdb get-upload-document-job \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--job-id "job-xxxxx" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops查看文档列表
aliyun gpdb list-documents \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops---
三、检索与问答
检索知识库
aliyun gpdb query-content \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace ns_my_knowledge_base \
--namespace-password '<namespace-password>' \
--collection my_knowledge_base \
--content "如何配置数据库参数?" \
--topk 10 \
--rerank-factor 5 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops知识库问答
aliyun gpdb chat-with-knowledge-base \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--model-params '{"Model":"qwen-max","Messages":[{"Role":"user","Content":"用户问题"}]}' \
--knowledge-params '{"SourceCollection":[{"Collection":"my_knowledge_base","Namespace":"ns_my_knowledge_base","NamespacePassword":"<namespace-password>","QueryParams":{"TopK":10}}]}' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops---
参考链接
| 文档 | 内容 |
|---|---|
| cli-installation-guide.md | CLI 安装指南 |
| ram-policies.md | RAM 权限清单 |
| related-apis.md | 相关 API 列表 |
| interaction-guidelines.md | 交互规范与最佳实践 |
| verification-method.md | 验证方法 |
| acceptance-criteria.md | 验收标准 |
| ../requirements.txt | scripts/ 的 Python 依赖 |
Verification Method - ADBPG Knowledge Base Management
This document describes how to verify that ADBPG Knowledge Base operations executed successfully.
Table of Contents
- 1. Environment Verification
- 2. Knowledge Base Management Verification
- 3. Document Management Verification
- 4. Search & Q&A Verification
- Common Error Troubleshooting
---
1. Environment Verification
1.1 CLI Version Verification
aliyun versionSuccess Criteria: Version >= 3.3.3
1.2 Credential Verification
aliyun configure listSuccess Criteria: Shows valid profile configuration
1.3 API Connectivity Verification
aliyun gpdb describe-regions --user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria: Returns region list JSON
---
2. Knowledge Base Management Verification
2.1 Initialize Vector Database
aliyun gpdb init-vector-database \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria:
- Returns
RequestId - No error messages
Verification Command: If the call succeeds, no extra verification; if the operation was already applied, expect an explicit API error—handle duplicate / already-exists per SKILL.md create pre-checks.
2.2 Create Namespace
aliyun gpdb create-namespace \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--namespace ns_test_kb \
--namespace-password '<namespace-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria:
- Returns
RequestId - No error messages
Verification Command: No direct namespace query API, verify through subsequent operations
2.3 Create Knowledge Base
aliyun gpdb create-document-collection \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--manager-account admin_user \
--manager-account-password '<manager-account-password>' \
--collection test_knowledge_base \
--embedding-model text-embedding-v4 \
--dimension 1024 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria:
- Returns
RequestId - No error messages
Verification Command:
aliyun gpdb list-document-collections \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace-password '<namespace-password>' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsVerification Criteria: Result contains test_knowledge_base
---
3. Document Management Verification
3.1 Upload Document
aliyun gpdb upload-document-async \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace-password '<namespace-password>' \
--collection test_knowledge_base \
--file-name "test.pdf" \
--file-url "https://example.com/test.pdf" \
--document-loader-name ADBPGLoader \
--chunk-size 500 \
--chunk-overlap 50 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria:
- Returns
JobId - Status is
runningorcompleted
Verification Command (poll progress):
aliyun gpdb get-upload-document-job \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace-password '<namespace-password>' \
--collection test_knowledge_base \
--job-id "job-xxxxx" \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsVerification Criteria:
StatusiscompletedProgressis100
3.2 List Documents
aliyun gpdb list-documents \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace-password '<namespace-password>' \
--collection test_knowledge_base \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria:
- Returns document list
- Contains uploaded document name
---
4. Search & Q&A Verification
4.1 Search Knowledge Base
aliyun gpdb query-content \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--namespace-password '<namespace-password>' \
--collection test_knowledge_base \
--content "test query" \
--topk 10 \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria:
- Returns
Matchesarray - Each result contains
ContentandScore
4.2 Knowledge Base Q&A
aliyun gpdb chat-with-knowledge-base \
--biz-region-id cn-hangzhou \
--db-instance-id gp-xxxxx \
--model-params '{"Model":"qwen-max","Messages":[{"Role":"user","Content":"test question"}]}' \
--knowledge-params '{"SourceCollection":[{"Collection":"test_knowledge_base","NamespacePassword":"<namespace-password>","TopK":10}]}' \
--user-agent AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-opsSuccess Criteria:
- Returns
Responsefield - Contains LLM-generated answer
---
Common Error Troubleshooting
| Error Code | Cause | Solution |
|---|---|---|
| InvalidAccessKeyId.NotFound | AK doesn't exist | Check AK configuration |
| SignatureDoesNotMatch | SK is incorrect | Check SK configuration |
| Instance.NotSupportVector | Instance doesn't support vector features | Upgrade instance or enable vector engine |
| role "knowledgebasepub" does not exist | Namespace not created | Execute CreateNamespace first |
| Collection.NotFound | Knowledge base doesn't exist | Check knowledge base name |
| Namespace.PasswordInvalid | Namespace password incorrect | Check if password is correct |
# Locked top-level dependencies for scripts/ (e.g. upload_document_local.py).
# Generated with: uv venv --python 3.12 .venv && uv pip install <packages> && pinned from `uv pip show`.
# To upgrade: recreate venv, reinstall latest, refresh pins, run py_compile / --help on the script.
alibabacloud-gpdb20160503==5.1.0
alibabacloud-credentials==1.0.8
alibabacloud-tea-openapi==0.4.4
alibabacloud-tea-util==0.3.14
alibabacloud-tea==0.4.3
#!/usr/bin/env python3
"""Upload a local file to an ADBPG knowledge base using upload_document_async_advance.
Uses the Alibaba Cloud Python SDK default credential chain (CredentialClient with no config).
Dependencies: see ../requirements.txt (skill root). Install:
pip install -r requirements.txt
"""
from __future__ import annotations
import argparse
import os
import re
import sys
from pathlib import Path
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_credentials.exceptions import CredentialException
from alibabacloud_gpdb20160503.client import Client
from alibabacloud_gpdb20160503 import models
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
from Tea.exceptions import TeaException, UnretryableException
USER_AGENT = "AlibabaCloud-Agent-Skills/alibabacloud-analyticdb-postgresql-knowledgebase-ops"
DEFAULT_TIMEOUT_MS = 10_000
_MAX_REGION_LEN = 64
_MAX_DB_INSTANCE_ID_LEN = 64
_MAX_NAME_LEN = 128
_MAX_PASSWORD_LEN = 256
_MAX_FILE_PATH_LEN = 4096
_MAX_ENDPOINT_LEN = 128
_MAX_LOADER_LEN = 64
_REGION_RE = re.compile(r"^[a-z]{2}-[a-z0-9-]+$")
_DB_INSTANCE_RE = re.compile(r"^gp-[a-zA-Z0-9]+$")
_NAME_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_-]*$")
_ENDPOINT_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9.-]*[a-zA-Z0-9]$|^[a-zA-Z0-9]$")
_LOADER_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9_-]*$")
def _err(msg: str) -> None:
print(msg, file=sys.stderr)
def validate_region_id(value: str) -> str | None:
if not value or len(value) > _MAX_REGION_LEN:
return "--region-id must be non-empty and within length limits."
if not _REGION_RE.match(value):
return "--region-id must match an Aliyun region id (e.g. cn-hangzhou)."
return None
def validate_db_instance_id(value: str) -> str | None:
if not value or len(value) > _MAX_DB_INSTANCE_ID_LEN:
return "--db-instance-id must be non-empty and within length limits."
if not _DB_INSTANCE_RE.match(value):
return "--db-instance-id must match gp-xxxxxx."
return None
def validate_namespace(value: str) -> str | None:
if not value or len(value) > _MAX_NAME_LEN:
return "--namespace must be non-empty and within length limits."
if not _NAME_RE.match(value):
return "--namespace must start with a letter; use only letters, digits, underscore, hyphen."
return None
def validate_collection(value: str) -> str | None:
if not value or len(value) > _MAX_NAME_LEN:
return "--collection must be non-empty and within length limits."
if not _NAME_RE.match(value):
return "--collection must start with a letter; use only letters, digits, underscore, hyphen."
return None
def validate_namespace_password(value: str) -> str | None:
if not value or len(value) > _MAX_PASSWORD_LEN:
return "--namespace-password length invalid."
if "\x00" in value:
return "--namespace-password must not contain NUL bytes."
if not value.isprintable():
return "--namespace-password must be printable ASCII/Unicode (no control characters)."
return None
def validate_endpoint(value: str) -> str | None:
if not value or len(value) > _MAX_ENDPOINT_LEN:
return "--endpoint invalid length."
if not _ENDPOINT_RE.match(value):
return "--endpoint must be a hostname (letters, digits, dots, hyphens)."
return None
def validate_document_loader_name(value: str) -> str | None:
if not value or len(value) > _MAX_LOADER_LEN:
return "--document-loader-name invalid length."
if not _LOADER_RE.match(value):
return "--document-loader-name must start with a letter; use letters, digits, underscore, hyphen."
return None
def validate_file_path(raw: str) -> str | None:
if not raw or len(raw) > _MAX_FILE_PATH_LEN:
return "--file path empty or too long."
if "\x00" in raw:
return "--file must not contain NUL bytes."
parts = Path(raw).parts
if ".." in parts:
return "--file must not contain path traversal (..)."
try:
p = Path(raw).expanduser()
_ = p.resolve()
except (OSError, ValueError):
return "--file is not a valid path on this system."
return None
def build_client(region_id: str, endpoint: str) -> Client:
return Client(
Config(
credential=CredentialClient(),
region_id=region_id,
endpoint=endpoint,
connect_timeout=DEFAULT_TIMEOUT_MS,
read_timeout=DEFAULT_TIMEOUT_MS,
user_agent=USER_AGENT,
)
)
def _format_api_error(exc: Exception) -> str:
if isinstance(exc, UnretryableException):
inner = getattr(exc, "inner_exception", None)
if isinstance(inner, TeaException):
return _format_api_error(inner)
if inner is not None:
return f"Request failed ({type(inner).__name__}): {inner}"
if isinstance(exc, TeaException):
parts = []
if exc.code:
parts.append(f"code={exc.code}")
if exc.message:
parts.append(exc.message)
if exc.data is not None:
parts.append(f"data={exc.data!r}")
body = "; ".join(parts) if parts else str(exc)
hint = (
"Check --region-id, --db-instance-id, --namespace, passwords, and RAM permissions; "
"verify network and endpoint reachability."
)
return f"API error ({body}). {hint}"
return f"{type(exc).__name__}: {exc}"
def main() -> int:
parser = argparse.ArgumentParser(
description="Upload a local file to an ADBPG DocumentCollection (async job)."
)
parser.add_argument("--region-id", default="cn-hangzhou")
parser.add_argument("--db-instance-id", required=True)
parser.add_argument("--namespace", required=True)
parser.add_argument("--namespace-password", required=True)
parser.add_argument("--collection", required=True)
parser.add_argument("--file", dest="file_path", required=True, help="Path to local file")
parser.add_argument("--document-loader-name", default="ADBPGLoader")
parser.add_argument("--chunk-size", type=int, default=500)
parser.add_argument("--chunk-overlap", type=int, default=50)
parser.add_argument("--endpoint", default="gpdb.aliyuncs.com")
args = parser.parse_args()
checks = [
validate_region_id(args.region_id),
validate_db_instance_id(args.db_instance_id),
validate_namespace(args.namespace),
validate_collection(args.collection),
validate_namespace_password(args.namespace_password),
validate_endpoint(args.endpoint),
validate_document_loader_name(args.document_loader_name),
validate_file_path(args.file_path),
]
for msg in checks:
if msg:
_err(msg)
return 2
if args.chunk_size < 1 or args.chunk_size > 1_000_000:
_err("--chunk-size must be between 1 and 1000000.")
return 2
if args.chunk_overlap < 0 or args.chunk_overlap > args.chunk_size:
_err("--chunk-overlap must be >= 0 and <= --chunk-size.")
return 2
path = args.file_path
if not os.path.isfile(path):
_err(
"Not a file or path does not exist (after validation). "
"Pass a readable file path with --file."
)
return 2
try:
client = build_client(args.region_id, args.endpoint)
with open(path, "rb") as fh:
request = models.UploadDocumentAsyncAdvanceRequest(
region_id=args.region_id,
dbinstance_id=args.db_instance_id,
namespace=args.namespace,
namespace_password=args.namespace_password,
collection=args.collection,
file_name=os.path.basename(path),
file_url_object=fh,
document_loader_name=args.document_loader_name,
chunk_size=args.chunk_size,
chunk_overlap=args.chunk_overlap,
)
runtime = RuntimeOptions(
connect_timeout=DEFAULT_TIMEOUT_MS,
read_timeout=DEFAULT_TIMEOUT_MS,
)
response = client.upload_document_async_advance(request, runtime)
except FileNotFoundError:
_err("File not found after open. Check --file.")
return 2
except PermissionError:
_err("Permission denied reading file. Fix filesystem permissions or choose another path.")
return 2
except OSError as e:
_err(f"Cannot read file: {type(e).__name__}. Check path and permissions.")
return 2
except CredentialException:
_err(
"Credential resolution failed. Configure the default credential chain outside this session "
"(for example `aliyun configure` or env-based setup per Alibaba Cloud docs), then retry. "
"Do not paste secrets into logs."
)
return 3
except UnretryableException as e:
_err(_format_api_error(e))
return 4
except TeaException as e:
_err(_format_api_error(e))
return 4
except Exception as e:
msg_l = str(e).lower()
if "timeout" in msg_l or "timed out" in msg_l:
_err(
"Network or timeout error. Check connectivity, firewall, and try again; "
"increase timeouts in this script if uploads are large."
)
return 5
_err(f"Unexpected error: {type(e).__name__}. Retry or enable verbose logging outside production.")
return 1
print(f"JobId: {response.body.job_id}")
return 0
if __name__ == "__main__":
sys.exit(main())