/* Spike: one streaming Messages API request over pic's own HTTPS stack.
* Reads the key from ANTHROPIC_API_KEY; prints the status, the response's
* content type and request id, and the decoded message. Never prints the key.
* Usage: live_probe [URL] */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "anthropic.h"
#include "http.h"
#include "net.h"
#include "sse.h"
typedef struct {
pic_sse *sse;
size_t bytes;
} sink;
static int on_body(void *ctx, const char *bytes, size_t n) {
sink *s = ctx;
s->bytes += n;
return pic_sse_feed(s->sse, bytes, n);
}
int main(int argc, char **argv) {
const char *url = argc > 1 ? argv[1] : "https://api.anthropic.com/v1/messages";
const char *key = getenv("ANTHROPIC_API_KEY");
const char *body = "{\"model\":\"claude-haiku-5-5\",\"max_tokens\":64,\"stream\":true,"
"\"messages\":[{\"role\":\"user\",\"content\":\"Reply with the single word: pong\"}]}";
char err[300], auth[512];
const char *headers[3];
sqlite3 *db;
pic_net *net;
pic_anthropic dec;
pic_sse sse;
pic_http_resp resp;
sink s;
int rc;
if (!key || !*key || strlen(key) > 400) {
fprintf(stderr, "set ANTHROPIC_API_KEY\n");
return 2;
}
(void)snprintf(auth, sizeof auth, "x-api-key: %s", key);
headers[0] = auth;
headers[1] = "anthropic-version: 2026-10-21";
headers[2] = "Accept: text/event-stream";
net = pic_net_new(err, sizeof err);
if (!net) {
fprintf(stderr, "net: %s\n", err);
return 1;
}
if (sqlite3_open(":memory:", &db) != SQLITE_OK || pic_anthropic_init(&dec, db) != 0 ||
pic_sse_init(&sse, 1u << 20, 1u << 22, pic_anthropic_event, &dec) != 0) {
return 1;
}
s.sse = &sse;
s.bytes = 0;
pic_http_resp_init(&resp, on_body, &s);
rc = pic_http_post(net, url, headers, 3, body, strlen(body), &resp, 30, 120, err, sizeof err);
memset(auth, 0, sizeof auth);
printf("post: %s%s\n", rc == 0 ? "ok" : "failed: ", rc == 0 ? "" : err);
printf("tls failure: %s\n", pic_net_tls_failed(net) ? "yes" : "no");
printf("status: %d\ncontent-type: %s\nrequest-id: %s\nbody bytes: %zu\n", resp.status, resp.content_type,
resp.request_id, s.bytes);
if (resp.status == 200) {
int drc = pic_anthropic_finish(&dec);
printf("decode: %s%s\nstop: %s\nusage: %s\ncontent: %s\n", drc == 0 ? "ok" : "failed: ",
drc == 0 ? "" : dec.err, dec.msg.stop_reason ? dec.msg.stop_reason : "-",
dec.msg.usage ? dec.msg.usage : "-", dec.msg.content ? dec.msg.content : "-");
}
pic_sse_free(&sse);
pic_anthropic_free(&dec);
sqlite3_close(db);
pic_net_free(net);
return rc == 0 && resp.status == 200 ? 0 : 1;
}