codegen.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { chromium } from 'playwright'
  2. import { z } from 'zod'
  3. import { openai } from '@ai-sdk/openai'
  4. import LLMScraper from './../src'
  5. // Launch a browser instance
  6. const browser = await chromium.launch()
  7. // Initialize LLM provider
  8. const llm = openai('gpt-4o-mini')
  9. // Create a new LLMScraper
  10. const scraper = new LLMScraper(llm)
  11. // Open new page
  12. const page = await browser.newPage()
  13. await page.goto('https://news.ycombinator.com')
  14. // Define schema to extract contents into
  15. const schema = z.object({
  16. top: z
  17. .array(
  18. z.object({
  19. title: z.string(),
  20. points: z.number(),
  21. by: z.string(),
  22. commentsURL: z.string(),
  23. })
  24. )
  25. .length(5)
  26. .describe('Top 5 stories on Hacker News'),
  27. })
  28. // Generate code and run it on the page
  29. const { code } = await scraper.generate(page, schema, {
  30. format: 'raw_html',
  31. })
  32. console.log('code', code)
  33. const result = await page.evaluate(code)
  34. const data = schema.parse(result)
  35. // Show the parsed result
  36. console.log('result', data)
  37. await page.close()
  38. await browser.close()