Class: Chocomint::Tools::FetchUrl

Inherits:
Base
  • Object
show all
Defined in:
lib/chocomint/tools/fetch_url.rb

Overview

指定 URL のウェブページを取得し、本文テキストを抽出したうえで、 別途 LLM (ChatClient#extract) に「ユーザーの目的に沿った情報」を要約・抽出させる。

取得は標準ライブラリ net/http のみ (依存追加なし)。http/https に限定し、 リダイレクトを数回だけ追い、応答サイズに上限を設ける。生 HTML をそのまま LLM に流すとノイズが多く読み取りにくいため、タグ除去で本文テキスト化してから渡す。

Constant Summary collapse

MAX_REDIRECTS =
5
DEFAULT_MAX_BYTES =

取得を許す本文サイズの上限 (バイト)。巨大ページで LLM 入力が溢れるのを防ぐ。

2_000_000
EXTRACT_TEXT_LIMIT =

LLM に渡す抽出後テキストの上限 (文字)。小型ローカルモデルの文脈長に配慮する。

12_000

Instance Method Summary collapse

Methods inherited from Base

#to_tool_definition

Constructor Details

#initialize(chat_client:, timeout_sec: 30, max_bytes: DEFAULT_MAX_BYTES) ⇒ FetchUrl

chat_client: ChatClient (extract を持つ)。timeout_sec: 取得タイムアウト。



23
24
25
26
27
# File 'lib/chocomint/tools/fetch_url.rb', line 23

def initialize(chat_client:, timeout_sec: 30, max_bytes: DEFAULT_MAX_BYTES)
  @chat_client = chat_client
  @timeout_sec = timeout_sec
  @max_bytes = max_bytes
end

Instance Method Details

#call(args) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/chocomint/tools/fetch_url.rb', line 52

def call(args)
  measure do
    url = args["url"].to_s
    uri = parse_http_uri(url)
    next fail(stderr: "url must be an http/https URL: #{url}") if uri.nil?

    body, err = fetch(uri)
    next fail(stderr: err) if body.nil?

    text = html_to_text(body)
    if text.empty?
      next fail(stderr: "no readable text extracted from #{url}")
    end

    summary = @chat_client.extract(args["query"], text[0, EXTRACT_TEXT_LIMIT], url: url)
    ok(stdout: summary)
  end
end

#descriptionObject



31
32
33
34
35
# File 'lib/chocomint/tools/fetch_url.rb', line 31

def description
  "指定した URL のウェブページを取得し、その内容から目的 (query) に沿った情報を" \
    "抽出して返す。最新情報の調査や外部ドキュメントの参照に使う。" \
    "url は http:// または https:// で始まること。"
end

#nameObject



29
# File 'lib/chocomint/tools/fetch_url.rb', line 29

def name = "fetch_url"

#schemaObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/chocomint/tools/fetch_url.rb', line 37

def schema
  {
    "type" => "object",
    "properties" => {
      "url" => { "type" => "string", "description" => "参照する http/https の URL" },
      "query" => {
        "type" => "string",
        "description" => "そのページから知りたいこと (任意。未指定ならページの要点をまとめる)"
      }
    },
    "required" => %w[url],
    "additionalProperties" => false
  }
end