ainative-chat-completions

Help agents build conversational AI with AINative's Chat Completions API. Use when (1) Building a chatbot or AI assistant, (2) Implementing streaming responses, (3) Using function/tool calling, (4) Tracking credit usage per request, (5) Choosing between streaming and non-streaming. Covers raw API, Python SDK, React SDK, and Next.js patterns. Closes

Safety Notice

This listing is from the official public ClawHub registry. Review SKILL.md and referenced scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "ainative-chat-completions" with this command: npx skills add urbantech/ainative-chat-completions

AINative Chat Completions

Endpoint

POST https://api.ainative.studio/v1/public/chat/completions

Auth: X-API-Key: ak_... or Authorization: Bearer <jwt>

Basic Request

import requests

response = requests.post(
    "https://api.ainative.studio/v1/public/chat/completions",
    headers={"X-API-Key": "ak_your_key"},
    json={
        "model": "claude-3-5-sonnet-20241022",
        "messages": [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "What is ZeroDB?"}
        ],
        "temperature": 0.7,
        "max_tokens": 1024
    }
)
data = response.json()
print(data["choices"][0]["message"]["content"])
print(f"Tokens used: {data['usage']['total_tokens']}")

Streaming (SSE)

import requests

with requests.post(
    "https://api.ainative.studio/v1/public/chat/completions",
    headers={"X-API-Key": "ak_your_key"},
    json={"model": "claude-3-5-sonnet-20241022",
          "messages": [{"role": "user", "content": "Count to 5"}],
          "stream": True},
    stream=True
) as resp:
    for line in resp.iter_lines():
        if line and line.startswith(b"data: "):
            chunk = line[6:]
            if chunk != b"[DONE]":
                import json
                delta = json.loads(chunk)["choices"][0]["delta"]
                print(delta.get("content", ""), end="", flush=True)

React SDK — useChat Hook

npm install @ainative/react-sdk
import { AINativeProvider, useChat } from '@ainative/react-sdk';

function App() {
  return (
    <AINativeProvider config={{ apiKey: 'ak_your_key' }}>
      <ChatComponent />
    </AINativeProvider>
  );
}

function ChatComponent() {
  const { messages, sendMessage, isLoading, error } = useChat({
    model: 'claude-3-5-sonnet-20241022',
    systemPrompt: 'You are a helpful assistant.',
  });

  const handleSend = () => sendMessage('Hello!');

  return (
    <div>
      {messages.map((msg, i) => (
        <div key={i}><b>{msg.role}:</b> {msg.content}</div>
      ))}
      <button onClick={handleSend} disabled={isLoading}>
        {isLoading ? 'Thinking...' : 'Send'}
      </button>
      {error && <p>Error: {error.message}</p>}
    </div>
  );
}

Next.js — Server Action + Streaming

npm install @ainative/next-sdk
// app/api/chat/route.ts
import { createServerClient } from '@ainative/next-sdk/server';

export async function POST(request: Request) {
  const { messages } = await request.json();
  const client = createServerClient({ apiKey: process.env.AINATIVE_API_KEY! });

  const stream = await client.chat.completions.create({
    model: 'claude-3-5-sonnet-20241022',
    messages,
    stream: true,
  });

  return new Response(stream.body, {
    headers: { 'Content-Type': 'text/event-stream' }
  });
}

Available Models

ModelContextBest For
claude-3-5-sonnet-20241022200kGeneral purpose (default)
claude-3-5-haiku-20241022200kFast, low cost
claude-3-opus-20240229200kComplex reasoning
gpt-4o128kOpenAI fallback

Request Parameters

ParameterTypeDefaultDescription
modelstringrequiredModel ID
messagesarrayrequiredConversation history
streambooleanfalseEnable SSE streaming
temperaturefloat0.7Randomness (0-1)
max_tokensint1024Max response length
systemstringSystem prompt (alternative)

Credit Costs

Credits are consumed per token. Check balance before high-volume usage:

balance = requests.get(
    "https://api.ainative.studio/api/v1/public/credits/balance",
    headers={"X-API-Key": "ak_your_key"}
).json()
print(f"Remaining: {balance['remaining_credits']}")

Error Handling

StatusMeaningAction
401Invalid API keyCheck key format: ak_...
402Insufficient creditsTop up or upgrade plan
429Rate limitBack off, retry with exponential delay
503Model unavailableRetry or use fallback model

References

  • docs/api/CHAT_COMPLETION_API_REFERENCE.md (757 lines — full spec)
  • src/backend/app/api/v1/endpoints/managed_chat.py
  • packages/sdks/react/src/hooks/useChat.ts
  • packages/sdks/nextjs/src/

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Automation

Verified Agent Identity

Billions decentralized identity for agents. Link agents to human identities using Billions ERC-8004 and Attestation Registries. Verify and generate authentic...

Registry SourceRecently Updated
15.4K41obrezhniev
Automation

挑选Skill

挑选Skill — 哪个AI Skill值得装?AI Skill生态的消费决策指南。覆盖58赛道、29000+ Skill,双轨评分(热度分给人类 + 质量分给Agent),提供搜索推荐、相似替代、工作流建议和13维质量分析。

Registry SourceRecently Updated
00Profile unavailable
Automation

挑选Skill

挑选Skill — 哪个AI Skill值得装?AI Skill生态的消费决策指南。覆盖58赛道、29000+ Skill,双轨评分(热度分给人类 + 质量分给Agent),提供搜索推荐、相似替代、工作流建议和13维质量分析。

Registry SourceRecently Updated
Automation

Agent Memory System v8

Agent 记忆系统 — 6维坐标编码 + RRF双路检索 + sqlite-vec统一存储 + 写入时因果检测 + 多Agent共享 + 记忆蒸馏 + 时间旅行 + 情感编码 + 元认知 + 内在动机 + 叙事自我 + 数字孪生 + 角色模板

Registry SourceRecently Updated