@aichatkit/apollo-adapter
v0.0.0-alpha.6
Published
Apollo GraphQL adapter for Hypermode ChatKit
Maintainers
Readme
@aichatkit/apollo-adapter
Apollo GraphQL implementation of the network adapter for Hypermode ChatKit with support for stateful chat agents and rich response items.
Installation
npm install @aichatkit/apollo-adapter @apollo/client graphqlUsage
import { ApolloAdapter } from "@aichatkit/apollo-adapter";
import { ChatInterface } from "@aichatkit/ui";
import { ApolloClient, InMemoryCache } from "@apollo/client";
// Option 1: Create with configuration options
const networkAdapter = new ApolloAdapter({
apiUrl: "http://localhost:8686/graphql",
apiToken: "your-auth-token",
maxRetries: 3,
});
// Option 2: Create with existing Apollo Client
const client = new ApolloClient({
uri: "http://localhost:8686/graphql",
cache: new InMemoryCache(),
});
const networkAdapter = new ApolloAdapter({
apolloClient: client,
});
// Use with ChatInterface
function ChatApp() {
return (
<ChatInterface
networkAdapter={networkAdapter}
// other props...
/>
);
}Configuration Options
The ApolloAdapter constructor accepts an optional configuration object with the following
properties:
apiUrl: The GraphQL API URL (default: 'http://localhost:8686/graphql')apiToken: Authentication token for the APImaxRetries: Maximum number of retry attempts for failed requests (default: 3)apolloClient: Custom Apollo Client instance (if provided, other options will be ignored)
API Methods
The ApolloAdapter implements all methods from the base NetworkAdapter:
startChatAgent(): Promise
Creates a new chat agent and returns the agent ID.
const agentId = await adapter.startChatAgent()sendMessage(agentId: string, message: string): Promise
Sends a message to a chat agent and returns the response with rich content items.
const response = await adapter.sendMessage(agentId, "Hello, world!")
// response contains an array of items: messages, tool calls, cards, etc.getConversationItems(agentId: string): Promise<ChatResponseItem[]>
Retrieves all conversation items (messages, tool calls, cards) from the backend agent.
const items = await adapter.getConversationItems(agentId)
// Returns array of mixed item types: messages, tool calls, cardsgetConversationHistory(agentId: string): Promise<Message[]>
Retrieves only the message history from the backend agent.
const messages = await adapter.getConversationHistory(agentId)
// Returns only message items, filtered from all response itemsclearConversationHistory(agentId: string): Promise
Clears the conversation history on the backend agent.
await adapter.clearConversationHistory(agentId)stopChatAgent(agentId: string): Promise
Stops/terminates a chat agent.
await adapter.stopChatAgent(agentId)getClient(): ApolloClient
Returns the underlying Apollo Client instance for advanced usage.
const client = adapter.getClient()Response Items
The adapter supports rich response items including:
Message Items
Standard chat messages from user or assistant.
{
id: "msg_123",
type: "message",
content: "Hello there!",
role: "assistant",
timestamp: "2024-01-01T00:00:00Z"
}Tool Call Items
Displays tool executions with arguments, 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 cards with structured data and 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"
}
]
}
}GraphQL Schema
The adapter expects the following GraphQL schema from your backend:
type Query {
# Start a new chat agent
createConversation: String!
# Send a message to an agent and get rich response items
continueChat(id: String!, query: String!): ChatResponse!
# Get all conversation items from an agent
chatHistory(id: String!): HistoryResponse!
}
type Mutation {
# Clear conversation history for an agent
deleteConversationHistory(id: String!): Boolean!
# Stop/delete a chat agent
deleteAgent(id: String!): String!
}
type ChatResponse {
items: String! # JSON string of ChatResponseItem array
conversationId: String!
}
type HistoryResponse {
items: String! # JSON string of ChatResponseItem array
count: Int!
}Agent-Based Architecture
This adapter is designed to work with Hypermode's stateful chat agents:
- Agent Creation: Each conversation starts by creating a new agent via
startChatAgent() - Stateful Conversations: Agents maintain conversation state including all response items
- Rich Responses: Agents can return messages, tool calls, cards, and other content types
- Message Handling: Messages are sent directly to specific agents
- History Sync: Full conversation state including all item types is stored on the agent
- Agent Lifecycle: Agents can be stopped/cleaned up when conversations are deleted
Example with Complete Setup
import { ApolloAdapter } from "@aichatkit/apollo-adapter";
import { LocalStorageAdapter } from "@aichatkit/localstorage-adapter";
import { ChatInterface } from "@aichatkit/ui";
import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
// Create Apollo Client with authentication
const httpLink = createHttpLink({
uri: "http://localhost:8686/graphql",
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: "Bearer your-token-here",
},
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
// Initialize adapters
const networkAdapter = new ApolloAdapter({ apolloClient: client });
const storageAdapter = new LocalStorageAdapter();
// Connect storage with network for syncing
await storageAdapter.initialize();
storageAdapter.setNetworkCallbacks({
getConversationItems: (agentId) =>
networkAdapter.getConversationItems(agentId),
clearConversationHistory: (agentId) =>
networkAdapter.clearConversationHistory(agentId),
});
// Use in your app
function App() {
return (
<ChatInterface
networkAdapter={networkAdapter}
storageAdapter={storageAdapter}
hypermodeStyle={true}
onCardAction={(action) => {
// Handle card button clicks
console.log("Card action:", action);
}}
/>
);
}Error Handling
The adapter includes built-in error handling and retry logic:
// Automatic retries for failed requests
const adapter = new ApolloAdapter({
maxRetries: 3,
})
// Handle errors in your application
try {
const response = await adapter.sendMessage(agentId, message)
} catch (error) {
console.error("Failed to send message:", error)
// Handle error appropriately
}Compatibility
- Apollo Client: 3.8.0+
- GraphQL: 16.8.0+
- React: 18.0.0+ or 19.0.0+
License
MIT © Hypermode
