Skip to content

AI page summaries #3217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
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
5 changes: 5 additions & 0 deletions .changeset/late-cherries-rule.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"gitbook": minor
---

Adds AI sidebar with recommendations based on browsing behaviour
1 change: 1 addition & 0 deletions packages/gitbook-v2/src/lib/data/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1394,6 +1394,7 @@ async function* streamAIResponse(
input: params.input,
output: params.output,
model: params.model,
tools: params.tools,
});

for await (const event of res) {
Expand Down
1 change: 1 addition & 0 deletions packages/gitbook-v2/src/lib/data/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,5 +189,6 @@ export interface GitBookDataFetcher {
input: api.AIMessageInput[];
output: api.AIOutputFormat;
model: api.AIModel;
tools?: api.AIToolCapabilities;
}): AsyncGenerator<api.AIStreamResponse, void, unknown>;
}
97 changes: 97 additions & 0 deletions packages/gitbook/src/components/Adaptive/AIPageSummary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { useVisitedPages } from '../Insights';
import { usePageContext } from '../PageContext';
import { useAdaptiveContext } from './AdaptiveContext';
import { streamPageSummary } from './server-actions/streamPageSummary';

export function AIPageSummary() {
const { toggle, setLoading, setToggle } = useAdaptiveContext();

const currentPage = usePageContext();
const visitedPages = useVisitedPages((state) => state.pages);
const visitedPagesRef = useRef(visitedPages);

const [summary, setSummary] = useState<{
keyFacts?: string;
bigPicture?: string;
}>({});

useEffect(() => {
if (!summary.keyFacts) setLoading(true);
if (!visitedPages?.length) return;

// Skip if the visited pages haven't changed
if (JSON.stringify(visitedPagesRef.current) === JSON.stringify(visitedPages)) return;

visitedPagesRef.current = visitedPages;

let canceled = false;
setLoading(true);

(async () => {
const stream = await streamPageSummary({
currentPage: {
id: currentPage.pageId,
title: currentPage.title,
},
currentSpace: {
id: currentPage.spaceId,
},
visitedPages: visitedPages,
});

for await (const summary of stream) {
if (canceled) return;

setSummary(summary);
}
})().finally(() => {
setLoading(false);
});

return () => {
canceled = true;
};
}, [currentPage, visitedPages, toggle, setLoading, setToggle]);

const shimmerBlocks = [20, 35, 25, 10, 45, 30, 30, 35, 25, 10, 40, 30]; // Widths in percentages

return (
toggle.open && (
<div className="flex min-w-64 animate-fadeIn flex-col gap-4">
{summary.keyFacts ? (
<div>
<h5 className="mb-0.5 font-semibold text-tint-subtle text-xs uppercase">
Key facts
</h5>
{summary.keyFacts}
</div>
) : (
<div className="flex w-full flex-wrap gap-2">
{shimmerBlocks.map((width, index) => (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: No other distinguishing feature available
key={index}
className="h-4 animate-pulse rounded bg-tint-active"
style={{
width: `${width}%`,
animationDelay: `${index * 0.1}s`,
}}
/>
))}
</div>
)}

{visitedPages.length > 1 && summary?.bigPicture ? (
<div>
<h5 className="mb-0.5 font-semibold text-tint-subtle text-xs uppercase">
Big Picture
</h5>
{summary?.bigPicture}
</div>
) : null}
</div>
)
);
}
71 changes: 71 additions & 0 deletions packages/gitbook/src/components/Adaptive/AdaptiveContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
'use client';

import React from 'react';

type AdaptiveContextType = {
loading: boolean;
setLoading: (loading: boolean) => void;
toggle: {
open: boolean;
manual: boolean;
};
setToggle: (toggle: { open: boolean; manual: boolean }) => void;
};

export const AdaptiveContext = React.createContext<AdaptiveContextType | null>(null);

