Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions client/src/components/chat/ConsensusResponses.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { useState } from 'react';
import { ChevronDown, ChevronRight } from 'lucide-react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
interface ConsensusResponse {
type: 'consensus-response';
provider: string;
model: string;
content: string;
}

function parseConsensusResponses(annotations: unknown[]): ConsensusResponse[] {
return annotations.filter(
(value): value is ConsensusResponse =>
typeof value === 'object' &&
value !== null &&
(value as Record<string, unknown>).type === 'consensus-response'
);
}

function formatModelName(model: string): string {
return model.split('/').pop() || model;
}

interface ConsensusResponsesProps {
annotations: unknown[];
}

export function ConsensusResponses({ annotations }: ConsensusResponsesProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [expandedModel, setExpandedModel] = useState<number | null>(null);

const responses = parseConsensusResponses(annotations);

if (responses.length === 0) return null;

return (
<div className="mt-3 border-t border-border/50 pt-3">
<button
onClick={() => setIsExpanded(!isExpanded)}
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{isExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
{responses.length} model responses
</button>

{isExpanded && (
<div className="mt-2 space-y-2">
{responses.map((response, index) => (
<div
key={index}
className="rounded-md border border-border/50 bg-secondary/30"
>
<button
onClick={() =>
setExpandedModel(expandedModel === index ? null : index)
}
className="flex items-center gap-1.5 w-full px-3 py-2 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
>
{expandedModel === index ? (
<ChevronDown className="h-3 w-3 shrink-0" />
) : (
<ChevronRight className="h-3 w-3 shrink-0" />
)}
{formatModelName(response.model)}
</button>

{expandedModel === index && (
<div className="px-3 pb-3 text-sm prose-sm">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code({ inline, className, children, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter
style={vscDarkPlus}
language={match[1]}
PreTag="div"
{...props}
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
}}
>
{response.content}
</ReactMarkdown>
</div>
)}
</div>
))}
</div>
)}
</div>
);
}
6 changes: 6 additions & 0 deletions client/src/components/chat/MessageBubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { cn } from '@/lib/utils';
import type { Message } from '@ai-sdk/react';
import type { Attachment } from '@/lib/types';
import { MessageAttachment } from './MessageAttachment';
import { ConsensusResponses } from './ConsensusResponses';

interface MessageBubbleProps {
message: Message & { attachments?: Attachment[] };
Expand Down Expand Up @@ -65,6 +66,11 @@ export function MessageBubble({ message }: MessageBubbleProps) {
{message.content}
</ReactMarkdown>
)}

{/* Consensus individual responses */}
{!isUser && message.annotations && message.annotations.length > 0 && (
<ConsensusResponses annotations={message.annotations} />
)}
</div>
</div>
);
Expand Down
34 changes: 0 additions & 34 deletions client/src/components/ui/icons/BirdIcon.tsx

This file was deleted.

27 changes: 19 additions & 8 deletions server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express from 'express';
import cors from 'cors';
import { streamText } from 'ai';
import { streamText, pipeDataStreamToResponse } from 'ai';
import { config, validateProviderConfig } from './config.js';
import {
getProvider,
Expand Down Expand Up @@ -149,29 +149,40 @@ app.post('/api/chat', async (req, res) => {
// Check for workflow handler
const workflowHandler = getWorkflowHandler(workflowId);

let result;

if (workflowHandler) {
result = await workflowHandler({
const { result, annotations } = await workflowHandler({
messages: multimodalMessages,
toolConfig: toolConfig || {},
systemContext,
provider,
model,
});

// Use standalone pipeDataStreamToResponse to inject annotations
pipeDataStreamToResponse(res, {
execute: (dataStream) => {
// Write annotations before merging the stream
if (annotations) {
for (const annotation of annotations) {
dataStream.writeMessageAnnotation(annotation);
}
}
result.mergeIntoDataStream(dataStream);
},
});
} else {
// Standard chat flow
const providerInstance = getProvider(provider, model);

result = await streamText({
const result = await streamText({
model: providerInstance,
messages: multimodalMessages as any,
...(systemContext && { system: systemContext }),
});
}

// Use Vercel Data Stream Protocol (compatible with useChat hook)
result.pipeDataStreamToResponse(res);
// Use Vercel Data Stream Protocol (compatible with useChat hook)
result.pipeDataStreamToResponse(res);
}
} catch (error) {
console.error('Chat error:', error);

Expand Down
10 changes: 8 additions & 2 deletions server/src/lib/workflow-router.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { StreamTextResult } from 'ai';
import { StreamTextResult, JSONValue } from 'ai';

// Workflow result wraps a stream with optional annotations
export interface WorkflowResult {
result: StreamTextResult<any, any>;
annotations?: JSONValue[];
}

// Workflow handler function signature
// Note: messages are pre-converted to multimodal format by the router
Expand All @@ -8,7 +14,7 @@ export type WorkflowHandler = (params: {
systemContext?: string;
provider: string;
model: string;
}) => Promise<StreamTextResult<any, any>>;
}) => Promise<WorkflowResult>;

// Workflow registry
const workflowRegistry = new Map<string, WorkflowHandler>();
Expand Down
13 changes: 11 additions & 2 deletions server/src/workflows/consensus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getProvider } from '../providers.js';
import {
registerWorkflow,
type WorkflowHandler,
type WorkflowResult,
} from '../lib/workflow-router.js';
import type { Message } from '../types.js';

Expand Down Expand Up @@ -48,7 +49,7 @@ export async function executeConsensusWorkflow(params: {
systemContext?: string;
provider: string;
model: string;
}) {
}): Promise<WorkflowResult> {
const { messages, toolConfig, systemContext, provider, model } = params;

// Extract models from tool config
Expand Down Expand Up @@ -151,7 +152,15 @@ Provide your synthesized response now.`;
messages: [{ role: 'user', content: synthesisPrompt }],
});

return result;
// 8. Return result with individual responses as annotations
const annotations = responses.map((r) => ({
type: 'consensus-response' as const,
provider: r.provider,
model: r.model,
content: r.content,
}));

return { result, annotations };
}

// Register the workflow
Expand Down
3 changes: 2 additions & 1 deletion server/tests/chat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ beforeAll(() => {
process.env.GOOGLE_API_KEY = 'test-key';
});

// Mock streamText
// Mock streamText and pipeDataStreamToResponse
vi.mock('ai', () => ({
streamText: vi.fn(),
pipeDataStreamToResponse: vi.fn(),
}));

describe('POST /api/chat', () => {
Expand Down