Use @ainative/svelte-sdk to add AI chat to Svelte/SvelteKit apps. Use when (1) Installing @ainative/svelte-sdk, (2) Using Svelte stores for chat state, (3) Configuring AINative in a Svelte app, (4) Displaying chat messages reactively, (5) Handling loading and error states with Svelte stores. Published npm package v1.0.0.
用于AINative聊天补全的Svelte存储和工具。
bash
npm install @ainative/svelte-sdk
typescript
// src/lib/ainative.ts
import { setAINativeConfig } from @ainative/svelte-sdk;
setAINativeConfig({
apiKey: import.meta.env.VITEAINATIVEAPI_KEY,
baseUrl: https://api.ainative.studio,
});
在应用根目录(+layout.svelte 或 App.svelte)中调用一次。
svelte
{#each $chat.messages as msg}
{#if $chat.isLoading}
思考中...
{#if $chat.error}
错误: {$chat.error.message}
e.key === Enter && send()} />
$chat 是一个响应式存储,具有以下结构:
| 字段 | 类型 | 描述 |
|---|---|---|
| messages | Message[] | 完整对话历史 |
| isLoading |
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| model | string | — | 模型 ID |
| initialMessages |
对于服务器端调用,直接使用原始 API(不暴露浏览器认证信息):
typescript
// src/routes/api/chat/+server.ts
import { AINATIVEAPIKEY } from $env/static/private;
import type { RequestHandler } from ./$types;
export const POST: RequestHandler = async ({ request }) => {
const { messages } = await request.json();
const resp = await fetch(https://api.ainative.studio/v1/public/chat/completions, {
method: POST,
headers: {
X-API-Key: AINATIVEAPIKEY,
Content-Type: application/json,
},
body: JSON.stringify({
model: claude-3-5-sonnet-20241022,
messages,
}),
});
return new Response(resp.body, {
headers: { Content-Type: application/json },
});
};
bash
生产环境请使用服务器路由 — 切勿在客户端包中暴露 API 密钥。
typescript
import {
createChatStore,
setAINativeConfig,
ainativeConfig,
type Message,
type ChatState,
type AINativeError,
} from @ainative/svelte-sdk;
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 ainative-svelte-sdk-1776060301 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 ainative-svelte-sdk-1776060301 技能
skillhub install ainative-svelte-sdk-1776060301
文件大小: 2.22 KB | 发布时间: 2026-4-14 10:42