Module: PWN::AI::OpenWebUI

Defined in:
lib/pwn/ai/open_web_ui.rb

Overview

Client for Open WebUI's REST API via PWN::Plugins::TransparentBrowser (:rest).

Live Open WebUI routes (gateway base_uri, no trailing slash):

GET  /api/v1/models              OpenAI-compat model list (:data)
POST /api/v1/chat/completions    OpenAI-compat chat (SSE when stream:true)
POST /api/chat/completions       alias of the above
GET  /ollama/api/tags            proxied Ollama tags (:models)
POST /ollama/api/chat            proxied Ollama chat (NDJSON when stream:true)
POST /ollama/api/embed           proxied embeddings (see PWN::MemoryIndex)

Bare /api/chat and bare /v1/* are NOT API routes on stock Open WebUI — they 405 or return the SPA HTML shell.

Class Method Summary collapse

Class Method Details

.authorsObject

Author(s)

0day Inc. support@0dayinc.com



678
679
680
681
682
# File 'lib/pwn/ai/open_web_ui.rb', line 678

public_class_method def self.authors
  "AUTHOR(S):
    0day Inc. <support@0dayinc.com>
  "
end

.chat(opts = {}) ⇒ Object

Supported Method Parameters

response = PWN::AI::OpenWebUI.chat( request: 'required - message to Open WebUI' model: 'optional - model to use for text generation (defaults to PWN::Env[:openwebui][:model])', temp: 'optional - creative response float (deafults to PWN::Env[:openwebui][:temp])', system_role_content: 'optional - context to set up the model behavior for conversation (Default: PWN::Env[:openwebui][:system_role_content])', response_history: 'optional - pass response back in to have a conversation', speak_answer: 'optional speak answer using PWN::Plugins::Voice.text_to_speech (Default: nil)', timeout: 'optional timeout in seconds (defaults to 900)', spinner: 'optional - display spinner (defaults to false)' )



589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# File 'lib/pwn/ai/open_web_ui.rb', line 589

public_class_method def self.chat(opts = {})
  engine = PWN::Env[:ai][:openwebui]
  request = opts[:request]
  max_prompt_length = engine[:max_prompt_length] ||= 1_000_000
  request_trunc_idx = ((max_prompt_length - 1) / 3.36).floor
  request = request[0..request_trunc_idx]

  model = opts[:model] ||= engine[:model]
  raise 'ERROR: Model is required.  Call #get_models method for details' unless real_config_value?(value: model)

  temp = opts[:temp].to_f ||= engine[:temp].to_f
  temp = 1 if temp.zero?

  # Open WebUI OpenAI-compat path (NOT bare v1/* — that hits the SPA).
  rest_call = 'api/v1/chat/completions'

  response_history = opts[:response_history]

  max_tokens = response_history[:usage][:total_tokens] unless response_history.nil?

  system_role_content = opts[:system_role_content] ||= engine[:system_role_content]

  system_role = {
    role: 'system',
    content: system_role_content
  }

  user_role = {
    role: 'user',
    content: request
  }

  response_history ||= { choices: [system_role] }
  choices_len = response_history[:choices].length

  http_body = {
    model: model,
    messages: [system_role],
    temperature: temp,
    stream: true
  }

  if response_history[:choices].length > 1
    response_history[:choices][1..].each do |message|
      http_body[:messages].push(message)
    end
  end

  http_body[:messages].push(user_role)

  timeout = opts[:timeout]
  spinner = opts[:spinner]

  response = openwebui_rest_call(
    http_method: :post,
    rest_call: rest_call,
    http_body: http_body,
    timeout: timeout,
    spinner: spinner
  )

  json_resp = JSON.parse(response, symbolize_names: true)
  assistant_resp = json_resp[:choices].first[:message]
  if assistant_resp.is_a?(Hash)
    content = assistant_resp[:content].to_s
    thinking = assistant_resp[:thinking].to_s
    thinking = assistant_resp[:reasoning_content].to_s if thinking.empty?
    assistant_resp = assistant_resp.merge(content: visible_from_thinking(thinking: thinking)) if content.strip.empty? && !thinking.strip.empty?
  end
  json_resp[:choices] = http_body[:messages]
  json_resp[:choices].push(assistant_resp)

  speak_answer = true if opts[:speak_answer]

  if speak_answer
    answer = assistant_resp[:content]
    text_path = "/tmp/#{SecureRandom.hex}.pwn_voice"
    File.write(text_path, answer)
    PWN::Plugins::Voice.text_to_speech(text_path: text_path)
    File.unlink(text_path)
  end

  json_resp
rescue StandardError => e
  raise e
end

.chat_with_tools(opts = {}) ⇒ Object

Supported Method Parameters

response = PWN::AI::OpenWebUI.chat_with_tools( messages: 'required - full OpenAI-format messages array (system/user/assistant/tool)', tools: 'optional - OpenAI tools array [function:{...}]', tool_choice: 'optional - "auto" | "none" | function:{name:..}', model: 'optional - overrides PWN::Env[:openwebui][:model]', temp: 'optional - temperature (defaults to PWN::Env[:openwebui][:temp] || 1)', timeout: 'optional - seconds (default 900)', spinner: 'optional - display spinner (default false)' )

Hits Open WebUI's PROXIED Ollama POST /ollama/api/chat so options.num_ctx / num_predict / keep_alive take effect. Streaming is ON; openwebui_rest_call assembles NDJSON chunks back into a single response. Bare POST /api/chat is not an API route on stock Open WebUI (405).



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/pwn/ai/open_web_ui.rb', line 515

public_class_method def self.chat_with_tools(opts = {})
  engine   = PWN::Env[:ai][:openwebui]
  messages = normalize_messages_for_ollama(messages: opts[:messages])
  raise 'ERROR: messages array is required' if messages.nil? || messages.empty?

  model = opts[:model] ||= engine[:model]
  raise 'ERROR: Model is required.  Call #get_models method for details' unless real_config_value?(value: model)

  temp = opts[:temp].to_f
  temp = engine[:temp].to_f.nonzero? || 1 if temp.zero?

  tools_present = opts[:tools] && !opts[:tools].empty?
  tool_temp     = (engine[:tool_temp] || 0.1).to_f
  num_ctx       = (engine[:num_ctx]   || 32_768).to_i
  num_predict   = (engine[:num_predict] || 4_096).to_i
  keep_alive    = engine[:keep_alive] || '30m'

  http_body = {
    model: model,
    messages: messages,
    stream: true,
    keep_alive: keep_alive,
    options: {
      num_ctx: num_ctx,
      num_predict: num_predict,
      temperature: tools_present ? tool_temp : temp
    }
  }
  if tools_present
    http_body[:tools] = opts[:tools]
    fmt = engine[:format]
    http_body[:format] = fmt unless fmt.nil? || fmt.to_s.empty?
  end
  http_body[:tool_choice] = opts[:tool_choice] if opts[:tool_choice]

  response = openwebui_rest_call(
    http_method: :post,
    rest_call: 'ollama/api/chat',
    http_body: http_body,
    timeout: opts[:timeout],
    spinner: opts[:spinner]
  )
  raise 'ERROR: Open WebUI chat_with_tools received empty response from openwebui_rest_call' if response.nil? || (response.respond_to?(:empty?) && response.empty?)

  json_resp = JSON.parse(response, symbolize_names: true)
  msg = json_resp[:message] || json_resp.dig(:choices, 0, :message)
  if msg.is_a?(Hash)
    content = msg[:content].to_s
    thinking = msg[:thinking].to_s
    thinking = msg[:reasoning_content].to_s if thinking.empty?
    tcalls = Array(msg[:tool_calls])
    msg = msg.merge(content: visible_from_thinking(thinking: thinking)) if content.strip.empty? && !thinking.strip.empty? && tcalls.empty?
  end
  json_resp[:choices] = [{ message: msg }] if msg && !json_resp.key?(:choices)
  json_resp[:assistant_message] = msg
  raise "ERROR: Open WebUI response missing message/choices: #{json_resp.inspect[0, 400]}" if msg.nil?

  json_resp
rescue StandardError => e
  raise e
end

.get_modelsObject

Supported Method Parameters

response = PWN::AI::OpenWebUI.get_models



406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/pwn/ai/open_web_ui.rb', line 406

public_class_method def self.get_models
  # Prefer Open WebUI's own OpenAI-compat catalog; fall back to the
  # proxied Ollama tag list when needed.
  raw = openwebui_rest_call(rest_call: 'api/v1/models')
  parsed = JSON.parse(raw, symbolize_names: true)
  return parsed[:data] if parsed[:data].is_a?(Array)
  return parsed[:models] if parsed[:models].is_a?(Array)

  raw = openwebui_rest_call(rest_call: 'ollama/api/tags')
  JSON.parse(raw, symbolize_names: true)[:models]
rescue StandardError => e
  raise e
end

.helpObject

Display Usage for this Module



686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
# File 'lib/pwn/ai/open_web_ui.rb', line 686

public_class_method def self.help
  puts "USAGE:
    models = #{self}.get_models

    response = #{self}.chat(
      request: 'required - message to Open WebUI',
      model: 'optional - model to use for text generation (defaults to PWN::Env[:ai][:openwebui][:model])',
      temp: 'optional - creative response float (defaults to PWN::Env[:ai][:openwebui][:temp])',
      system_role_content: 'optional - context to set up the model behavior for conversation (Default: PWN::Env[:ai][:openwebui][:system_role_content])',
      response_history: 'optional - pass response back in to have a conversation',
      speak_answer: 'optional speak answer using PWN::Plugins::Voice.text_to_speech (Default: nil)',
      timeout: 'optional - timeout in seconds (defaults to 900)',
      spinner: 'optional - display spinner (defaults to false)'
    )

    response = #{self}.chat_with_tools(
      messages: 'required - OpenAI-format messages array',
      tools: 'optional - OpenAI tools array',
      model: 'optional - overrides PWN::Env[:ai][:openwebui][:model]',
      temp: 'optional - temperature',
      timeout: 'optional - seconds (default 900)',
      spinner: 'optional - display spinner (default false)'
    )

    #{self}.authors
  "
end