specific-request.ts 760 B

12345678910111213141516171819202122232425262728293031
  1. import ollama from 'ollama'
  2. import { AbortableAsyncIterator } from '../../src/utils'
  3. let stream: AbortableAsyncIterator<object>
  4. // Set a timeout to abort the request after 1 second
  5. setTimeout(() => {
  6. console.log('\nAborting request...\n')
  7. stream.abort()
  8. }, 1000) // 1000 milliseconds = 1 second
  9. ollama.generate({
  10. model: 'llama3.1',
  11. prompt: 'Write a long story',
  12. stream: true,
  13. }).then(
  14. async (_stream) => {
  15. stream = _stream
  16. for await (const chunk of stream) {
  17. process.stdout.write(chunk.response)
  18. }
  19. }
  20. ).catch(
  21. (error) => {
  22. if (error.name === 'AbortError') {
  23. console.log('The request has been aborted')
  24. } else {
  25. console.error('An error occurred:', error)
  26. }
  27. }
  28. )