beetlebug▾
/

ztcl::agent post

Sends one HTTP/1.1 POST of a JSON body.

ztcl::agent post URL HEADERS BODY

Description

Sends one HTTP/1.1 POST of the JSON text BODY to URL, with the headers of the list HEADERS, and gives the dict status N body TEXT. run uses it. An odd list of headers is an error of ZTCL AGENT HEADER.

Arguments

ArgumentTypeDefaultDescription
URLURLrequiredAn http or https URL.
HEADERSlist of names and valuesrequiredThe headers of the request.
BODYJSON textrequiredThe body of the request.

Returns

A dict of status and body.

Examples

Each example of this page runs after package require ztcl::agent # A fake model on 127.0.0.1, on a port of the system, in a thread: each # request gets the next reply of ::replies, and ::requests keeps them. set srv [thread::create { proc serve {c a p} { fconfigure $c -translation binary set len 0 set hs {} while {[gets $c line] >= 0 && [set line [string trim $line]] ne ""} { lappend hs $line regexp -nocase {^content-length: *(\d+)} $line -> len } lappend ::requests [list $hs [read $c $len]] set body [lindex $::replies 0] set ::replies [lrange $::replies 1 end] puts -nonewline $c "HTTP/1.1 $::status OK\r\nContent-Length: [string length $body]\r\nConnection: close\r\n\r\n$body" close $c } set ::status 200 set ::replies {} set ::requests {} set ::port [lindex [fconfigure [socket -server serve -myaddr 127.0.0.1 0] -sockname] 2] thread::wait }] set url http://127.0.0.1:[thread::send $srv {set ::port}]/v1/messages # Sets the replies of the fake model, and gives the requests that it got. proc replies {args} { thread::send $::srv [list set ::replies $args] } proc requests {} { thread::send $::srv {set ::requests} } # A reply of the Messages API with one call of a tool. proc call {name input} { return "{\"content\":\[{\"type\":\"tool_use\",\"id\":\"t[incr ::id]\",\"name\":\"$name\",\"input\":$input}\],\"usage\":{\"input_tokens\":5,\"output_tokens\":3}}" } proc add {a b} { expr {$a + $b} } .

% replies {{"ok":true}}
> set r [ztcl::agent post $url {x-api-key k} {{"a":1}}]
> list $r [lindex [requests] end 1]
{status 200 body {{"ok":true}}} {{"a":1}}

Errors

% ztcl::agent post ftp://x {} {}
bad endpoint "ftp://x"
-errorcode ZTCL AGENT ENDPOINT

% ztcl::agent post $url {a "b\nc"} {}
a header has a line end
-errorcode ZTCL AGENT HEADER

% ztcl::agent post
wrong # args: should be "ztcl::agent post url headers body"
-errorcode TCL WRONGARGS

Facts

Capability
thread. A new interpreter does not have it until the host turns it on.
Tcl release
Tcl 9.1 and 8.6.
Since
ztcl 1.0.0-beta.1

See also