# Query and List Conversations

## User Intent

"I want to list all my conversations or find a specific conversation by name"

## Operation

* **SDK Method**: `graphlit.queryConversations()` or `graphlit.getConversation()`
* **GraphQL**: `queryConversations` or `getConversation` query
* **Entity Type**: Conversation
* **Common Use Cases**: List conversations, find conversation by name, retrieve conversation history, manage conversations

## TypeScript (Canonical)

```typescript
import { Graphlit } from 'graphlit-client';
import { EntityState } from 'graphlit-client/dist/generated/graphql-types';

const graphlit = new Graphlit();

// Query all conversations
const allConversations = await graphlit.queryConversations();

console.log(`Total conversations: ${allConversations.conversations.results.length}`);

allConversations.conversations.results.forEach(conv => {
  console.log(`- ${conv.name} (${conv.state})`);
  console.log(`  Messages: ${conv.messages?.length || 0}`);
});

// Search by name
const searchResults = await graphlit.queryConversations({
  search: 'Support Chat'
});

console.log(`\nFound ${searchResults.conversations.results.length} matching conversations`);

// Get specific conversation with full details
const conversationId = 'conversation-id-here';
const conversation = await graphlit.getConversation(conversationId);

console.log(`\nConversation: ${conversation.conversation.name}`);
console.log(`Created: ${conversation.conversation.creationDate}`);
console.log(`Messages: ${conversation.conversation.messages?.length || 0}`);

// Print message history
conversation.conversation.messages?.forEach((msg, index) => {
  console.log(`\n${index + 1}. ${msg.role}:`);
  console.log(msg.message);
});
```

## Parameters

### queryConversations (Optional Filter)

* **`search`** (string): Search by conversation name
* **`states`** (EntityState\[]): Filter by state
  * `ENABLED`, `DISABLED`

### getConversation (Required)

* **`id`** (string): Conversation ID

## Response

### queryConversations

```typescript
{
  conversations: {
    results: Conversation[];
  }
}

interface Conversation {
  id: string;
  name: string;
  state: EntityState;
  creationDate: Date;
  messages?: Message[];
  specification?: Specification;
}
```

### getConversation

```typescript
{
  conversation: {
    id: string;
    name: string;
    state: EntityState;
    creationDate: Date;
    messages: Message[];
    specification?: Specification;
  }
}

interface Message {
  role: MessageRole;  // USER, ASSISTANT, SYSTEM
  message: string;
  timestamp: Date;
  citations?: Citation[];
}
```

## Developer Hints

### Conversation History Access

**Important**: Only `getConversation()` returns full message history. `queryConversations()` returns summaries.

```typescript
// Query - NO message history
const conversations = await graphlit.queryConversations();
conversations.conversations.results.forEach(conv => {
  console.log(conv.name);  //  Available
  console.log(conv.messages);  //  Usually undefined or partial
});

// Get - FULL message history
const conversation = await graphlit.getConversation(conversationId);
conversation.conversation.messages?.forEach(msg => {
  console.log(msg.message);  //  Full history
});
```

### Find Conversation by Name

```typescript
// Search for conversation
const results = await graphlit.queryConversations({
  search: 'Customer Support'
});

if (results.conversations.results.length > 0) {
  const conv = results.conversations.results[0];
  console.log(`Found: ${conv.name} (${conv.id})`);
} else {
  console.log('Conversation not found');
}
```

### Resume Conversation

```typescript
// Find existing conversation
const conversations = await graphlit.queryConversations({
  search: 'My Chat'
});

let conversationId: string;

if (conversations.conversations.results.length > 0) {
  // Resume existing
  conversationId = conversations.conversations.results[0].id;
  console.log('Resuming existing conversation');
} else {
  // Create new
  const newConv = await graphlit.createConversation({
    name: 'My Chat'
  });
  conversationId = newConv.createConversation.id;
  console.log('Created new conversation');
}

// Continue conversation
await graphlit.promptConversation({
  prompt: 'Hello!',
  id: conversationId
});
```

### Conversation Statistics

```typescript
const conversations = await graphlit.queryConversations();

// Count by state
const active = conversations.conversations.results.filter(
  c => c.state === EntityState.Enabled
).length;

console.log(`Active conversations: ${active} / ${conversations.conversations.results.length}`);

// Find most recent
const sorted = conversations.conversations.results.sort(
  (a, b) => new Date(b.creationDate).getTime() - new Date(a.creationDate).getTime()
);

console.log('\nMost recent conversations:');
sorted.slice(0, 5).forEach(conv => {
  console.log(`- ${conv.name} (${new Date(conv.creationDate).toLocaleDateString()})`);
});
```

## Variations

### 1. List All Conversations

Get all conversations:

```typescript
const conversations = await graphlit.queryConversations();

console.log(`You have ${conversations.conversations.results.length} conversations`);
```

### 2. Search by Name

Find specific conversations:

```typescript
const results = await graphlit.queryConversations({
  search: 'Support'
});

console.log('Support conversations:');
results.conversations.results.forEach(conv => {
  console.log(`- ${conv.name}`);
});
```

### 3. Get Full Conversation History

Retrieve with messages:

