-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathvercel-ai-stream.ts
More file actions
72 lines (60 loc) · 1.89 KB
/
Copy pathvercel-ai-stream.ts
File metadata and controls
72 lines (60 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Vercel AI SDK Streaming Example
*
* Scrapes a webpage and streams a summary using the Vercel AI SDK.
*
* Usage:
* npx tsx ai-tools/vercel-ai-stream.ts https://example.com
*
* Requirements:
* - Set OPENAI_API_KEY environment variable
*/
import { ReaderClient } from "@vakra-dev/reader";
import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
async function main() {
const url = process.argv[2] || "https://example.com";
console.log(`Scraping ${url}...\n`);
// Check for API key
if (!process.env.OPENAI_API_KEY) {
console.error("Error: OPENAI_API_KEY environment variable is required");
process.exit(1);
}
const reader = new ReaderClient({ verbose: true });
try {
// Step 1: Scrape the webpage
const result = await reader.scrape({
urls: [url],
formats: ["markdown"],
});
const content = result.data[0]?.markdown;
if (!content) {
console.error("No content scraped");
process.exit(1);
}
console.log(`Scraped ${content.length} characters`);
console.log("Streaming summary...\n");
console.log("=== STREAMING SUMMARY ===\n");
// Step 2: Stream summary with Vercel AI SDK
const { textStream } = await streamText({
model: openai("gpt-4o-mini"),
system:
"You are a helpful assistant that summarizes web content. Provide a concise summary in 2-3 paragraphs.",
prompt: `Please summarize the following webpage content:\n\n${content.slice(0, 10000)}`,
maxTokens: 500,
});
// Stream the response to stdout
for await (const chunk of textStream) {
process.stdout.write(chunk);
}
console.log("\n\n=== METADATA ===");
console.log(`Source: ${url}`);
console.log(`Content length: ${content.length} chars`);
} catch (error: any) {
console.error("Error:", error.message);
process.exit(1);
} finally {
await reader.close();
}
}
main();