toolUse.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { openai } from '@ai-sdk/openai'
  2. import { generateText, jsonSchema as toJSONSChema, tool } from 'ai'
  3. import { chromium } from 'playwright'
  4. import { z } from 'zod'
  5. import LLMScraper from './../src'
  6. const model = openai('gpt-4o-mini')
  7. const scraper = new LLMScraper(model)
  8. const { text } = await generateText({
  9. model,
  10. tools: {
  11. scrapeWebsite: tool({
  12. description: 'Scrape a website with a given schema and URL',
  13. parameters: z.object({
  14. url: z.string(),
  15. jsonSchema: z.string(),
  16. }),
  17. execute: async ({ url, jsonSchema }) => {
  18. console.log('scraping website', url)
  19. console.log('with schema', jsonSchema)
  20. // Launch a browser instance
  21. const browser = await chromium.launch()
  22. // Open new page
  23. const page = await browser.newPage()
  24. await page.goto('https://news.ycombinator.com')
  25. // Parse jsonSchema
  26. const schema = toJSONSChema(JSON.parse(jsonSchema))
  27. // Run the scraper
  28. const result = await scraper.run(page, schema)
  29. await page.close()
  30. await browser.close()
  31. // Feed the result back to the model
  32. return result.data
  33. },
  34. }),
  35. },
  36. maxSteps: 2,
  37. prompt: 'List top stories from HackerNews frontpage and summarize them',
  38. })
  39. console.log(text)