mirror of
https://ghfast.top/https://github.com/discourse/discourse-ai.git
synced 2026-07-15 11:27:11 +08:00
This re-implements tool support in DiscourseAi::Completions::Llm #generate
Previously tool support was always returned via XML and it would be the responsibility of the caller to parse XML
New implementation has the endpoints return ToolCall objects.
Additionally this simplifies the Llm endpoint interface and gives it more clarity. Llms must implement
decode, decode_chunk (for streaming)
It is the implementers responsibility to figure out how to decode chunks, base no longer implements. To make this easy we ship a flexible json decoder which is easy to wire up.
Also (new)
Better debugging for PMs, we now have a next / previous button to see all the Llm messages associated with a PM
Token accounting is fixed for vllm (we were not correctly counting tokens)
48 lines
1.1 KiB
Ruby
48 lines
1.1 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
module DiscourseAi
|
|
module Completions
|
|
# will work for anthropic and open ai compatible
|
|
class JsonStreamDecoder
|
|
attr_reader :buffer
|
|
|
|
LINE_REGEX = /data: ({.*})\s*$/
|
|
|
|
def initialize(symbolize_keys: true, line_regex: LINE_REGEX)
|
|
@symbolize_keys = symbolize_keys
|
|
@buffer = +""
|
|
@line_regex = line_regex
|
|
end
|
|
|
|
def <<(raw)
|
|
@buffer << raw.to_s
|
|
rval = []
|
|
|
|
split = @buffer.scan(/.*\n?/)
|
|
split.pop if split.last.blank?
|
|
|
|
@buffer = +(split.pop.to_s)
|
|
|
|
split.each do |line|
|
|
matches = line.match(@line_regex)
|
|
next if !matches
|
|
rval << JSON.parse(matches[1], symbolize_names: @symbolize_keys)
|
|
end
|
|
|
|
if @buffer.present?
|
|
matches = @buffer.match(@line_regex)
|
|
if matches
|
|
begin
|
|
rval << JSON.parse(matches[1], symbolize_names: @symbolize_keys)
|
|
@buffer = +""
|
|
rescue JSON::ParserError
|
|
# maybe it is a partial line
|
|
end
|
|
end
|
|
end
|
|
|
|
rval
|
|
end
|
|
end
|
|
end
|
|
end
|