Loading...
Loading...
Compare original and translation side by side
from subconscious import Subconscious
client = Subconscious(api_key="your-api-key") # Get from https://subconscious.dev/platform
run = client.run(
engine="tim-gpt",
input={
"instructions": "Research quantum computing breakthroughs in 2025",
"tools": [] # Optional: see Tools section below
},
options={"await_completion": True}
)from subconscious import Subconscious
client = Subconscious(api_key="your-api-key") # Get from https://subconscious.dev/platform
run = client.run(
engine="tim-gpt",
input={
"instructions": "Research quantum computing breakthroughs in 2025",
"tools": [] # Optional: see Tools section below
},
options={"await_completion": True}
)undefinedundefinedimport { Subconscious } from "subconscious";
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const run = await client.run({
engine: "tim-gpt",
input: {
instructions: "Research quantum computing breakthroughs in 2025",
tools: [], // Optional: see Tools section below
},
options: { awaitCompletion: true },
});
// Extract the answer for display
const answer = run.result?.answer; // Clean text response
console.log(answer);import { Subconscious } from "subconscious";
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const run = await client.run({
engine: "tim-gpt",
input: {
instructions: "Research quantum computing breakthroughs in 2025",
tools: [], // Optional: see Tools section below
},
options: { awaitCompletion: true },
});
// Extract the answer for display
const answer = run.result?.answer; // Clean text response
console.log(answer);{
runId: "run_abc123...",
status: "succeeded",
result: {
answer: "The clean text response for display", // ← Use this for chat UIs
reasoning: [ // Optional: step-by-step reasoning
{
title: "Step 1",
thought: "I need to search for...",
conclusion: "Found relevant information"
}
]
},
usage: {
inputTokens: 1234,
outputTokens: 567,
durationMs: 45000
}
}run.result?.answerreasoning{
runId: "run_abc123...",
status: "succeeded",
result: {
answer: "The clean text response for display", // ← Use this for chat UIs
reasoning: [ // Optional: step-by-step reasoning
{
title: "Step 1",
thought: "I need to search for...",
conclusion: "Found relevant information"
}
]
},
usage: {
inputTokens: 1234,
outputTokens: 567,
durationMs: 45000
}
}run.result?.answerreasoningfrom subconscious import Subconscious
client = Subconscious(api_key="your-api-key")from subconscious import Subconscious
client = Subconscious(api_key="your-api-key")undefinedundefinedimport { Subconscious } from "subconscious";
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const messages = [
{ role: "user", content: "Hello!" },
{ role: "assistant", content: "Hi there! How can I help?" },
{ role: "user", content: "Tell me about quantum computing" }
];
// Convert to instructions string
const instructions = messages
.map(m => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`)
.join("\n\n") + "\n\nRespond to the user's latest message.";
const run = await client.run({
engine: "tim-gpt",
input: { instructions, tools: [] },
options: { awaitCompletion: true },
});
console.log(run.result?.answer); // Clean text responseimport { Subconscious } from "subconscious";
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const messages = [
{ role: "user", content: "Hello!" },
{ role: "assistant", content: "Hi there! How can I help?" },
{ role: "user", content: "Tell me about quantum computing" }
];
// Convert to instructions string
const instructions = messages
.map(m => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`)
.join("\n\n") + "\n\nRespond to the user's latest message.";
const run = await client.run({
engine: "tim-gpt",
input: { instructions, tools: [] },
options: { awaitCompletion: true },
});
console.log(run.result?.answer); // Clean text responseinstructionsmessagesmessages: [{role: "user", content: "..."}]input: {instructions: "..."}instructionsmessagesmessages: [{role: "user", content: "..."}]input: {instructions: "..."}function buildInstructions(
systemPrompt: string,
messages: Array<{role: string; content: string}>
): string {
const conversation = messages
.map(m => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`)
.join("\n\n");
return `${systemPrompt}function buildInstructions(
systemPrompt: string,
messages: Array<{role: string; content: string}>
): string {
const conversation = messages
.map(m => `${m.role === "user" ? "User" : "Assistant"}: ${m.content}`)
.join("\n\n");
return `${systemPrompt}undefinedundefinedsystemconst systemPrompt = "You are a helpful assistant. Always be concise.";
const userMessage = "Explain quantum computing";
const instructions = `${systemPrompt}
User: ${userMessage}
Respond to the user's message.`;systemconst systemPrompt = "You are a helpful assistant. Always be concise.";
const userMessage = "Explain quantum computing";
const instructions = `${systemPrompt}
User: ${userMessage}
Respond to the user's message.`;| Engine | API Name | Type | Best For |
|---|---|---|---|
| TIM | | Unified | Flagship unified agent engine for a wide range of tasks |
| TIM-Edge | | Unified | Speed, efficiency, search-heavy tasks |
| TIMINI | | Compound (Gemini-3 Flash backed) | Long-context and tool use, strong reasoning |
| TIM-GPT | | Compound (GPT-4.1 backed) | Most use cases, good balance of cost/performance |
| TIM-GPT-Heavy | | Compound (GPT-5.2 backed) | Maximum capability, complex reasoning |
tim-gpt| 引擎 | API名称 | 类型 | 最佳适用场景 |
|---|---|---|---|
| TIM | | 统一型 | 适用于广泛任务的旗舰统一Agent引擎 |
| TIM-Edge | | 统一型 | 追求速度、效率和搜索密集型任务 |
| TIMINI | | 复合型(基于Gemini-3 Flash) | 长上下文和工具调用场景,推理能力强 |
| TIM-GPT | | 复合型(基于GPT-4.1) | 大多数使用场景,成本与性能平衡 |
| TIM-GPT-Heavy | | 复合型(基于GPT-5.2) | 最大能力,适用于复杂推理任务 |
tim-gpttools = [
{
"type": "function",
"name": "SearchTool",
"description": "a general search engine returns title, url, and description of 10 webpages",
"url": "https://your-server.com/search", # YOUR hosted endpoint
"method": "POST",
"timeout": 10, # seconds
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "A natural language query for the search engine."
}
},
"required": ["query"],
"additionalProperties": False
}
}
]urlmethodtimeouttools = [
{
"type": "function",
"name": "SearchTool",
"description": "a general search engine returns title, url, and description of 10 webpages",
"url": "https://your-server.com/search", # YOUR hosted endpoint
"method": "POST",
"timeout": 10, # seconds
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "A natural language query for the search engine."
}
},
"required": ["query"],
"additionalProperties": False
}
}
]urlmethodtimeoutfrom fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class SearchRequest(BaseModel):
query: str
@app.post("/search")
async def search(req: SearchRequest):
# Your search logic here
return {
"results": [
{"title": "Result 1", "url": "https://example.com/1", "description": "..."}
]
}from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class SearchRequest(BaseModel):
query: str
@app.post("/search")
async def search(req: SearchRequest):
# Your search logic here
return {
"results": [
{"title": "Result 1", "url": "https://example.com/1", "description": "..."}
]
}
**Express.js (Node.js):**
```typescript
import express from "express";
const app = express();
app.use(express.json());
app.post("/search", (req, res) => {
const { query } = req.body;
// Your search logic here
res.json({
results: [
{ title: "Result 1", url: "https://example.com/1", description: "..." }
]
});
});
app.listen(8000, () => console.log("Tool server running on :8000"));
**Express.js(Node.js):**
```typescript
import express from "express";
const app = express();
app.use(express.json());
app.post("/search", (req, res) => {
const { query } = req.body;
// Your search logic here
res.json({
results: [
{ title: "Result 1", url: "https://example.com/1", description: "..." }
]
});
});
app.listen(8000, () => console.log("Tool server running on :8000"));answerFormatfrom subconscious import Subconscious
client = Subconscious(api_key="your-api-key")
run = client.run(
engine="tim-gpt",
input={
"instructions": "Analyze the sentiment of this review: 'Great product, fast shipping!'",
"tools": [],
"answerFormat": {
"type": "object",
"title": "SentimentAnalysis",
"properties": {
"sentiment": {
"type": "string",
"enum": ["positive", "negative", "neutral"],
"description": "The overall sentiment"
},
"confidence": {
"type": "number",
"description": "Confidence score from 0 to 1"
},
"keywords": {
"type": "array",
"items": {"type": "string"},
"description": "Key phrases that influenced the sentiment"
}
},
"required": ["sentiment", "confidence", "keywords"]
}
},
options={"await_completion": True},
)answerFormatfrom subconscious import Subconscious
client = Subconscious(api_key="your-api-key")
run = client.run(
engine="tim-gpt",
input={
"instructions": "Analyze the sentiment of this review: 'Great product, fast shipping!'",
"tools": [],
"answerFormat": {
"type": "object",
"title": "SentimentAnalysis",
"properties": {
"sentiment": {
"type": "string",
"enum": ["positive", "negative", "neutral"],
"description": "The overall sentiment"
},
"confidence": {
"type": "number",
"description": "Confidence score from 0 to 1"
},
"keywords": {
"type": "array",
"items": {"type": "string"},
"description": "Key phrases that influenced the sentiment"
}
},
"required": ["sentiment", "confidence", "keywords"]
}
},
options={"await_completion": True},
)
**Node.js/TypeScript:**
```typescript
import { Subconscious } from "subconscious";
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const run = await client.run({
engine: "tim-gpt",
input: {
instructions: "Analyze the sentiment of this review: 'Great product, fast shipping!'",
tools: [],
answerFormat: {
type: "object",
title: "SentimentAnalysis",
properties: {
sentiment: {
type: "string",
enum: ["positive", "negative", "neutral"],
description: "The overall sentiment"
},
confidence: {
type: "number",
description: "Confidence score from 0 to 1"
},
keywords: {
type: "array",
items: { type: "string" },
description: "Key phrases that influenced the sentiment"
}
},
required: ["sentiment", "confidence", "keywords"]
}
},
options: { awaitCompletion: true },
});
// Response is already an object matching your schema - no parsing needed
const result = run.result?.answer;
console.log(result.sentiment); // "positive"
console.log(result.confidence); // 0.95
console.log(result.keywords); // ["Great product", "fast shipping"]answerFormatrun.result.answer
**Node.js/TypeScript:**
```typescript
import { Subconscious } from "subconscious";
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const run = await client.run({
engine: "tim-gpt",
input: {
instructions: "Analyze the sentiment of this review: 'Great product, fast shipping!'",
tools: [],
answerFormat: {
type: "object",
title: "SentimentAnalysis",
properties: {
sentiment: {
type: "string",
enum: ["positive", "negative", "neutral"],
description: "The overall sentiment"
},
confidence: {
type: "number",
description: "Confidence score from 0 to 1"
},
keywords: {
type: "array",
items: { type: "string" },
description: "Key phrases that influenced the sentiment"
}
},
required: ["sentiment", "confidence", "keywords"]
}
},
options: { awaitCompletion: true },
});
// Response is already an object matching your schema - no parsing needed
const result = run.result?.answer;
console.log(result.sentiment); // "positive"
console.log(result.confidence); // 0.95
console.log(result.keywords); // ["Great product", "fast shipping"]answerFormatrun.result.answerfrom subconscious import Subconscious
from pydantic import BaseModel
class SentimentAnalysis(BaseModel):
sentiment: str
confidence: float
keywords: list[str]
client = Subconscious(api_key="your-api-key")
run = client.run(
engine="tim-gpt",
input={
"instructions": "Analyze the sentiment of: 'Great product!'",
"answerFormat": SentimentAnalysis, # Pass the class directly
},
options={"await_completion": True},
)
print(run.result.answer["sentiment"])from subconscious import Subconscious
from pydantic import BaseModel
class SentimentAnalysis(BaseModel):
sentiment: str
confidence: float
keywords: list[str]
client = Subconscious(api_key="your-api-key")
run = client.run(
engine="tim-gpt",
input={
"instructions": "Analyze the sentiment of: 'Great product!'",
"answerFormat": SentimentAnalysis, # Pass the class directly
},
options={"await_completion": True},
)
print(run.result.answer["sentiment"])import { z } from 'zod';
import { Subconscious, zodToJsonSchema } from 'subconscious';
const AnalysisSchema = z.object({
summary: z.string().describe('A brief summary of the findings'),
keyPoints: z.array(z.string()).describe('Main takeaways'),
sentiment: z.enum(['positive', 'neutral', 'negative']),
confidence: z.number().describe('Confidence score from 0 to 1'),
});
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const run = await client.run({
engine: 'tim-gpt',
input: {
instructions: 'Analyze the latest news about electric vehicles',
tools: [{ type: 'platform', id: 'fast_search' }],
answerFormat: zodToJsonSchema(AnalysisSchema, 'Analysis'),
},
options: { awaitCompletion: true },
});
// Result is typed according to your schema
const result = run.result?.answer as z.infer<typeof AnalysisSchema>;
console.log(result.summary);
console.log(result.keyPoints);import { z } from 'zod';
import { Subconscious, zodToJsonSchema } from 'subconscious';
const AnalysisSchema = z.object({
summary: z.string().describe('A brief summary of the findings'),
keyPoints: z.array(z.string()).describe('Main takeaways'),
sentiment: z.enum(['positive', 'neutral', 'negative']),
confidence: z.number().describe('Confidence score from 0 to 1'),
});
const client = new Subconscious({
apiKey: process.env.SUBCONSCIOUS_API_KEY!,
});
const run = await client.run({
engine: 'tim-gpt',
input: {
instructions: 'Analyze the latest news about electric vehicles',
tools: [{ type: 'platform', id: 'fast_search' }],
answerFormat: zodToJsonSchema(AnalysisSchema, 'Analysis'),
},
options: { awaitCompletion: true },
});
// Result is typed according to your schema
const result = run.result?.answer as z.infer<typeof AnalysisSchema>;
console.log(result.summary);
console.log(result.keyPoints);reasoningFormatconst ReasoningSchema = z.object({
steps: z.array(z.object({
thought: z.string(),
action: z.string(),
})),
conclusion: z.string(),
});
const run = await client.run({
engine: 'tim-gpt',
input: {
instructions: 'Research and analyze a topic',
tools: [],
reasoningFormat: zodToJsonSchema(ReasoningSchema, 'Reasoning'),
},
options: { awaitCompletion: true },
});
const reasoning = run.result?.reasoning; // Structured reasoningreasoningFormatconst ReasoningSchema = z.object({
steps: z.array(z.object({
thought: z.string(),
action: z.string(),
})),
conclusion: z.string(),
});
const run = await client.run({
engine: 'tim-gpt',
input: {
instructions: 'Research and analyze a topic',
tools: [],
reasoningFormat: zodToJsonSchema(ReasoningSchema, 'Reasoning'),
},
options: { awaitCompletion: true },
});
const reasoning = run.result?.reasoning; // Structured reasoningtype: "object"titlepropertiesrequiredadditionalProperties: falsereferences/api-reference.mdtype: "object"titlepropertiesrequiredadditionalProperties: falsereferences/api-reference.mdrun()run()run({ options: { awaitCompletion: true } })run.result?.answerconst run = await client.run({
engine: "tim-gpt",
input: { instructions: "Your prompt", tools: [] },
options: { awaitCompletion: true }
});
const answer = run.result?.answer; // Clean text - use this for display
const reasoning = run.result?.reasoning; // Optional: step-by-step reasoningrun({ options: { awaitCompletion: true } })run.result?.answerconst run = await client.run({
engine: "tim-gpt",
input: { instructions: "Your prompt", tools: [] },
options: { awaitCompletion: true }
});
const answer = run.result?.answer; // Clean text - use this for display
const reasoning = run.result?.reasoning; // Optional: step-by-step reasoningstream()stream()stream(){"reasoning": [...], "answer": "..."}stream(){"reasoning": [...], "answer": "..."}delta: {"rea
delta: soning": [{"th
delta: ought": "Analyzing
...
delta: "}], "answer": "Here's the answer"}
done: {runId: "run_xxx"}delta: {"rea
delta: soning": [{"th
delta: ought": "Analyzing
...
delta: "}], "answer": "Here's the answer"}
done: {runId: "run_xxx"}| Use Case | Method | Why |
|---|---|---|
| Show thinking in real-time | | Users see reasoning as it happens (like ChatGPT) |
| Simple chat, fast response | | Easier, returns clean |
| Background processing | | Poll for status |
| 使用场景 | 方法 | 原因 |
|---|---|---|
| 实时展示思考过程 | | 用户可实时看到推理步骤(类似ChatGPT) |
| 简单聊天、快速响应 | | 更简单,直接返回纯文本响应 |
| 后台处理 | 不设置 | 轮询状态 |
references/streaming-and-reasoning.mdconst stream = client.stream({
engine: "tim-gpt",
input: { instructions: "Your prompt", tools: [] }
});
let fullContent = "";
for await (const event of stream) {
if (event.type === "delta") {
fullContent += event.content;
// Extract thoughts using regex (see streaming-and-reasoning.md)
const thoughts = extractThoughts(fullContent);
// Send to UI
} else if (event.type === "done") {
const final = JSON.parse(fullContent);
const answer = final.answer; // Extract final answer
}
}run()references/streaming-and-reasoning.mdconst stream = client.stream({
engine: "tim-gpt",
input: { instructions: "Your prompt", tools: [] }
});
let fullContent = "";
for await (const event of stream) {
if (event.type === "delta") {
fullContent += event.content;
// Extract thoughts using regex (see streaming-and-reasoning.md)
const thoughts = extractThoughts(fullContent);
// Send to UI
} else if (event.type === "done") {
const final = JSON.parse(fullContent);
const answer = final.answer; // Extract final answer
}
}run()run = client.run(
engine="tim-gpt",
input={"instructions": "Your task", "tools": tools},
options={"await_completion": True}
)
answer = run.result.answer # Clean textrun = client.run(
engine="tim-gpt",
input={"instructions": "Your task", "tools": tools},
options={"await_completion": True}
)
answer = run.result.answer # Clean textawait_completionrun = client.run(
engine="tim-gpt",
input={"instructions": "Long task", "tools": tools}
# No await_completion - returns immediately
)
run_id = run.run_idawait_completionrun = client.run(
engine="tim-gpt",
input={"instructions": "Long task", "tools": tools}
# No await_completion - returns immediately
)
run_id = run.run_idundefinedundefinedreferences/examples.mdreferences/examples.md| Method | Description | When to Use |
|---|---|---|
| Create a run (sync or async) | Most common - create agent runs |
| Stream run events in real-time | Chat UIs, live demos |
| Get current status of a run | Check async run status |
| Poll until run completes | Background jobs, dashboards |
| Cancel a running/queued run | User cancellation, timeouts |
| 方法 | 描述 | 何时使用 |
|---|---|---|
| 创建一个运行任务(同步或异步) | 最常用 - 创建Agent运行任务 |
| 实时流式传输运行事件 | 聊天UI、实时演示 |
| 获取运行任务的当前状态 | 检查异步任务状态 |
| 轮询直到任务完成 | 后台任务、仪表板 |
| 取消运行中/排队的任务 | 用户取消、超时 |
status = client.get(run.run_id)
print(status.status) # 'queued' | 'running' | 'succeeded' | 'failed'
if status.status == "succeeded":
print(status.result.answer)const status = await client.get(run.runId);
console.log(status.status);
if (status.status === "succeeded") {
console.log(status.result?.answer);
}status = client.get(run.run_id)
print(status.status) # 'queued' | 'running' | 'succeeded' | 'failed'
if status.status == "succeeded":
print(status.result.answer)const status = await client.get(run.runId);
console.log(status.status);
if (status.status === "succeeded") {
console.log(status.result?.answer);
}result = client.wait(
run.run_id,
options={
"interval_ms": 2000, # Poll every 2 seconds (default)
"max_attempts": 60, # Max attempts before giving up (default: 60)
},
)const result = await client.wait(run.runId, {
intervalMs: 2000, // Poll every 2 seconds
maxAttempts: 60, // Max attempts before giving up
});result = client.wait(
run.run_id,
options={
"interval_ms": 2000, # Poll every 2 seconds (default)
"max_attempts": 60, # Max attempts before giving up (default: 60)
},
)const result = await client.wait(run.runId, {
intervalMs: 2000, # Poll every 2 seconds
maxAttempts: 60, # Max attempts before giving up
});client.cancel(run.run_id)await client.cancel(run.runId);client.cancel(run.run_id)await client.cancel(run.runId);tools = [
{
"type": "function",
"name": "web_search",
"description": "Search the web for current information",
"url": "https://your-server.com/search",
"method": "POST",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
}
]
run = client.run(
engine="tim-gpt",
input={
"instructions": "Research the latest AI breakthroughs",
"tools": tools
},
options={"await_completion": True}
)
print(run.result.answer)tools = [
{
"type": "function",
"name": "web_search",
"description": "Search the web for current information",
"url": "https://your-server.com/search",
"method": "POST",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"}
},
"required": ["query"]
}
}
]
run = client.run(
engine="tim-gpt",
input={
"instructions": "Research the latest AI breakthroughs",
"tools": tools
},
options={"await_completion": True}
)
print(run.result.answer)tools = [
{
"type": "function",
"name": "search",
"description": "Search the web",
"url": "https://your-server.com/search",
"method": "POST",
"parameters": {...}
},
{
"type": "function",
"name": "save_to_db",
"description": "Save results to database",
"url": "https://your-server.com/save",
"method": "POST",
"parameters": {...}
}
]tools = [
{
"type": "function",
"name": "search",
"description": "Search the web",
"url": "https://your-server.com/search",
"method": "POST",
"parameters": {...}
},
{
"type": "function",
"name": "save_to_db",
"description": "Save results to database",
"url": "https://your-server.com/save",
"method": "POST",
"parameters": {...}
}
]import {
Subconscious,
type RunResponse,
type StreamEvent,
type ReasoningStep,
type Tool,
type SubconsciousError
} from "subconscious";import {
Subconscious,
type RunResponse,
type StreamEvent,
type ReasoningStep,
type Tool,
type SubconsciousError
} from "subconscious";interface RunResponse {
runId: string;
status: "queued" | "running" | "succeeded" | "failed" | "canceled" | "timed_out";
result?: {
answer: string; // Clean text response
reasoning?: ReasoningStep[]; // Optional: step-by-step reasoning
};
usage?: {
inputTokens: number;
outputTokens: number;
durationMs: number;
toolCalls?: { [toolName: string]: number };
};
error?: {
code: string;
message: string;
};
}
interface ReasoningStep {
title?: string;
thought?: string;
conclusion?: string;
tooluse?: {
tool_name: string;
parameters: Record<string, unknown>;
tool_result: unknown;
};
subtasks?: ReasoningStep[];
}
interface StreamEvent {
type: "delta" | "done" | "error";
content?: string; // Raw JSON chunk for delta events
runId?: string; // Present on done
message?: string; // Present on error
}interface RunResponse {
runId: string;
status: "queued" | "running" | "succeeded" | "failed" | "canceled" | "timed_out";
result?: {
answer: string; // Clean text response
reasoning?: ReasoningStep[]; // Optional: step-by-step reasoning
};
usage?: {
inputTokens: number;
outputTokens: number;
durationMs: number;
toolCalls?: { [toolName: string]: number };
};
error?: {
code: string;
message: string;
};
}
interface ReasoningStep {
title?: string;
thought?: string;
conclusion?: string;
tooluse?: {
tool_name: string;
parameters: Record<string, unknown>;
tool_result: unknown;
};
subtasks?: ReasoningStep[];
}
interface StreamEvent {
type: "delta" | "done" | "error";
content?: string; // Raw JSON chunk for delta events
runId?: string; // Present on done
message?: string; // Present on error
}import { SubconsciousError } from "subconscious";
try {
const run = await client.run({
engine: "tim-gpt",
input: { instructions: "...", tools: [] },
options: { awaitCompletion: true }
});
} catch (error) {
if (error instanceof SubconsciousError) {
switch (error.code) {
case "invalid_api_key":
// Redirect to settings
console.error("Invalid API key");
break;
case "rate_limited":
// Show retry message
console.error("Rate limited, retry later");
break;
case "insufficient_credits":
// Prompt to add credits
console.error("Insufficient credits");
break;
case "invalid_request":
// Log for debugging
console.error("Invalid request:", error.message);
break;
case "timeout":
// Offer to retry with longer timeout
console.error("Request timed out");
break;
default:
console.error("Error:", error.message);
}
} else {
// Network or other errors
console.error("Unexpected error:", error);
}
}import { SubconsciousError } from "subconscious";
try {
const run = await client.run({
engine: "tim-gpt",
input: { instructions: "...", tools: [] },
options: { awaitCompletion: true }
});
} catch (error) {
if (error instanceof SubconsciousError) {
switch (error.code) {
case "invalid_api_key":
// Redirect to settings
console.error("Invalid API key");
break;
case "rate_limited":
// Show retry message
console.error("Rate limited, retry later");
break;
case "insufficient_credits":
// Prompt to add credits
console.error("Insufficient credits");
break;
case "invalid_request":
// Log for debugging
console.error("Invalid request:", error.message);
break;
case "timeout":
// Offer to retry with longer timeout
console.error("Request timed out");
break;
default:
console.error("Error:", error.message);
}
} else {
// Network or other errors
console.error("Unexpected error:", error);
}
}| Status | Code | Meaning | Action |
|---|---|---|---|
| 400 | | Bad request parameters | Fix request |
| 401 | | Invalid or missing API key | Check API key |
| 402 | | Account needs credits | Add credits |
| 429 | | Too many requests | Retry after delay |
| 500 | | Server error | Retry with backoff |
| 503 | | Service down | Retry later |
| 状态码 | 错误码 | 含义 | 处理方式 |
|---|---|---|---|
| 400 | | 请求参数错误 | 修正请求 |
| 401 | | API密钥无效或缺失 | 检查API密钥 |
| 402 | | 账户余额不足 | 充值 |
| 429 | | 请求过于频繁 | 延迟后重试 |
| 500 | | 服务器错误 | 指数退避重试 |
| 503 | | 服务不可用 | 稍后重试 |
const run = await client.run({...});
if (run.status === "succeeded") {
console.log(run.result?.answer);
} else if (run.status === "failed") {
console.error("Run failed:", run.error?.message);
} else if (run.status === "timed_out") {
console.error("Run timed out");
}const run = await client.run({...});
if (run.status === "succeeded") {
console.log(run.result?.answer);
} else if (run.status === "failed") {
console.error("Run failed:", run.error?.message);
} else if (run.status === "timed_out") {
console.error("Run timed out");
}const controller = new AbortController();
// Start the request
const runPromise = client.run({
engine: "tim-gpt",
input: { instructions: "...", tools: [] },
options: { awaitCompletion: true }
});
// Cancel after 10 seconds
setTimeout(() => controller.abort(), 10000);
// Or cancel on user action
cancelButton.onclick = () => controller.abort();
try {
const run = await runPromise;
} catch (error) {
if (error.name === "AbortError") {
console.log("Request cancelled by user");
}
}const controller = new AbortController();
// Start the request
const runPromise = client.run({
engine: "tim-gpt",
input: { instructions: "...", tools: [] },
options: { awaitCompletion: true }
});
// Cancel after 10 seconds
setTimeout(() => controller.abort(), 10000);
// Or cancel on user action
cancelButton.onclick = () => controller.abort();
try {
const run = await runPromise;
} catch (error) {
if (error.name === "AbortError") {
console.log("Request cancelled by user");
}
}// Start async run
const run = await client.run({
engine: "tim-gpt",
input: { instructions: "...", tools: [] }
// No awaitCompletion
});
// Cancel it
await client.cancel(run.runId);// Start async run
const run = await client.run({
engine: "tim-gpt",
input: { instructions: "...", tools: [] }
// No awaitCompletion
});
// Cancel it
await client.cancel(run.runId);event.contentstream(){"reasoning":[{"thought":"I need to...// BAD - shows raw JSON in UI
for await (const event of stream) {
if (event.type === "delta") {
displayToUser(event.content); // Shows: {"rea... (ugly!)
}
}
// GOOD - extract thoughts and show clean text
let fullContent = "";
let sentThoughts: string[] = [];
for await (const event of stream) {
if (event.type === "delta") {
fullContent += event.content;
// Extract thoughts using regex
const thoughtPattern = /"thought"\s*:\s*"((?:[^"\\]|\\.)*)"/g;
let match;
while ((match = thoughtPattern.exec(fullContent)) !== null) {
const thought = match[1].replace(/\\n/g, " ").replace(/\\"/g, '"');
if (!sentThoughts.includes(thought)) {
displayThinking(thought); // Shows: "I need to search for movies..."
sentThoughts.push(thought);
}
}
} else if (event.type === "done") {
const parsed = JSON.parse(fullContent);
displayAnswer(parsed.answer); // Shows clean final answer
}
}references/streaming-and-reasoning.mdrun.result?.answerchoices[0].message.contentstream()run()references/streaming-and-reasoning.md/chat/completionsresult.answerresult.answerresult.contenttimtim-edgetiminitim-gpttim-gpt-heavy{"reasoning": [...], "answer": "..."}run()tools: []run.statusrun.resultstream()event.content{"reasoning":[{"thought":"I need to...// BAD - shows raw JSON in UI
for await (const event of stream) {
if (event.type === "delta") {
displayToUser(event.content); // Shows: {"rea... (ugly!)
}
}
// GOOD - extract thoughts and show clean text
let fullContent = "";
let sentThoughts: string[] = [];
for await (const event of stream) {
if (event.type === "delta") {
fullContent += event.content;
// Extract thoughts using regex
const thoughtPattern = /"thought"\s*:\s*"((?:[^"\\]|\\.)*)"/g;
let match;
while ((match = thoughtPattern.exec(fullContent)) !== null) {
const thought = match[1].replace(/\\n/g, " ").replace(/\\"/g, '"');
if (!sentThoughts.includes(thought)) {
displayThinking(thought); // Shows: "I need to search for movies..."
sentThoughts.push(thought);
}
}
} else if (event.type === "done") {
const parsed = JSON.parse(fullContent);
displayAnswer(parsed.answer); // Shows clean final answer
}
}references/streaming-and-reasoning.mdrun.result?.answerchoices[0].message.contentstream()run()references/streaming-and-reasoning.md/chat/completionsresult.answerresult.answerresult.contenttimtim-edgetiminitim-gpttim-gpt-heavy{"reasoning": [...], "answer": "..."}run()tools: []run.statusrun.resultreferences/examples.mdreferences/examples.mdrun.usagerun.usage.durationMsrun.usage.toolCallsrun.usagerun.usage.durationMsrun.usage.toolCallstimtim-edgetim-gpt-heavytimtim-edgetim-gpt-heavyreferences/api-reference.mdreferences/streaming-and-reasoning.mdreferences/typescript-types.mdreferences/error-handling.mdreferences/tools-guide.mdreferences/examples.mdreferences/api-reference.mdreferences/streaming-and-reasoning.mdreferences/typescript-types.mdreferences/error-handling.mdreferences/tools-guide.mdreferences/examples.md