AgentDB with Ruby
Use AgentDB as the database of your Ruby app. This page shows every call you need, with Net::HTTP and json from the standard library. No gems. With Faraday or HTTParty, the calls look the same.
You can copy each block into your own code. Together they form one program that our tests run.
This page is tested: its code runs locally and in CI against a fresh AgentDB on every change.
Server-side only. In Rails, read the key from ENV or encrypted credentials, and call AgentDB from a model service or a job. Never render the key into a view.
#Before you start
- Ruby 3.1 or newer.
- A workspace with the example schema:
contact,companyandworks_at. - Three environment variables on your server:
AGENTDB_URL,AGENTDB_API_KEYandAGENTDB_WORKSPACE. See Environment variables.
#Connect
Read the settings from the environment. The key never appears in the code.
BASE_URL = ENV.fetch("AGENTDB_URL", "https://app.agentdb.link").chomp("/")
API_KEY = ENV["AGENTDB_API_KEY"] # a server-side secret: never in browser code
WORKSPACE = ENV["AGENTDB_WORKSPACE"] # ws_...
abort "Set AGENTDB_API_KEY and AGENTDB_WORKSPACE" if API_KEY.to_s.empty? || WORKSPACE.to_s.empty?
API = "#{BASE_URL}/v1/workspaces/#{WORKSPACE}"Every call goes through one small helper. It sends the key in the Authorization: Bearer header, turns AgentDB errors into one error type, and retries when that is safe.
# An AgentDB error: HTTP status plus the error envelope {code, message, retryable, details}.
class AgentDBError < StandardError
attr_reader :status, :code, :retryable, :details
def initialize(status, error)
error ||= {}
@status = status
@code = error["code"] || "HTTP_ERROR"
@retryable = error["retryable"] == true
@details = error["details"] || {}
super("#{status} #{@code}: #{error["message"]}")
end
end
# One API call. Sends the key in the Authorization header. Retries 429 and 503 with Retry-After
# (or exponential backoff), and network errors when the call is safe to repeat (GET, or a write
# with an Idempotency-Key). Returns the "data" part of the answer, or the raw body.
def api(method, path, json: nil, body: nil, idempotency_key: nil, raw: false)
uri = URI(API + path)
headers = { "Authorization" => "Bearer #{API_KEY}" }
payload = nil
if json
headers["Content-Type"] = "application/json"
payload = JSON.generate(json)
end
if body
headers["Content-Type"] = "application/octet-stream"
payload = body
end
headers["Idempotency-Key"] = idempotency_key if idempotency_key
safe_to_repeat = method == "GET" || !idempotency_key.nil?
attempt = 0
loop do
begin
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 60) do |http|
http.send_request(method, uri.request_uri, payload, headers)
end
rescue IOError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError
raise unless safe_to_repeat && attempt < 4
sleep(0.5 * 2**attempt)
attempt += 1
next
end
status = res.code.to_i
if [429, 503].include?(status) && attempt < 4
retry_after = res["Retry-After"].to_i
sleep(retry_after.positive? ? retry_after : 0.5 * 2**attempt + rand / 4)
attempt += 1
next
end
if status >= 400
envelope = JSON.parse(res.body) rescue {}
raise AgentDBError.new(status, envelope["error"])
end
return raw ? res.body : JSON.parse(res.body)["data"]
end
endCheck the connection by reading the schema:
schema = api("GET", "/object-types")
puts "Objects: #{schema["objects"].map { |o| o["name"] }.join(", ")}"#Create a record
Send the object name and the field values. AgentDB checks each value against its field type. The answer holds the new record with its id and version 1.
ada = api("POST", "/records",
json: { object: "contact", data: { name: "Ada Lovelace", email: "ada-#{run}@example.com", score: 72 } },
idempotency_key: SecureRandom.uuid) # safe to retry: the same key never writes twice
puts "Created #{ada["id"]} version #{ada["version"]}"The Idempotency-Key header makes a retry safe. See Idempotency keys.
#Read a record
record = api("GET", "/records/#{ada["id"]}")
puts "#{record["data"]["name"]} #{record["data"]["email"]} version #{record["version"]}"#Update a record
An update names the version you read. If someone changed the record since then, AgentDB refuses with VERSION_CONFLICT (HTTP 409) and writes nothing. Read it again, apply your change, and try again:
# Read, change, write with the current version. On VERSION_CONFLICT: read again and retry.
def update_record(id, attempts: 3)
(1..attempts).each do |i|
current = api("GET", "/records/#{id}")
begin
return api("PATCH", "/records/#{id}", json: { version: current["version"], data: yield(current["data"]) })
rescue AgentDBError => e
raise unless e.code == "VERSION_CONFLICT" && i < attempts
end
end
end
updated = update_record(ada["id"]) { |data| { score: data["score"] + 10 } }
puts "Score #{updated["data"]["score"]} version #{updated["version"]}"This is what the conflict looks like:
begin
api("PATCH", "/records/#{ada["id"]}", json: { version: 1, data: { score: 0 } }) # stale version
rescue AgentDBError => e
raise unless e.code == "VERSION_CONFLICT"
puts "Conflict: the record is now at version #{e.details["current_version"]}"
end#Query with filters, sort and pages
A query takes an object, a where filter, a sort and a limit (at most 200). Every condition in all must match. Use the in operator for "one of several values". Operators: eq, neq, in, lt, lte, gt, gte, is_null, is_not_null.
When more records match, the answer holds a next_cursor. Send it as cursor with the same query to get the next page. A next_cursor of null means you have them all.
# Every record that matches, page by page (limit up to 200; follow next_cursor).
def query_all(object, where, sort, page_size: 2)
out = []
cursor = nil
loop do
body = { object: object, where: where, sort: sort, limit: page_size }
body[:cursor] = cursor if cursor
page = api("POST", "/query", json: body)
out.concat(page["records"])
cursor = page["next_cursor"] # nil on the last page
return out unless cursor
end
end
good = query_all("contact",
{ all: [{ field: "score", op: "gte", value: 70 }, { field: "email", op: "neq", value: "nobody@example.com" }] },
[{ field: "score", order: "desc" }])
good.each { |c| puts "#{c["data"]["score"]} #{c["data"]["name"]}" }See Querying for text search, totals and saved views.
#Link records
A relationship type such as works_at links a contact to a company. Create a link, then list the records on the other side:
company = api("POST", "/records", json: { object: "company", data: { name: "Example Ltd #{run}" } })
api("POST", "/links",
json: { relationship: "works_at", source_record_id: ada["id"], target_record_id: company["id"] },
idempotency_key: "link-#{ada["id"]}-#{company["id"]}")
related = api("GET", "/records/#{ada["id"]}/related?relationship=works_at")
puts "Ada works at #{related["records"].map { |r| r["data"]["name"] }.join(", ")}"Add direction=incoming to list from the other side, for example all contacts of a company.
#Files
A file upload has three steps: announce the file with its name, type and size; send the raw bytes; attach it to a record. AgentDB checks that the bytes match the type.
bytes = "Meeting notes for Ada (#{run})\n".b
# 1. Announce the file, 2. send the raw bytes, 3. attach it to a record.
file = api("POST", "/files", json: { filename: "notes.txt", content_type: "text/plain", size: bytes.bytesize })
api("PUT", "/files/#{file["id"]}/content", body: bytes)
api("POST", "/attachments", json: { file_id: file["id"], record_id: ada["id"] })
# Download with the key (server side) ...
back = api("GET", "/files/#{file["id"]}/content", raw: true)
# ... or make a signed link that expires, for an <img> or a download button in your page.
link = api("POST", "/files/#{file["id"]}/links", json: { expires_in_seconds: 600 })
puts "Signed link until #{link["expires_at"]}"To show a file in a browser, give the page the signed link, never your key. The link expires and can be revoked. See Files and imports.
#Errors
Every error has a stable code, a message, a retryable flag and details, plus an HTTP status. Act on the code.
begin
api("GET", "/records/rec_doesnotexist")
rescue AgentDBError => e # a network error raises IOError or SystemCallError instead
puts "#{e.status} #{e.code} #{e.message}" # 404 NOT_FOUND ...
puts "Safe to retry later" if e.retryable
endNetwork errors raise IOError or SystemCallError; the helper retries those only when the call is safe to repeat.
Common codes:
| Code | HTTP | What to do |
|---|---|---|
VALIDATION_ERROR, FIELD_TYPE_MISMATCH | 400 | Fix the request; details names the field. |
UNAUTHENTICATED | 401 | Check the key. |
FORBIDDEN | 403 | The key's role or a permission rule does not allow this. |
NOT_FOUND | 404 | Check the id and the workspace. |
VERSION_CONFLICT | 409 | Read again and retry the update. |
RATE_LIMITED | 429 | Wait for Retry-After, then retry. |
The error codes page lists them all.
#Rate limits and retries
AgentDB limits how many requests a key and a workspace may send. Over the limit, it answers 429 RATE_LIMITED with a Retry-After header in seconds.
The request helper above already handles this:
- On 429 or 503, it waits for
Retry-After, or backs off (0.5, 1, 2, 4 seconds), then tries again. - On a network error, it retries only reads and writes with an idempotency key.
- It gives up after a few attempts and reports the error.
To load many records, use one batch call instead of one call per record: POST /records/upsert takes up to 500 items. See records_upsert_batch.
#Idempotency keys
A timeout can leave you unsure whether a write happened. Send an Idempotency-Key header with each write you may retry. If the same key comes again with the same request, AgentDB returns the first result and writes nothing twice. Keys are kept for 7 days.
key = SecureRandom.uuid # one key per intention; reuse it only to retry the same request
request = { object: "contact", data: { name: "Mary Somerville", email: "mary-#{run}@example.com" } }
first = api("POST", "/records", json: request, idempotency_key: key)
retry_result = api("POST", "/records", json: request, idempotency_key: key) # e.g. after a timeout
puts first["id"] == retry_result["id"] ? "Same record, written once" : "Duplicate!"Use a new key for each new intention, such as each form submission. The same key with a different request fails with IDEMPOTENCY_KEY_REUSED.
#Run the full example
The complete program is examples/languages/ruby/crm.rb. Set the three environment variables and run:
ruby crm.rbIt prints one OK line per topic: OK connect, OK create, OK read, OK update, OK query, OK relationships, OK files, OK errors and OK idempotency.