cohere-webhooks-events
Implement Cohere streaming event handling, SSE patterns, and connector webhooks. Use when building streaming UIs, handling chat/tool events, or registering Cohere connectors for RAG. Trigger with phrases like "cohere streaming", "cohere events", "cohere SSE", "cohere connectors", "cohere webhook".
What this skill does
# Cohere Streaming Events & Connectors
## Overview
Handle Cohere's streaming chat events (SSE), tool-call events, citation events, and register data connectors for RAG. Cohere does not use traditional webhooks — its event model is streaming-based.
## Prerequisites
- `cohere-ai` SDK v7+
- Understanding of Server-Sent Events (SSE)
- For connectors: HTTPS endpoint accessible from internet
## Instructions
### Step 1: Chat Streaming Events
Cohere's `chatStream` returns a stream of typed events:
```typescript
import { CohereClientV2 } from 'cohere-ai';
const cohere = new CohereClientV2();
async function handleStream(userMessage: string) {
const stream = await cohere.chatStream({
model: 'command-a-03-2025',
messages: [{ role: 'user', content: userMessage }],
});
for await (const event of stream) {
switch (event.type) {
// Text content streaming
case 'content-start':
console.log('--- Generation started ---');
break;
case 'content-delta':
const text = event.delta?.message?.content?.text ?? '';
process.stdout.write(text);
break;
case 'content-end':
console.log('\n--- Generation complete ---');
break;
// Citation events (when using documents)
case 'citation-start':
console.log('Citation:', event.delta?.message?.citations);
break;
// Tool call events (when using tools)
case 'tool-call-start':
console.log('Tool call started:', event.delta?.message?.toolCalls?.function?.name);
break;
case 'tool-call-delta':
// Streaming tool arguments
break;
case 'tool-call-end':
console.log('Tool call complete');
break;
// Message lifecycle
case 'message-start':
console.log('Message ID:', event.id);
break;
case 'message-end':
console.log('Finish reason:', event.delta?.finishReason);
console.log('Usage:', event.delta?.usage);
break;
}
}
}
```
### Step 2: RAG Streaming with Citations
```typescript
async function streamRAG(query: string, docs: string[]) {
const stream = await cohere.chatStream({
model: 'command-a-03-2025',
messages: [{ role: 'user', content: query }],
documents: docs.map((text, i) => ({
id: `doc-${i}`,
data: { text },
})),
});
let fullText = '';
const citations: Array<{ start: number; end: number; text: string; sources: string[] }> = [];
for await (const event of stream) {
if (event.type === 'content-delta') {
const chunk = event.delta?.message?.content?.text ?? '';
fullText += chunk;
process.stdout.write(chunk);
}
if (event.type === 'citation-start') {
const cite = event.delta?.message?.citations;
if (cite) {
citations.push({
start: cite.start,
end: cite.end,
text: cite.text,
sources: cite.sources?.map((s: any) => s.id) ?? [],
});
}
}
}
return { fullText, citations };
}
```
### Step 3: Streaming Tool Use
```typescript
const tools = [{
type: 'function' as const,
function: {
name: 'get_price',
description: 'Get stock price',
parameters: {
type: 'object' as const,
properties: { ticker: { type: 'string' } },
required: ['ticker'],
},
},
}];
async function streamToolUse(query: string) {
const stream = await cohere.chatStream({
model: 'command-a-03-2025',
messages: [{ role: 'user', content: query }],
tools,
});
let currentToolName = '';
let currentToolArgs = '';
for await (const event of stream) {
switch (event.type) {
case 'tool-call-start':
currentToolName = event.delta?.message?.toolCalls?.function?.name ?? '';
currentToolArgs = '';
console.log(`Calling tool: ${currentToolName}`);
break;
case 'tool-call-delta':
currentToolArgs += event.delta?.message?.toolCalls?.function?.arguments ?? '';
break;
case 'tool-call-end':
console.log(`Tool args: ${currentToolArgs}`);
// Execute tool here, then send results back
break;
case 'content-delta':
process.stdout.write(event.delta?.message?.content?.text ?? '');
break;
}
}
}
```
### Step 4: SSE Endpoint for Frontend
```typescript
// Express endpoint that proxies Cohere stream as SSE
import express from 'express';
const app = express();
app.use(express.json());
app.post('/api/chat/stream', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const cohere = new CohereClientV2();
try {
const stream = await cohere.chatStream({
model: 'command-a-03-2025',
messages: req.body.messages,
});
for await (const event of stream) {
if (event.type === 'content-delta') {
const text = event.delta?.message?.content?.text ?? '';
res.write(`data: ${JSON.stringify({ type: 'text', text })}\n\n`);
}
if (event.type === 'citation-start') {
res.write(`data: ${JSON.stringify({ type: 'citation', data: event.delta })}\n\n`);
}
if (event.type === 'message-end') {
res.write(`data: ${JSON.stringify({ type: 'done', usage: event.delta?.usage })}\n\n`);
}
}
res.write('data: [DONE]\n\n');
res.end();
} catch (err) {
res.write(`data: ${JSON.stringify({ type: 'error', message: String(err) })}\n\n`);
res.end();
}
});
```
### Step 5: Cohere Connectors (Data Source Registration)
```typescript
// Register a custom data source for RAG queries
// Connectors allow Cohere to fetch documents from your APIs
// Create a connector
const connector = await cohere.connectors.create({
name: 'internal-docs',
url: 'https://api.yourapp.com/search',
description: 'Internal documentation search',
});
// Use connector in chat for automatic retrieval
const response = await cohere.chat({
model: 'command-a-03-2025',
messages: [{ role: 'user', content: 'How do I reset my password?' }],
connectors: [{ id: connector.connector.id }],
});
// List registered connectors
const connectors = await cohere.connectors.list();
console.log('Registered connectors:', connectors.connectors.length);
```
**Connector endpoint contract:** Your URL receives `POST { query: string }` and must return `{ results: [{ id, text, title?, url? }] }`.
## Event Type Reference
| Event | When | Contains |
|-------|------|----------|
| `message-start` | Stream begins | Message ID |
| `content-start` | Text generation starts | Content index |
| `content-delta` | Each text token | Text chunk |
| `content-end` | Text generation ends | - |
| `citation-start` | Citation found | Source, position |
| `tool-call-start` | Tool call begins | Tool name |
| `tool-call-delta` | Tool args streaming | Argument chunk |
| `tool-call-end` | Tool call complete | - |
| `message-end` | Stream ends | Finish reason, usage |
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Stream drops mid-response | Network timeout | Set higher timeout, add reconnect |
| No citation events | No documents passed | Include `documents` param |
| Tool events but no content | Tool call in progress | Wait for tool results, re-stream |
| Connector returns empty | Bad search endpoint | Test endpoint with `curl` |
## Resources
- [Cohere Streaming Guide](https://docs.cohere.com/docs/streaming)
- [RAG Streaming](https://docs.cohere.com/docs/rag-streaming)
- [Tool Use Streaming](https://docs.cohere.com/docs/tool-use-streaming)
- [Connectors API](https://docs.cohere.com/reference/create-connector)
## Next Steps
For performance optimization, see `cohere-performance-tuning`.
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.