```typescript
const conversation = await graphlit.getConversation(conversationId);

console.log(`\nConversation: ${conversation.conversation.name}`);
console.log(`Total messages: ${conversation.conversation.messages?.length || 0}\n`);

conversation.conversation.messages?.forEach((msg, index) => {
  console.log(`${index + 1}. [${msg.role}]:`);
  console.log(msg.message);
  console.log('---');
});
```

### 4. Filter Active Conversations

Only enabled conversations:

```typescript
const active = await graphlit.queryConversations({
  states: [EntityState.Enabled]
});

console.log(`Active conversations: ${active.conversations.results.length}`);
```

### 5. Recent Conversations

Sort by creation date:

```typescript
const conversations = await graphlit.queryConversations();

const recent = conversations.conversations.results
  .sort((a, b) => new Date(b.creationDate).getTime() - new Date(a.creationDate).getTime())
  .slice(0, 10);

console.log('Last 10 conversations:');
recent.forEach((conv, index) => {
  console.log(`${index + 1}. ${conv.name} - ${new Date(conv.creationDate).toLocaleDateString()}`);
});
```

### 6. Conversation with Citations

Get conversation with citation tracking:

```typescript
const conversation = await graphlit.getConversation(conversationId);

console.log(`Conversation: ${conversation.conversation.name}\n`);

conversation.conversation.messages?.forEach((msg, index) => {
  if (msg.role === MessageRole.Assistant) {
    console.log(`Assistant Response ${index + 1}:`);
    console.log(msg.message);
    
    if (msg.citations && msg.citations.length > 0) {
      console.log('\nCitations:');
      msg.citations.forEach((citation, citIndex) => {
        console.log(`  [${citIndex + 1}] ${citation.content?.name}`);
      });
    }
    console.log('---\n');
  }
});
```

## Common Issues

**Issue**: `Conversation not found` error\
**Solution**: Verify conversation ID is correct. Conversation may have been deleted. Use `queryConversations()` to list all.

**Issue**: No message history returned\
**Solution**: Use `getConversation()` not `queryConversations()`. Only `getConversation()` includes full messages.

**Issue**: Search returns no results\
**Solution**: Search is case-sensitive. Try partial matches. Use `queryConversations()` without filter to see all.

**Issue**: Old conversations appearing\
**Solution**: Conversations persist indefinitely. Use `deleteConversation()` to clean up old ones.

## Production Example

**Conversation history viewer**:

```typescript
// List all conversations with details
const conversations = await graphlit.queryConversations();

console.log('=== CONVERSATION HISTORY ===\n');

for (const conv of conversations.conversations.results) {
  // Get full details
  const fullConv = await graphlit.getConversation(conv.id);
  
  const messageCount = fullConv.conversation.messages?.length || 0;
  const lastMessage = fullConv.conversation.messages?.[messageCount - 1];
  
  console.log(`📝 ${fullConv.conversation.name}`);
  console.log(`   ID: ${fullConv.conversation.id}`);
  console.log(`   Created: ${new Date(fullConv.conversation.creationDate).toLocaleDateString()}`);
  console.log(`   Messages: ${messageCount}`);
  console.log(`   State: ${fullConv.conversation.state}`);
  
  if (lastMessage) {
    console.log(`   Last message: ${lastMessage.message.substring(0, 50)}...`);
  }
  
  console.log('');
}
```

**Resume or create conversation**:

```typescript
// Try to find existing conversation by name
async function getOrCreateConversation(name: string): Promise<string> {
  const results = await graphlit.queryConversations({
    search: name
  });
  
  if (results.conversations.results.length > 0) {
    const existing = results.conversations.results[0];
    console.log(`📌 Resuming conversation: ${existing.name}`);
    return existing.id;
  }
  
  // Create new
  const newConv = await graphlit.createConversation({
    name: name
  });
  
  console.log(`✨ Created new conversation: ${name}`);
  return newConv.createConversation.id;
}

// Usage
const conversationId = await getOrCreateConversation('Customer Support Chat');

// Continue conversation
const answer = await graphlit.promptConversation({
  prompt: 'How can I help you today?',
  id: conversationId
});

console.log(answer.message.message);
```

**Conversation management dashboard**:

```typescript
const conversations = await graphlit.queryConversations();

console.log('=== CONVERSATION DASHBOARD ===\n');

// Statistics
const total = conversations.conversations.results.length;
const active = conversations.conversations.results.filter(
  c => c.state === EntityState.Enabled
).length;

console.log(`Total Conversations: ${total}`);
console.log(`Active: ${active}`);
console.log(`Disabled: ${total - active}\n`);

// Recent activity
const sorted = conversations.conversations.results
  .sort((a, b) => new Date(b.creationDate).getTime() - new Date(a.creationDate).getTime())
  .slice(0, 5);

console.log('Recent Conversations:');
for (const conv of sorted) {
  const fullConv = await graphlit.getConversation(conv.id);
  const msgCount = fullConv.conversation.messages?.length || 0;
  
  console.log(`\n${conv.name}`);
  console.log(`  Messages: ${msgCount}`);
  console.log(`  Created: ${new Date(conv.creationDate).toLocaleDateString()}`);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.graphlit.dev/api-guides/use-cases/conversations/conversation-query.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
