@aichatkit/network-adapter
v0.0.0-alpha.6
Published
Base network adapter for Hypermode ChatKit
Maintainers
Readme
@aichatkit/network-adapter
Base network adapter abstract class for Hypermode ChatKit with support for stateful chat agents and rich response items.
Installation
npm install @aichatkit/network-adapterUsage
This package provides the base abstract class for implementing network adapters. You typically won't
use this package directly, but rather create or use an implementation like
@aichatkit/apollo-adapter.
import { NetworkAdapter } from "@aichatkit/network-adapter"
import { ChatResponse, ChatResponseItem, Message } from "@aichatkit/types"
// Example: Create a custom adapter implementation
class CustomNetworkAdapter extends NetworkAdapter {
async startChatAgent(): Promise<string> {
// Create a new chat agent/session and return its ID
const response = await fetch("https://your-api.com/agents", {
method: "POST",
})
const data = await response.json()
return data.agentId
}
async sendMessage(agentId: string, message: string): Promise<ChatResponse> {
// Send message to a specific agent and get rich response
const response = await fetch(`https://your-api.com/agents/${agentId}/messages`, {
method: "POST",
body: JSON.stringify({ message }),
headers: { "Content-Type": "application/json" },
})
const data = await response.json()
return {
items: data.items, // Array of messages, tool calls, cards, etc.
conversationId: data.conversationId,
}
}
async getConversationItems(agentId: string): Promise<ChatResponseItem[]> {
// Retrieve all conversation items from the agent
const response = await fetch(`https://your-api.com/agents/${agentId}/items`)
const data = await response.json()
return data.items // Mixed array of messages, tool calls, cards, etc.
}
async getConversationHistory(agentId: string): Promise<Message[]> {
// Get only message items (convenience method)
const items = await this.getConversationItems(agentId)
// Filter and convert to messages
return items
.filter((item) => item.type === "message")
.map((item) => ({
id: item.id,
content: item.content,
role: item.role,
timestamp: item.timestamp,
}))
}
async clearConversationHistory(agentId: string): Promise<void> {
// Clear the agent's conversation history
await fetch(`https://your-api.com/agents/${agentId}/history`, {
method: "DELETE",
})
}
async stopChatAgent(agentId: string): Promise<void> {
// Stop/terminate the chat agent
await fetch(`https://your-api.com/agents/${agentId}`, {
method: "DELETE",
})
}
}Abstract Methods
All network adapters must implement these methods:
startChatAgent(): Promise
Creates a new chat agent/session and returns its unique identifier.
abstract startChatAgent(): Promise<string>;Returns: Promise resolving to the agent ID
Example:
const agentId = await adapter.startChatAgent()
console.log("New agent created:", agentId)sendMessage(agentId: string, message: string): Promise
Sends a message to a specific chat agent and returns the response with rich content items.
abstract sendMessage(agentId: string, message: string): Promise<ChatResponse>;Parameters:
agentId: The ID of the agent to send the message tomessage: The message content to send
Returns: Promise resolving to the chat response containing mixed item types
Example:
const response = await adapter.sendMessage("agent-123", "Hello, world!")
console.log("Response items:", response.items)
// Items can include messages, tool calls, cards, etc.getConversationItems(agentId: string): Promise<ChatResponseItem[]>
Retrieves all conversation items from a specific agent.
abstract getConversationItems(agentId: string): Promise<ChatResponseItem[]>;Parameters:
agentId: The ID of the agent
Returns: Promise resolving to an array of mixed response items
Example:
const items = await adapter.getConversationItems("agent-123")
console.log("Total items:", items.length)
// Items include messages, tool calls, cards, etc.getConversationHistory(agentId: string): Promise<Message[]>
Retrieves only the message history from a specific agent (convenience method).
async getConversationHistory(agentId: string): Promise<Message[]>Parameters:
agentId: The ID of the agent
Returns: Promise resolving to an array of messages only
Example:
const messages = await adapter.getConversationHistory("agent-123")
console.log("Message count:", messages.length)
// Only message items, filtered from all response itemsclearConversationHistory(agentId: string): Promise
Clears the conversation history for a specific agent.
abstract clearConversationHistory(agentId: string): Promise<void>;Parameters:
agentId: The ID of the agent
Example:
await adapter.clearConversationHistory("agent-123")
console.log("History cleared")stopChatAgent(agentId: string): Promise
Stops/terminates a chat agent and cleans up resources.
abstract stopChatAgent(agentId: string): Promise<void>;Parameters:
agentId: The ID of the agent to stop
Example:
await adapter.stopChatAgent("agent-123")
console.log("Agent stopped")Optional Methods
initialize(config?: Record<string, any>): Promise
Optional initialization method for setting up the adapter.
async initialize(config?: Record<string, any>): Promise<void> {
// Default implementation does nothing
return Promise.resolve();
}Example Override:
class CustomAdapter extends NetworkAdapter {
async initialize(config?: Record<string, any>): Promise<void> {
// Initialize connection pools, auth tokens, etc.
this.apiKey = config?.apiKey || process.env.API_KEY
await this.validateConnection()
}
}Response Item Types
The adapter supports various response item types:
Message Items
Standard chat messages between user and assistant.
{
id: "msg_123",
type: "message",
content: "Hello there!",
role: "assistant",
timestamp: "2024-01-01T00:00:00Z"
}Tool Call Items
Represents tool/function executions with status and results.
{
id: "tool_123",
type: "tool_call",
toolCall: {
id: "call_123",
name: "get_weather",
arguments: { location: "New York" },
status: "completed",
result: { temperature: "22°C", condition: "Sunny" }
}
}Card Items
Rich content displays with structured data and interactive actions.
{
id: "card_123",
type: "card",
card: {
id: "weather_card",
type: "weather",
title: "Weather Information",
content: { location: "New York", temperature: "22°C" },
actions: [
{
id: "view_forecast",
label: "View Forecast",
type: "button",
action: "show_forecast"
}
]
}
}Agent-Based Architecture
This adapter is designed around the concept of stateful chat agents:
- Agent Lifecycle: Each conversation is backed by a unique agent that maintains state
- Rich Responses: Agents can return various item types including messages, tool calls, and cards
- Stateful Conversations: Agents remember conversation context and all response items
- Isolated Sessions: Each agent represents an isolated conversation session
- Resource Management: Agents can be stopped to free up resources
Typical Flow
// 1. Start a new agent for a conversation
const agentId = await adapter.startChatAgent()
// 2. Send messages to the agent and get rich responses
const response1 = await adapter.sendMessage(agentId, "Hello")
const response2 = await adapter.sendMessage(agentId, "What's the weather?")
// Responses can contain messages, tool calls, cards, etc.
// 3. Get all conversation items from the agent
const allItems = await adapter.getConversationItems(agentId)
// 4. Get only messages if needed
const messagesOnly = await adapter.getConversationHistory(agentId)
// 5. Clean up when done
await adapter.stopChatAgent(agentId)Available Implementations
- @aichatkit/apollo-adapter: GraphQL implementation for Hypermode
- Custom implementations: Create your own for REST APIs, WebSockets, etc.
License
MIT © Hypermode
