Class: VSM::Drivers::Anthropic::AsyncDriver
- Inherits:
-
Object
- Object
- VSM::Drivers::Anthropic::AsyncDriver
- Defined in:
- lib/vsm/drivers/anthropic/async_driver.rb
Instance Method Summary collapse
-
#initialize(api_key:, model:, base_url: "https://api.anthropic.com/v1", version: "2023-06-01") ⇒ AsyncDriver
constructor
A new instance of AsyncDriver.
- #run!(conversation:, tools:, policy: {}, &emit) ⇒ Object
Constructor Details
#initialize(api_key:, model:, base_url: "https://api.anthropic.com/v1", version: "2023-06-01") ⇒ AsyncDriver
Returns a new instance of AsyncDriver.
11 12 13 |
# File 'lib/vsm/drivers/anthropic/async_driver.rb', line 11 def initialize(api_key:, model:, base_url: "https://api.anthropic.com/v1", version: "2023-06-01") @api_key, @model, @base, @version = api_key, model, base_url, version end |
Instance Method Details
#run!(conversation:, tools:, policy: {}, &emit) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
# File 'lib/vsm/drivers/anthropic/async_driver.rb', line 15 def run!(conversation:, tools:, policy: {}, &emit) # Always use Net::HTTP with SSE emitted_terminal = false headers = { "x-api-key" => @api_key, "anthropic-version" => @version, "content-type" => "application/json", "accept" => "text/event-stream" } = (conversation, policy[:system_prompt]) tool_list = normalize_anthropic_tools(tools) payload = { model: @model, system: policy[:system_prompt], messages: , max_tokens: 512, stream: true } if tool_list.any? payload[:tools] = tool_list payload[:tool_choice] = { type: "auto" } end body = JSON.dump(payload) url = URI.parse("#{@base}/messages") http = Net::HTTP.new(url.host, url.port) http.use_ssl = (url.scheme == "https") http.read_timeout = 120 req = Net::HTTP::Post.new(url.request_uri) headers.each { |k,v| req[k] = v } req.body = body res = http.request(req) do |response| ct = response["content-type"] if response.code.to_i != 200 err_body = +"" response.read_body { |chunk| err_body << chunk } preview = err_body.to_s.byteslice(0, 400) emit.call(:assistant_final, "Anthropic HTTP #{response.code}: #{preview}") emitted_terminal = true next end if ct && ct.include?("text/event-stream") buffer = +"" textbuf = +"" toolbuf = {} tool_calls = [] response.read_body do |chunk| buffer << chunk while (i = buffer.index("\n")) line = buffer.slice!(0..i) line.chomp! next unless line.start_with?("data:") data = line.sub("data:","").strip next if data.empty? || data == "[DONE]" obj = JSON.parse(data) rescue nil next unless obj ev = obj["type"].to_s if ENV["VSM_DEBUG_STREAM"] == "1" $stderr.puts "anthropic(nethttp) <= #{ev}: #{data.byteslice(0, 160)}" end case ev when "content_block_delta" idx = obj["index"]; delta = obj["delta"] || {} case delta["type"] when "text_delta" part = delta["text"].to_s textbuf << part emit.call(:assistant_delta, part) when "input_json_delta" toolbuf[idx] ||= { id: nil, name: nil, json: +"" } toolbuf[idx][:json] << (delta["partial_json"] || "") end when "content_block_start" # For anthropic, the key can be 'content' or 'content_block' c = obj["content"] || obj["content_block"] || {} if c["type"] == "tool_use" name = c["name"] || obj["name"] toolbuf[obj["index"]] = { id: c["id"], name: name, json: +"" } end when "content_block_stop" idx = obj["index"] if tb = toolbuf[idx] args = tb[:json].empty? ? {} : (JSON.parse(tb[:json]) rescue {"_raw"=>tb[:json]}) # Only enqueue if name is present if tb[:name].to_s.strip != "" && tb[:id] tool_calls << { id: tb[:id], name: tb[:name], arguments: args } end end when "message_stop" if tool_calls.any? emit.call(:tool_calls, tool_calls) else emit.call(:assistant_final, textbuf.dup) end emitted_terminal = true end end end unless emitted_terminal # If the stream closed without a terminal, emit final text emit.call(:assistant_final, textbuf) emitted_terminal = true end else # Non-streaming JSON data = "" response.read_body { |chunk| data << chunk } obj = JSON.parse(data) rescue {} parts = Array(obj.dig("content")) calls = [] text = +"" parts.each do |p| case p["type"] when "text" then text << p["text"].to_s when "tool_use" then calls << { id: p["id"] || SecureRandom.uuid, name: p["name"], arguments: p["input"] || {} } end end if calls.any? emit.call(:tool_calls, calls) else emit.call(:assistant_final, text) end emitted_terminal = true end end :done end |