跳至主要内容

快速開始

這份指南會帶你在 5 分鐘內完成第一個 Vecstruct API 呼叫。

前置準備

你需要:

  1. 一個 Vecstruct 帳號
  2. 一組 API Key — 如何取得?

設定環境變數

把 API Key 存成環境變數,不要寫死在程式裡:

export VECSTRUCT_API_KEY="sk-your-api-key-here"

Windows(命令提示字元):

set VECSTRUCT_API_KEY=sk-your-api-key-here

:::tip 安全提醒 記得把 .env 加入 .gitignore,避免 API Key 被提交到版本控制系統。 :::


你的第一個 Chat 請求

Vecstruct AI Gateway 完全相容 OpenAI API 格式,只要替換 base_urlapi_key

使用 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);

加入 RAG 知識庫查詢

如果你的 API Key 有綁定專案,只要加上 vecstruct 參數就能啟用知識庫查詢:

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)})`);
}

下一步