Let's Start with the Failed Approaches
Before describing the right approach, I want to review a few typical failure stories first. Indie developers and small teams most easily fall into the following traps, and often only realize how serious the problem is late in the project.
Trap 1: Writing API calls directly inside components. Many people's first instinct after getting an API Key is to fetch directly in the Chat.vue component, hardcoding the URL, Key, and model name. Two weeks after launch, when they want to switch models, add retry logic, or add multi-turn conversation memory, they discover the component has grown into a plate of spaghetti — every call site needs to be modified.
Trap 2: Exposing the Key naked in the frontend. For convenience, the API Key is placed directly in frontend code and shipped in the bundle. This looks fine during the demo stage, but as soon as the page is publicly accessible, the Key is essentially given away. At best your quota gets drained; at worst the bill spirals out of control. Even if your app is just an internal tool, this habit will eventually come back to bite you.
Trap 3: Locking into a single vendor's proprietary protocol. Directly using a specific model's dedicated SDK and private parameter format creates deep coupling. When you need to switch models or run comparison tests, the entire calling layer has to be torn down and rewritten, and all the streaming parsing logic in your components is wasted.
The correct path boils down to one sentence: frontend components are only responsible for interaction; the calling logic converges into a well-encapsulated service layer, which then accesses models through a unified gateway. Below, we'll walk through the complete process using a unified gateway like ThisToken.AI as an example.
Step 1: Register an Account and Get an API Key
- Open the ThisToken.AI website, go to the registration page, and register with your email (regarding pricing models and plans, refer to the official pricing page — this article won't cover that).
- After logging in, go to the console, find the API Key management page, and create a new Key.
- Immediately copy the Key and save it in a secure location, and make sure it only exists in server-side environment variables — it must never end up in frontend build artifacts.
The benefit of a unified gateway: the interface follows the OpenAI-compatible style, so you only need one base_url to use different models under the same protocol — switching requires changing just one model name string.
Step 2: Get Your First Piece of Code Running
First, use minimal code to verify the Key and gateway connectivity. It's recommended to test locally with Python first (Node.js works too — same idea):
from openai import OpenAI
client = OpenAI(
api_key="你的_API_KEY", # 生产环境请从环境变量读取
base_url="https://api.thistoken.ai/v1"
)
response = client.chat.completions.create(
model="gpt-4o-mini", # 模型名以网关文档支持的列表为准
messages=[
{"role": "system", "content": "你是一个简洁的中文助手。"},
{"role": "user", "content": "用一句话介绍 Vue3 的组合式 API"}
],
stream=False
)
print(response.choices[0].message.content)If this code runs, it means the account, Key, gateway, and model name are all fine. If it doesn't, check three things first: whether the Key was copied in full, whether the base_url ends with /v1, and whether the model name is in the gateway's supported list.
Step 3: Encapsulate a Service Layer (Instead of Stuffing It into Components)
Once it runs, encapsulate the calling logic into a standalone module, e.g., src/services/ai.js:
// src/services/ai.js
// 注意:生产环境应经由你自己的后端转发请求,避免在前端暴露 Key
const BASE_URL = 'https://api.thistoken.ai/v1'
export async function sendChat(messages, { model, signal } = {}) {
const res = await fetch(`${BASE_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${import.meta.env.VITE_AI_KEY}`
},
body: JSON.stringify({ model, messages, stream: true }),
signal
})
if (!res.ok) throw new Error(`网关返回 ${res.status}`)
return res.body // 返回流,交给组件逐块解析
}Then encapsulate a reusable AiChat component: input box, message list, loading state, and abort button, with the message array and streaming append rendering managed internally by a useAiChat() composable. This way, when you change pages or projects, the component can be moved over directly without touching a single line of the calling layer.
A Few Practical Tips
- The Key's final home is the backend. The frontend calls your backend, and the backend holds the Key to call the gateway. This is the only secure arrangement — the simplified approach above is only suitable for local development.
- Handle retries and timeouts uniformly in the service layer; components should only consume results, not each implement their own version.
- Make the model name a configuration item — switching models is just changing one string, which is exactly the biggest value of a unified gateway.
Once you complete these three steps, you'll have a portable chat component and a clean integration layer. If you haven't registered yet, you can start right here: https://api.thistoken.ai/register
---
Tired of juggling provider integrations? Register at https://api.thistoken.ai/register and call every model through one base_url.
Vous voulez essayer Token.AI ?
Créez une API Key au niveau du projet, activez les canaux dans la console et configurez le routage, les budgets et les journaux d'audit.
注册 ThisToken.AI 并获取 API Key