useInferenceResponse.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import {ref} from 'vue'
  2. class ChunkParser {
  3. constructor(tags, name = 'inference_rag_') {
  4. this.name = name
  5. this.tags = tags
  6. this.chunks = []
  7. }
  8. append(chunk, index) {
  9. this.chunks.push({index: index, chunk: chunk})
  10. }
  11. parse(handlers) {
  12. const buffer = this.buffer()
  13. this.tags.forEach(tag => {
  14. const positions = this.position(buffer, tag)
  15. let string = null
  16. if(positions.length > 0) {
  17. const length = `<|${this.name}${tag}|>`.length
  18. string = buffer.substring(positions[0] + length, positions[1] || buffer.length)
  19. }
  20. handlers[tag]?.(string)
  21. })
  22. }
  23. position(input, tag) {
  24. const regex = new RegExp(`<\\|${this.name}${tag}\\|>`, 'g')
  25. return [...input.matchAll(regex)].map(match => match.index)
  26. }
  27. buffer() {
  28. if (!this.chunks.length) return '';
  29. const [{index: firstIndex}] = this.chunks.slice().sort((a, b) => a.index - b.index);
  30. return this.chunks
  31. .slice()
  32. .sort((a, b) => a.index - b.index)
  33. .filter(({index}, i) => index === firstIndex + i)
  34. .map(({chunk}) => chunk)
  35. .join('');
  36. }
  37. reset() {
  38. this.chunks = []
  39. }
  40. }
  41. export function useInferenceResponse() {
  42. const status = ref(null)
  43. const think = ref(null)
  44. const content = ref(null)
  45. const parser = new ChunkParser(['think', 'content', 'fields'])
  46. function append(chunk, index) {
  47. parser.append(chunk, index)
  48. parser.parse({
  49. think: text => think.value = text,
  50. content: text => content.value = text,
  51. fields: () => {
  52. },
  53. })
  54. }
  55. function setStatus(value) {
  56. status.value = value
  57. }
  58. function reset() {
  59. think.value = null
  60. content.value = null
  61. status.value = null
  62. parser.reset()
  63. }
  64. return {think, content, status, append, reset, setStatus}
  65. }