/**
* Client side context provider to pass information about the current page.
*/
export function AdaptiveContextProvider({ children }: { children: React.ReactNode }) {
const [loading, setLoading] = React.useState(true);

// Start with a default state that works for SSR
const [toggle, setToggle] = React.useState({
open: false, // Default to open for SSR
manual: false,
});

// Update the toggle state on the client side only
React.useEffect(() => {
// Check for mobile only on the client
const handleResize = () => {
if (!toggle.manual) {
const isMobile = window.innerWidth < 1280;
setToggle((prev) => ({
...prev,
open: !isMobile,
}));
}
};
handleResize();

window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [toggle.manual]);

React.useEffect(() => {
if (toggle.open) {
document.body.classList.add('adaptive-pane');
} else {
document.body.classList.remove('adaptive-pane');
}
}, [toggle.open]);

return (
<AdaptiveContext.Provider value={{ loading, setLoading, toggle, setToggle }}>
{children}
</AdaptiveContext.Provider>
);
}

/**
* Hook to use the adaptive context.
*/
export function useAdaptiveContext() {
const context = React.useContext(AdaptiveContext);
if (!context) {
throw new Error('useAdaptiveContext must be used within a AdaptiveContextProvider');
}
return context;
}
21 changes: 21 additions & 0 deletions packages/gitbook/src/components/Adaptive/AdaptivePane.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use client';

import { tcls } from '@/lib/tailwind';
import { AIPageSummary } from './AIPageSummary';
import { useAdaptiveContext } from './AdaptiveContext';
import { AdaptivePaneHeader } from './AdaptivePaneHeader';
export function AdaptivePane() {
const { toggle } = useAdaptiveContext();

return (
<div
className={tcls(
'flex shrink-0 flex-col gap-4 overflow-x-hidden rounded-md straight-corners:rounded-none bg-tint-subtle ring-1 ring-tint-subtle ring-inset transition-all duration-300',
toggle.open ? 'max-h px-4 py-4 xl:w-72' : 'px-4 py-3 xl:w-56'
)}
>
<AdaptivePaneHeader />
<AIPageSummary />
</div>
);
}
46 changes: 46 additions & 0 deletions packages/gitbook/src/components/Adaptive/AdaptivePaneHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use client';

import { tcls } from '@/lib/tailwind';
import { AnimatePresence, motion } from 'framer-motion';
import { Button, Loading } from '../primitives';
import { useAdaptiveContext } from './AdaptiveContext';

export function AdaptivePaneHeader() {
const { loading, toggle, setToggle } = useAdaptiveContext();

return (
<div className="flex flex-row items-center gap-3 rounded-md straight-corners:rounded-none transition-all duration-500">
<div className="flex grow flex-col">
<h4 className="flex items-center gap-1.5 font-semibold ">
<Loading className="size-4 text-tint-subtle" busy={loading} />
For you
</h4>
<AnimatePresence initial={false} mode="wait">
<motion.h5
key={loading ? 'loading' : 'loaded'}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.3 }}
className="text-tint-subtle text-xs"
>
{loading ? 'Basing on your context...' : 'Based on your context'}
</motion.h5>
</AnimatePresence>
</div>
<Button
variant="blank"
className={tcls('px-2 *:transition-transform', !toggle.open && '*:-rotate-45')}
iconOnly
label="Close"
icon="close"
onClick={() =>
setToggle({
open: !toggle.open,
manual: true,
})
}
/>
</div>
);
}
3 changes: 3 additions & 0 deletions packages/gitbook/src/components/Adaptive/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export * from './AIPageLinkSummary';
export * from './AIPageSummary';
export * from './AdaptiveContext';
export * from './AdaptivePane';
12 changes: 10 additions & 2 deletions packages/gitbook/src/components/Adaptive/server-actions/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
'use server';
import { type AIMessageInput, AIModel, type AIStreamResponse } from '@gitbook/api';
import {
type AIMessageInput,
AIModel,
type AIStreamResponse,
type AIToolCapabilities,
} from '@gitbook/api';
import type { GitBookBaseContext } from '@v2/lib/context';
import { EventIterator } from 'event-iterator';
import type { MaybePromise } from 'p-map';
Expand Down Expand Up @@ -47,11 +52,13 @@ export async function streamGenerateObject<T>(
schema,
messages,
model = AIModel.Fast,
tools = {},
}: {
schema: z.ZodSchema<T>;
messages: AIMessageInput[];
model?: AIModel;
previousResponseId?: string;
tools?: AIToolCapabilities;
}
) {
const rawStream = context.dataFetcher.streamAIResponse({
Expand All @@ -62,12 +69,13 @@ export async function streamGenerateObject<T>(
type: 'object',
schema: zodToJsonSchema(schema),
},
tools,
model,
});

let json = '';
return parseResponse<DeepPartial<T>>(rawStream, (event) => {
if (event.type === 'response_object') {
if (event.type === 'response_object' && event.jsonChunk) {
json += event.jsonChunk;

const parsed = partialJson.parse(json, partialJson.ALL);
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './streamLinkPageSummary';
export * from './streamPageSummary';
Loading
Loading