<span id="管理连接器"></span>

# Manage Connectors

Use the AI Studio SDK to list connectors in a workspace, validate external connectivity before creating a new connector, and update or delete existing connectors by ID. Creating a connector saves connection metadata only and does not start data import or export.

(sdk-ai-studio-connector-flow)=
<span id="任务流程"></span>

## Task flow

Connector management covers listing existing connectors, validating external connectivity, creating and confirming a connector, and updating or deleting it later. The connector ID returned upon creation serves as the input for source inspection and import or export tasks.

```text
Workspace Connector Service
          │
          ├── List existing connectors ──▶ Obtain connector ID, source type, and status
          │
          └── External settings ──▶ Validate connectivity ──▶ Create and read back connector
                                                                          │
                                                                          ▼
                                                             Update or delete by connector ID
```

(sdk-ai-studio-connector-list-prepare)=
<span id="准备"></span>

## Prerequisites

1. Complete the endpoint, personal access token, and workspace setup in [Use the SDK](../../../quickstart/ai-studio/sdk.md).
2. **External endpoint and credentials** (when creating or updating a connector): obtain them from the external system administrator and verify that the endpoint is reachable from the AI Studio service network. The creation example below configures a Dify knowledge-base export connector: a Dify workspace owner or administrator must create a key under **Knowledge > Service API > API Key** with permission to list all knowledge bases, and copy the API base URL from the same panel (including the API prefix such as `/v1`, omitting `/datasets`).
3. **Connector name** (when creating a connector): choose a name not yet used in the target workspace.

Before running the Dify validation and creation steps below, set the following environment variables:

```bash
export CONNECTOR_NAME='dify-export-demo'
export DIFY_API_URL='<API base URL shown in Dify>'
export DIFY_API_KEY='<Dify knowledge-base API key>'
```

(sdk-ai-studio-connector-list)=
<span id="列出工作区连接器"></span>

## List workspace connectors

List connectors visible in the current workspace to obtain their IDs, names, source types, usage types, and current statuses for downstream sampling or transfer tasks.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
import os

import moi_product_sdk as sdk

client = sdk.new_with_personal_access_token(
    os.environ["PRODUCT_API_BASE_URL"],
    os.environ["PRODUCT_API_KEY"],
)
workspace = client.workspace(os.environ["WORKSPACE_ID"])

listed = workspace.connectors().list()
for item in listed.connectors:
    print(item.id, item.name, item.source_type, list(item.usage_type), item.status)
```

::::

::::{tab-item} Go
:sync: go

```go
package main

import (
	"context"
	"fmt"
	"os"

	sdk "github.com/matrixorigin/matrixflow/sdk/go-sdk"
)

func main() {
	ctx := context.Background()
	client, err := sdk.NewWithPersonalAccessToken(
		os.Getenv("PRODUCT_API_BASE_URL"),
		os.Getenv("PRODUCT_API_KEY"),
	)
	if err != nil {
		panic(err)
	}
	workspace, err := client.Workspace(os.Getenv("WORKSPACE_ID"))
	if err != nil {
		panic(err)
	}

	listed, err := workspace.Connectors().List(ctx)
	if err != nil {
		panic(err)
	}
	for _, item := range listed.GetConnectors() {
		fmt.Println(item.GetId(), item.GetName(), item.GetSourceType(), item.GetUsageType(), item.GetStatus())
	}
}
```

::::

:::::

(sdk-ai-studio-connector-validate)=
<span id="校验连接配置"></span>

## Validate a connection configuration

Before creating a connector, submit the configuration to verify connectivity. In this example, the source type is `6` (Dify) and the usage type is `2` (export; `1` indicates import and `3` indicates both, whereas Dify connectors support export only). Validation succeeds when the server queries Dify's knowledge-base list with the supplied key and receives HTTP 200.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
name = os.environ["CONNECTOR_NAME"]
config = {
    "dify": {
        "api_url": os.environ["DIFY_API_URL"].rstrip("/"),
        "api_key": os.environ["DIFY_API_KEY"],
    }
}
source_type, usage_type = 6, 2  # Dify, export

validation = workspace.connectors().validate(
    name,
    source_type,
    usage_type,
    sdk.with_connector_config(config),
)
if not validation.HasField("valid") or not validation.valid:
    raise RuntimeError("Validation failed; check the Dify endpoint, key, permissions, and network")
print("Dify connectivity validation passed")
```

::::

::::{tab-item} Go
:sync: go

```go
// Include "strings" in the import block above
name := os.Getenv("CONNECTOR_NAME")
config := map[string]any{
	"dify": map[string]any{
		"api_url": strings.TrimRight(os.Getenv("DIFY_API_URL"), "/"),
		"api_key": os.Getenv("DIFY_API_KEY"),
	},
}
const sourceType, usageType = 6, 2 // Dify, export

validation, err := workspace.Connectors().Validate(
	ctx,
	name,
	sourceType,
	usageType,
	sdk.WithConnectorConfig(config),
)
if err != nil {
	panic(err)
}
if validation.Valid == nil || !validation.GetValid() {
	panic("Validation failed; check the Dify endpoint, key, permissions, and network")
}
fmt.Println("Dify connectivity validation passed")
```

::::

:::::

(sdk-ai-studio-connector-confirm)=
<span id="创建并确认连接器"></span>

## Create and confirm a connector

After validation passes, create the connector in the workspace with the same configuration and read back its details through the returned handle to verify the connector ID, name, source type, and status. Creating a duplicate name in the same workspace returns an error; if the read-back step encounters a network error, check the connector list before submitting another creation request.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
connector, created = workspace.create_connector(
    name,
    source_type,
    usage_type,
    sdk.with_connector_config(config),
)
info = connector.info()
print(created.id, info.name, info.source_type, list(info.usage_type), info.status)
```

::::

::::{tab-item} Go
:sync: go

```go
connector, created, err := workspace.CreateConnector(
	ctx,
	name,
	sourceType,
	usageType,
	sdk.WithConnectorConfig(config),
)
if err != nil {
	panic(err)
}
info, err := connector.Info(ctx)
if err != nil {
	panic(err)
}
fmt.Println(created.GetId(), info.GetName(), info.GetSourceType(), info.GetUsageType(), info.GetStatus())
```

::::

:::::

(sdk-ai-studio-connector-update)=
(sdk-ai-studio-connector-delete)=
<span id="更新或删除连接器"></span>

## Update or delete a connector

To rename an existing connector or rotate external credentials, bind a handle by connector ID and submit an update. When a connector is no longer needed and has no active import or export tasks, delete it through the same handle.

:::::{tab-set}
:sync-group: sdk-language

::::{tab-item} Python
:sync: python

```python
existing = workspace.connector(created.id)
existing.update(sdk.with_connector_name("dify-export-prod"))

# Delete only after confirming no import or export tasks depend on this connector
# existing.delete()
```

::::

::::{tab-item} Go
:sync: go

```go
existing, err := workspace.Connector(created.GetId())
if err != nil {
	panic(err)
}
if err := existing.Update(ctx, sdk.WithConnectorName("dify-export-prod")); err != nil {
	panic(err)
}

// Delete only after confirming no import or export tasks depend on this connector
// if err := existing.Delete(ctx); err != nil {
// 	panic(err)
// }
```

::::

:::::

(sdk-ai-studio-connector-next)=
<span id="下一步"></span>

## Next steps

- [Check Data Sources and Read Samples](检查数据源与采样.md)
- [Create Import and Export Tasks](创建导入导出任务.md)
