discourse-ai/spec/lib/completions/endpoints/hugging_face_spec.rb
Sam 6ddc17fd61
DEV: port directory structure to Zeitwerk (#319)
Previous to this change we relied on explicit loading for a files in Discourse AI.

This had a few downsides:

- Busywork whenever you add a file (an extra require relative)
- We were not keeping to conventions internally ... some places were OpenAI others are OpenAi
- Autoloader did not work which lead to lots of full application broken reloads when developing.

This moves all of DiscourseAI into a Zeitwerk compatible structure.

It also leaves some minimal amount of manual loading (automation - which is loading into an existing namespace that may or may not be there)

To avoid needing /lib/discourse_ai/... we mount a namespace thus we are able to keep /lib pointed at ::DiscourseAi

Various files were renamed to get around zeitwerk rules and minimize usage of custom inflections

Though we can get custom inflections to work it is not worth it, will require a Discourse core patch which means we create a hard dependency.
2023-11-29 15:17:46 +11:00

69 lines
1.9 KiB
Ruby

# frozen_string_literal: true
require_relative "endpoint_examples"
RSpec.describe DiscourseAi::Completions::Endpoints::HuggingFace do
subject(:model) { described_class.new(model_name, DiscourseAi::Tokenizer::Llama2Tokenizer) }
let(:model_name) { "Llama2-*-chat-hf" }
let(:prompt) { <<~TEXT }
[INST]<<SYS>>You are a helpful bot.<</SYS>>[/INST]
[INST]Write 3 words[/INST]
TEXT
let(:request_body) do
model
.default_options
.merge(inputs: prompt)
.tap { |payload| payload[:parameters][:max_new_tokens] = 2_000 - model.prompt_size(prompt) }
.to_json
end
let(:stream_request_body) { request_body }
before { SiteSetting.ai_hugging_face_api_url = "https://test.dev" }
def response(content)
{ generated_text: content }
end
def stub_response(prompt, response_text)
WebMock
.stub_request(:post, "#{SiteSetting.ai_hugging_face_api_url}/generate")
.with(body: request_body)
.to_return(status: 200, body: JSON.dump(response(response_text)))
end
def stream_line(delta, finish_reason: nil)
+"data: " << {
token: {
id: 29_889,
text: delta,
logprob: -0.08319092,
special: !!finish_reason,
},
generated_text: finish_reason ? response_text : nil,
details: nil,
}.to_json
end
def stub_streamed_response(prompt, deltas)
chunks =
deltas.each_with_index.map do |_, index|
if index == (deltas.length - 1)
stream_line(deltas[index], finish_reason: true)
else
stream_line(deltas[index])
end
end
chunks = chunks.join("\n\n")
WebMock
.stub_request(:post, "#{SiteSetting.ai_hugging_face_api_url}/generate_stream")
.with(body: request_body)
.to_return(status: 200, body: chunks)
end
it_behaves_like "an endpoint that can communicate with a completion service"
end