Skip to main content

Using distri-client from @distri/core

The distri-client from @distri/core provides a programmatic API for interacting with Distri agents without React components. Use it when you need direct control over agent execution, want to build custom UIs, or integrate Distri into non-React applications.

Installation

npm install @distri/core
# or
pnpm add @distri/core
# or
yarn add @distri/core

Basic Usage

Create a Distri client instance:

import { Distri } from '@distri/core';

const config = {
baseUrl: 'http://localhost:8787/api/v1',
apiKey: process.env.DISTRI_API_KEY, // optional
debug: true, // optional
};

const client = new Distri(config);

Configuration

The DistriConfig interface:

interface DistriConfig {
baseUrl: string; // Required: API base URL
apiKey?: string; // Optional: API key for authentication
debug?: boolean; // Optional: Enable debug logging
}

Sending Messages

Simple Message

const threadId = crypto.randomUUID();
const response = await client.sendMessage({
agentId: 'my_agent',
threadId,
message: {
role: 'user',
parts: [{ part_type: 'text', data: 'Hello, agent!' }],
},
});

console.log(response);

Streaming Messages

const stream = await client.streamMessage({
agentId: 'my_agent',
threadId,
message: {
role: 'user',
parts: [{ part_type: 'text', data: 'Tell me a story' }],
},
});

for await (const chunk of stream) {
console.log('Chunk:', chunk);
// Handle streaming response
}

Direct LLM Calls

You can call the LLM directly with custom messages and tools:

import type { DistriMessage, DistriBaseTool } from '@distri/core';

const messages: DistriMessage[] = [
{
id: crypto.randomUUID(),
role: 'system',
parts: [{ part_type: 'text', data: 'You are a helpful assistant.' }],
created_at: Date.now(),
},
{
id: crypto.randomUUID(),
role: 'user',
parts: [{ part_type: 'text', data: 'What is 2+2?' }],
created_at: Date.now(),
},
];

const tools: DistriBaseTool[] = [
{
name: 'calculator',
type: 'function',
description: 'Perform calculations',
parameters: {
type: 'object',
properties: {
expression: { type: 'string' },
},
required: ['expression'],
},
},
];

const response = await client.llm(messages, tools, {
thread_id: threadId,
});

console.log('Response:', response);
console.log('Tool calls:', response.tool_calls);

Working with Tools

Defining External Tools

import type { DistriFnTool } from '@distri/core';

const myTool: DistriFnTool = {
name: 'my_tool',
description: 'My custom tool',
type: 'function',
parameters: {
type: 'object',
properties: {
input: { type: 'string' },
},
required: ['input'],
},
handler: async (input) => {
// Your tool implementation
return `Processed: ${input.input}`;
},
};

Using Tools with LLM

const tools: DistriFnTool[] = [myTool];

const response = await client.llm(messages, tools, {
thread_id: threadId,
});

// Handle tool calls
if (response.tool_calls && response.tool_calls.length > 0) {
for (const toolCall of response.tool_calls) {
const tool = tools.find(t => t.name === toolCall.name);
if (tool && 'handler' in tool) {
const result = await tool.handler(toolCall.input);
console.log('Tool result:', result);
}
}
}

Managing Threads

Create a Thread

const thread = await client.createThread({
title: 'My Conversation',
});

console.log('Thread ID:', thread.id);

Get Thread Messages

const messages = await client.getThreadMessages(threadId);
console.log('Messages:', messages);

Update Thread

await client.updateThread(threadId, {
title: 'Updated Title',
});

Delete Thread

await client.deleteThread(threadId);

Listing Agents

const agents = await client.listAgents();
console.log('Available agents:', agents);

Getting Agent Details

const agent = await client.getAgent('my_agent');
console.log('Agent:', agent);
console.log('Tools:', agent.tools);

Complete Example: Custom Chat Implementation

import { Distri } from '@distri/core';
import type { DistriMessage, DistriFnTool } from '@distri/core';

class CustomChat {
private client: Distri;
private threadId: string;
private tools: DistriFnTool[];

constructor(config: DistriConfig) {
this.client = new Distri(config);
this.threadId = crypto.randomUUID();
this.tools = [];
}

async sendMessage(text: string): Promise<string> {
const message: DistriMessage = {
id: crypto.randomUUID(),
role: 'user',
parts: [{ part_type: 'text', data: text }],
created_at: Date.now(),
};

const response = await this.client.sendMessage({
agentId: 'my_agent',
threadId: this.threadId,
message,
});

// Handle tool calls if any
if (response.tool_calls) {
for (const toolCall of response.tool_calls) {
await this.handleToolCall(toolCall);
}
}

return response.text || '';
}

private async handleToolCall(toolCall: any) {
const tool = this.tools.find(t => t.name === toolCall.name);
if (tool && 'handler' in tool) {
const result = await tool.handler(toolCall.input);
console.log('Tool executed:', result);
}
}

addTool(tool: DistriFnTool) {
this.tools.push(tool);
}
}

// Usage
const chat = new CustomChat({
baseUrl: 'http://localhost:8787/api/v1',
});

chat.addTool({
name: 'echo',
description: 'Echo back the input',
type: 'function',
parameters: {
type: 'object',
properties: {
text: { type: 'string' },
},
required: ['text'],
},
handler: async (input) => `Echo: ${input.text}`,
});

const response = await chat.sendMessage('Hello!');
console.log(response);

Singleton Pattern

For applications that need a single client instance:

import { Distri } from '@distri/core';
import type { DistriConfig } from '@distri/core';

let client: Distri | null = null;

export const getDistriClient = (config?: DistriConfig): Distri => {
if (!client) {
if (!config) {
config = {
baseUrl: import.meta.env.VITE_DISTRI_API_URL || 'http://localhost:8787/api/v1',
debug: true,
};
}
client = new Distri(config);
}
return client;
};

Error Handling

try {
const response = await client.sendMessage({
agentId: 'my_agent',
threadId,
message: { /* ... */ },
});
} catch (error) {
if (error instanceof Error) {
console.error('Distri error:', error.message);
}
// Handle error
}

Type Definitions

All types are exported from @distri/core:

import type {
DistriConfig,
DistriMessage,
DistriPart,
DistriBaseTool,
DistriFnTool,
DistriAnyTool,
LLMResponse,
Agent,
} from '@distri/core';

References