快速開始
這份指南會帶你在 5 分鐘內完成第一個 Vecstruct API 呼叫。
前置準備
你需要:
- 一個 Vecstruct 帳號
- 一組 API Key — 如何取得?
設定環境變數
把 API Key 存成環境變數,不要寫死在程式裡:
- Shell / CLI
- Node.js
- Python
- Go
export VECSTRUCT_API_KEY="sk-your-api-key-here"
Windows(命令提示字元):
set VECSTRUCT_API_KEY=sk-your-api-key-here
安裝 dotenv:
npm install dotenv
在專案根目錄建立 .env:
VECSTRUCT_API_KEY=sk-your-api-key-here
在程式最頂端載入(CommonJS):
require('dotenv').config();
或 ESM 版本:
import 'dotenv/config';
安裝 python-dotenv:
pip install python-dotenv
在專案根目錄建立 .env:
VECSTRUCT_API_KEY=sk-your-api-key-here
在程式開頭載入:
from dotenv import load_dotenv
load_dotenv()
安裝 godotenv:
go get github.com/joho/godotenv
在專案根目錄建立 .env:
VECSTRUCT_API_KEY=sk-your-api-key-here
在程式開頭載入:
import "github.com/joho/godotenv"
func main() {
godotenv.Load() // 讀取 .env 檔(生產環境直接設系統環境變數即可)
// ...
}
:::tip 安全提醒
記得把 .env 加入 .gitignore,避免 API Key 被提交到版本控制系統。
:::
你的第一個 Chat 請求
Vecstruct AI Gateway 完全相容 OpenAI API 格式,只要替換 base_url 和 api_key。
- Node.js
- Python
- Go
使用 OpenAI SDK(相容格式)
npm install openai dotenv
import 'dotenv/config';
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.VECSTRUCT_API_KEY,
baseURL: 'https://api.vecstruct.com/v1',
});
const reply = await client.chat.completions.create({
model: 'openai/gpt-4o',
messages: [{ role: 'user', content: '你好,介紹一下自己' }],
});
console.log(reply.choices[0].message.content);
使用 Vecstruct SDK
npm install @vecstruct/sdk dotenv
import 'dotenv/config';
import { Vecstruct } from '@vecstruct/sdk';
const client = new Vecstruct({
apiKey: process.env.VECSTRUCT_API_KEY,
});
const reply = await client.chat.completions.create({
model: 'openai/gpt-4o',
messages: [{ role: 'user', content: '你好,介紹一下自己' }],
});
console.log(reply.choices[0].message.content);
使用 OpenAI SDK(相容格式)
pip install openai python-dotenv
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI(
api_key=os.environ["VECSTRUCT_API_KEY"],
base_url="https://api.vecstruct.com/v1",
)
reply = client.chat.completions.create(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "你好,介紹一下自己"}],
)
print(reply.choices[0].message.content)
使用 Vecstruct SDK
pip install vecstruct python-dotenv
import asyncio
import os
from dotenv import load_dotenv
from vecstruct import AsyncVecstruct
load_dotenv()
async def main():
async with AsyncVecstruct(api_key=os.environ["VECSTRUCT_API_KEY"]) as client:
reply = await client.chat.completions.create(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "你好,介紹一下自己"}],
)
print(reply["choices"][0]["message"]["content"])
asyncio.run(main())
使用 OpenAI SDK(相容格式)
go get github.com/sashabaranov/go-openai
go get github.com/joho/godotenv
package main
import (
"context"
"fmt"
"log"
"os"
openai "github.com/sashabaranov/go-openai"
"github.com/joho/godotenv"
)
func main() {
godotenv.Load()
cfg := openai.DefaultConfig(os.Getenv("VECSTRUCT_API_KEY"))
cfg.BaseURL = "https://api.vecstruct.com/v1"
client := openai.NewClientWithConfig(cfg)
resp, err := client.CreateChatCompletion(context.Background(), openai.ChatCompletionRequest{
Model: "openai/gpt-4o",
Messages: []openai.ChatCompletionMessage{
{Role: openai.ChatMessageRoleUser, Content: "你好,介紹一下自己"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Choices[0].Message.Content)
}
使用 Vecstruct SDK
go get github.com/vecstruct/vecstruct-sdk-go
go get github.com/joho/godotenv
package main
import (
"context"
"fmt"
"log"
"os"
vecstruct "github.com/vecstruct/vecstruct-sdk-go"
"github.com/joho/godotenv"
)
func main() {
godotenv.Load()
client, err := vecstruct.NewClient(os.Getenv("VECSTRUCT_API_KEY"))
if err != nil {
log.Fatal(err)
}
resp, err := client.CreateChatCompletion(context.Background(), vecstruct.ChatCompletionRequest{
Model: "openai/gpt-4o",
Messages: []vecstruct.ChatMessage{
{Role: "user", Content: "你好,介紹一下自己"},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Choices[0].Message.Content)
}
加入 RAG 知識庫查詢
如果你的 API Key 有綁定專案,只要加上 vecstruct 參數就能啟用知識庫查詢:
- Node.js
- Python
- Go
const reply = await client.chat.completions.create({
model: 'openai/gpt-4o',
messages: [{ role: 'user', content: '你們的退貨政策是什麼?' }],
vecstruct: {
rag: true, // 開啟 RAG,AI 會根據你上傳的文件回答
rag_top_k: 5, // 參考最相關的 5 個文件段落
},
});
// 查看 AI 引用了哪些文件段落
for (const src of reply.vecstruct.rag_sources) {
console.log(`來源: ${src.title} (相似度: ${src.similarity.toFixed(2)})`);
}
reply = await client.chat.completions.create(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "你們的退貨政策是什麼?"}],
vecstruct={
"rag": True,
"rag_top_k": 5,
},
)
# 查看引用來源
for src in reply["vecstruct"]["rag_sources"]:
print(f"來源: {src['title']} (相似度: {src['similarity']:.2f})")
ragOn := true
resp, err := client.CreateChatCompletion(ctx, vecstruct.ChatCompletionRequest{
Model: "openai/gpt-4o",
Messages: []vecstruct.ChatMessage{
{Role: "user", Content: "你們的退貨政策是什麼?"},
},
Vecstruct: &vecstruct.VecstructParams{
RAG: &ragOn,
RAGTopK: 5,
},
})
for _, src := range resp.Vecstruct.RAGSources {
fmt.Printf("來源: %s (相似度: %.2f)\n", src.Title, src.Similarity)
}
下一步
- 取得 API Key — 建立並管理 API Key
- AI Gateway — 深入了解模型選擇和進階用法
- RAG 知識庫 — 上傳文件,讓 AI 根據你的資料回答
- SDK 文件 — 各語言 SDK 的完整說明