npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@aichatkit/apollo-adapter

v0.0.0-alpha.6

Published

Apollo GraphQL adapter for Hypermode ChatKit

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 graphql

Usage

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 API
  • maxRetries: 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, cards

getConversationHistory(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 items

clearConversationHistory(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:

  1. Agent Creation: Each conversation starts by creating a new agent via startChatAgent()
  2. Stateful Conversations: Agents maintain conversation state including all response items
  3. Rich Responses: Agents can return messages, tool calls, cards, and other content types
  4. Message Handling: Messages are sent directly to specific agents
  5. History Sync: Full conversation state including all item types is stored on the agent
  6. 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