Files
RoboMovel/simulacao/robo-movel-godot/addons/claude_godot/agent/providers/provider_anthropic.gd
T
mguinhosandClaude Opus 5.5 393019705c Projeto: app demo, servidor/firmware em software/, simulacao Godot, planta do bloco D, chapas MDF da base, renders e slides
- app/: app demo (Kivy/buildozer) da API do robo
- software/: servidor RoboMovel (SLAM, profundidade, navegacao) e firmware da base movel (movido de firmware/)
- simulacao/: projeto Godot do robo e script de lancamento servidor + simulacao
- modelos/: planta do 5o andar do bloco D, cena Blender do corredor e modelo real do robo
- partes/mdf/: chapas identificadas e nesting da base do robo (DXF/SVG/FCStd)
- projeto/render, relatorio/imagens, slides: renders finais e apresentacoes de progresso
- ferramentas/scripts: encaixe de chapas, planta do bloco D e render do corredor no Blender
- .gitignore: ignora backups do Blender/FreeCAD e .godot/

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 23:38:16 -03:00

369 lines
13 KiB
GDScript

## Native client for the Anthropic Messages API.
class_name ClaudeGodotProviderAnthropic
extends Node
## Text as it arrives, for the dock's live indicator.
signal stream_delta(text: String)
const API_URL := "https://api.anthropic.com/v1/messages"
const COUNT_URL := API_URL + "/count_tokens"
const API_VERSION := "2023-06-01"
var api_key: String = ""
var model: String = "claude-sonnet-5"
var env_var: String = "ANTHROPIC_API_KEY"
var _messages: Array = []
## Shown in error messages so the user can tell which provider failed.
var preset_label: String = "This provider"
var http_timeout := 0.0
var _cancel_requested := false
## Instance state, NOT locals captured by a lambda: GDScript lambdas capture
## locals by value, so a callback writing to a captured local never reaches
## the polling loop below — that bug hung every request indefinitely.
var streaming := true
var _stream: ClaudeGodotStreamClient
var _got_response := false
var _pending_response: Array = []
## Replaces the conversation with one restored from disk. The caller is
## responsible for it being this protocol's shape — see ClaudeGodotSessionStore.
func set_history(history: Array) -> void:
_messages = history.duplicate(true)
## The conversation exactly as it goes on the wire, for export.
## Replaces the text of the most recent tool_result blocks, for when one of
## them was big enough to break the request.
func shrink_last_tool_results(note: String) -> int:
var shrunk := 0
for i in range(_messages.size() - 1, -1, -1):
var message = _messages[i]
if not (message is Dictionary) or message.get("role", "") != "user":
continue
var content = message.get("content", null)
if not (content is Array):
continue
var touched := false
for block in content:
if block is Dictionary and block.get("type", "") == "tool_result":
shrunk += str(block.get("content", "")).length()
block["content"] = note
touched = true
if touched:
break
return shrunk
func get_history() -> Array:
return _messages.duplicate(true)
## A user message that is really the user talking, rather than the carrier
## for a batch of tool_result blocks. Compaction cuts the history at one of
## these, so the kept tail never begins with a result whose tool_use was
## summarized away.
func is_real_user_turn(message) -> bool:
if not (message is Dictionary) or message.get("role", "") != "user":
return false
var content = message.get("content", null)
if content is Array:
for block in content:
if block is Dictionary and block.get("type", "") == "tool_result":
return false
return true
func is_tool_result(message) -> bool:
if not (message is Dictionary) or message.get("role", "") != "user":
return false
var content = message.get("content", null)
if content is Array:
for block in content:
if block is Dictionary and block.get("type", "") == "tool_result":
return true
return false
func reset() -> void:
_messages.clear()
func add_user_message(text: String, images: Array = []) -> void:
if images.is_empty():
_messages.append({"role": "user", "content": text})
return
var blocks: Array = []
for img in images:
blocks.append({
"type": "image",
"source": {
"type": "base64",
"media_type": img["mime"],
"data": Marshalls.raw_to_base64(img["bytes"]),
},
})
if text != "":
blocks.append({"type": "text", "text": text})
_messages.append({"role": "user", "content": blocks})
func add_tool_results(results: Array) -> void:
var blocks: Array = []
for r in results:
blocks.append({
"type": "tool_result",
"tool_use_id": r["id"],
"content": str(r["content"]),
"is_error": r.get("is_error", false),
})
_messages.append({"role": "user", "content": blocks})
## Aborts the in-flight request, if any. step() will return {"error": ...}
## on its next poll rather than hang — see the wait loop below.
func cancel() -> void:
_cancel_requested = true
if _stream:
_stream.cancel()
func _get_api_key() -> String:
if api_key != "":
return api_key
return OS.get_environment(env_var)
## Anthropic names its cache fields differently and bills separately, so
## there is no cost in the response to read.
static func _read_usage(usage: Dictionary) -> Dictionary:
return {
"input": int(usage.get("input_tokens", 0)),
"output": int(usage.get("output_tokens", 0)),
"cost": 0.0,
"cached": int(usage.get("cache_read_input_tokens", 0)),
"reasoning": 0,
# What the next request starts from. input_tokens excludes the cache,
# and cached tokens are still part of the prompt, so the parts are
# summed here rather than read from input alone — otherwise a cache
# hit would look like a small context and compaction would never fire.
"context": int(usage.get("input_tokens", 0)) + int(usage.get("cache_read_input_tokens", 0)) + int(usage.get("cache_creation_input_tokens", 0)),
}
func _headers(key: String) -> Array:
return [
"content-type: application/json",
"x-api-key: %s" % key,
"anthropic-version: %s" % API_VERSION,
]
func _request_body(system_prompt: String, tools: Array) -> Dictionary:
var body := {
"model": model,
"max_tokens": 8192,
"system": system_prompt,
"messages": _messages,
}
if tools.size() > 0:
body["tools"] = tools
return body
## Runs one request/response step. Returns
## {"text": Array[String], "tool_calls": Array[{id,name,input}], "usage": {"input": int, "output": int}}
## or {"error": String}.
## Exact input tokens for the conversation plus a draft, from Anthropic's
## count_tokens endpoint — free, separately rate-limited, and it accepts the
## same system/messages/tools shape the real call takes. Returns -1 if it
## can't be reached, and the caller falls back to estimating.
func count_input_tokens(system_prompt: String, tools: Array, draft: String) -> int:
var key := _get_api_key()
if key == "":
return -1
var messages := _messages.duplicate(true)
if draft != "":
messages.append({"role": "user", "content": draft})
var body := {"model": model, "system": system_prompt, "messages": messages}
if tools.size() > 0:
body["tools"] = tools
var http := HTTPRequest.new()
http.timeout = 20.0
add_child(http)
if http.request(COUNT_URL, _headers(key), HTTPClient.METHOD_POST, JSON.stringify(body)) != OK:
http.queue_free()
return -1
var response: Array = await http.request_completed
http.queue_free()
if int(response[0]) != HTTPRequest.RESULT_SUCCESS or int(response[1]) != 200:
return -1
var json := JSON.new()
if json.parse((response[3] as PackedByteArray).get_string_from_utf8()) != OK:
return -1
var data = json.get_data()
return int(data.get("input_tokens", -1)) if data is Dictionary else -1
func step(system_prompt: String, tools: Array) -> Dictionary:
if streaming:
return await _step_streaming(system_prompt, tools)
return await _step_buffered(system_prompt, tools)
## Messages arrive as content blocks opened, filled by deltas and closed, so
## the blocks are rebuilt here into the array a non-streamed message carries
## and handed to the same parser.
func _step_streaming(system_prompt: String, tools: Array) -> Dictionary:
var key := _get_api_key()
if key == "":
return {"error": "No API key set for Anthropic. Paste one into the dock or set %s." % env_var}
_cancel_requested = false
if _stream == null:
_stream = ClaudeGodotStreamClient.new()
add_child(_stream)
var body := _request_body(system_prompt, tools)
body["stream"] = true
# index -> content block being assembled; tool_use inputs arrive as JSON
# fragments that only parse once the block is closed.
var blocks: Dictionary = {}
var partial_json: Dictionary = {}
var usage: Dictionary = {}
var on_event := func(event: Dictionary):
match event.get("type", ""):
"message_start":
var message: Dictionary = event.get("message", {})
var start_usage: Dictionary = message.get("usage", {})
usage["input_tokens"] = int(start_usage.get("input_tokens", 0))
"content_block_start":
var index := int(event.get("index", 0))
blocks[index] = (event.get("content_block", {}) as Dictionary).duplicate(true)
partial_json[index] = ""
"content_block_delta":
var index := int(event.get("index", 0))
var delta: Dictionary = event.get("delta", {})
match delta.get("type", ""):
"text_delta":
var chunk := str(delta.get("text", ""))
if blocks.has(index):
blocks[index]["text"] = str(blocks[index].get("text", "")) + chunk
stream_delta.emit(chunk)
"thinking_delta":
var chunk := str(delta.get("thinking", ""))
if blocks.has(index):
blocks[index]["thinking"] = str(blocks[index].get("thinking", "")) + chunk
stream_delta.emit(chunk)
"input_json_delta":
partial_json[index] = str(partial_json.get(index, "")) + str(delta.get("partial_json", ""))
"content_block_stop":
var index := int(event.get("index", 0))
var fragment := str(partial_json.get(index, ""))
if fragment != "" and blocks.has(index):
var json := JSON.new()
if json.parse(fragment) == OK and json.get_data() is Dictionary:
blocks[index]["input"] = json.get_data()
"message_delta":
var delta_usage: Dictionary = event.get("usage", {})
if delta_usage.has("output_tokens"):
usage["output_tokens"] = int(delta_usage["output_tokens"])
"error":
var failure: Dictionary = event.get("error", {})
usage["__error"] = str(failure.get("message", "The provider reported a failure mid-stream."))
var result := await _stream.stream(API_URL, _headers(key), JSON.stringify(body), on_event, http_timeout)
if result.has("error"):
return result
if usage.has("__error"):
return {"error": "%s: %s" % [preset_label, usage["__error"]]}
var status: int = result["status"]
if status != 200:
var json := JSON.new()
var data = json.get_data() if json.parse(result["body"]) == OK else null
return {"error": ClaudeGodotHttpError.api_error(preset_label, model, status, result["body"], data)}
var indices := blocks.keys()
indices.sort()
var content: Array = []
for index in indices:
content.append(blocks[index])
return _parse_content(content, usage)
func _step_buffered(system_prompt: String, tools: Array) -> Dictionary:
var key := _get_api_key()
if key == "":
return {"error": "No API key set for Anthropic. Paste one into the dock or set %s." % env_var}
_cancel_requested = false
var http := HTTPRequest.new()
http.timeout = http_timeout # 0 keeps Godot's default (no timeout); set request_timeout in preferences to bound it.
add_child(http)
var body := _request_body(system_prompt, tools)
var request_error := http.request(API_URL, _headers(key), HTTPClient.METHOD_POST, JSON.stringify(body))
if request_error != OK:
http.queue_free()
return {"error": "%s: could not start the request (Godot error %d)." % [preset_label, request_error]}
_got_response = false
_pending_response = []
http.request_completed.connect(_on_request_completed)
while not _got_response and not _cancel_requested:
await get_tree().process_frame
http.request_completed.disconnect(_on_request_completed)
var response := _pending_response
if _cancel_requested:
http.cancel_request()
http.queue_free()
return {"error": "Cancelled."}
http.queue_free()
var transport_failure := ClaudeGodotHttpError.transport_error(int(response[0]), API_URL, http_timeout)
if transport_failure != "":
return {"error": transport_failure}
var response_code: int = response[1]
var text := (response[3] as PackedByteArray).get_string_from_utf8()
var json := JSON.new()
if json.parse(text) != OK:
return {"error": ClaudeGodotHttpError.unparseable(preset_label, response_code, text)}
var data = json.get_data()
if response_code != 200:
return {"error": ClaudeGodotHttpError.api_error(preset_label, model, response_code, text, data)}
return _parse_content(data.get("content", []), data.get("usage", {}))
## Shared by both transports: the assistant's content blocks.
func _parse_content(content: Array, usage: Dictionary) -> Dictionary:
_messages.append({"role": "assistant", "content": content})
var texts: Array = []
var reasoning: Array = []
var tool_calls: Array = []
for block in content:
if block.get("type") == "text":
texts.append(block.get("text", ""))
elif block.get("type") == "thinking":
reasoning.append(block.get("thinking", ""))
elif block.get("type") == "tool_use":
tool_calls.append({
"id": block.get("id", ""),
"name": block.get("name", ""),
"input": block.get("input", {}),
})
return {
"text": texts,
"reasoning": reasoning,
"tool_calls": tool_calls,
"usage": _read_usage(usage),
}
## Connected to HTTPRequest.request_completed. Must be a real method writing
## instance state — a lambda writing captured locals would not be visible to
## step()'s polling loop (GDScript captures locals by value).
func _on_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) -> void:
_pending_response = [result, response_code, headers, body]
_got_response = true