abort-single-request.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { Ollama } from 'ollama'
  2. // Create multiple ollama clients
  3. const client1 = new Ollama()
  4. const client2 = new Ollama()
  5. // Set a timeout to abort just the first request after 5 seconds
  6. setTimeout(() => {
  7. console.log('\nAborting dragons story...\n')
  8. // abort the first client
  9. client1.abort()
  10. }, 5000) // 5000 milliseconds = 5 seconds
  11. // Start multiple concurrent streaming requests with different clients
  12. Promise.all([
  13. client1.generate({
  14. model: 'llama3.2',
  15. prompt: 'Write a long story about dragons',
  16. stream: true,
  17. }).then(
  18. async (stream) => {
  19. console.log(' Starting stream for dragons story...')
  20. for await (const chunk of stream) {
  21. process.stdout.write(' 1> ' + chunk.response)
  22. }
  23. }
  24. ),
  25. client2.generate({
  26. model: 'llama3.2',
  27. prompt: 'Write a short story about wizards',
  28. stream: true,
  29. }).then(
  30. async (stream) => {
  31. console.log(' Starting stream for wizards story...')
  32. for await (const chunk of stream) {
  33. process.stdout.write(' 2> ' + chunk.response)
  34. }
  35. }
  36. ),
  37. ]).catch(error => {
  38. if (error.name === 'AbortError') {
  39. console.log('Dragons story request has been aborted')
  40. } else {
  41. console.error('An error occurred:', error)
  42. }
  43. })