summaryrefslogtreecommitdiff
path: root/src/ai.zig
blob: 98e82ac7360384ac61ef30f17ac9307bf2005ec1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
//! The AI's part: one question to a model and its answer as text, by way of libpantograph.
//! No AppKit, and nothing here knows what the question is about.
const std = @import("std");
const panto = @import("panto");
const Allocator = std.mem.Allocator;

/// The wire dialects libpantograph speaks. Any provider is one of these and a base URL.
pub const Style = enum { anthropic_messages, openai_chat, openai_responses, google_interactions };

pub const style_names = [_][]const u8{ "Anthropic Messages", "OpenAI Chat Completions", "OpenAI Responses", "Google Interactions" };
/// Where each dialect's own provider answers, as libpantograph's adapters expect the URL.
pub const style_urls = [_][]const u8{ "https://api.anthropic.com", "https://api.openai.com/v1", "https://api.openai.com/v1", "https://generativelanguage.googleapis.com/v1beta" };

pub const Settings = struct {
    style: Style = .anthropic_messages,
    base_url: []const u8 = "",
    model: []const u8 = "",
    api_key: []const u8 = "",

    pub fn ready(s: Settings) bool {
        return s.base_url.len > 0 and s.model.len > 0 and s.api_key.len > 0;
    }
};

const key_file = "inference";

/// The API key, from `<dir>/inference.json`: libpantograph's own token file, which only
/// its owner can read. Empty if there is none. `arena` owns it.
pub fn loadKey(arena: Allocator, io: std.Io, dir: []const u8) []const u8 {
    const parsed = (panto.loadTokenSet(arena, io, dir, key_file) catch return "") orelse return "";
    return parsed.value.access_token orelse "";
}

/// An empty key removes the file.
pub fn saveKey(gpa: Allocator, io: std.Io, dir: []const u8, key: []const u8) !void {
    if (key.len == 0) {
        _ = try panto.deleteTokenSet(gpa, io, dir, key_file);
    } else {
        try panto.saveTokenSet(gpa, io, dir, key_file, .{ .type = "api_key", .access_token = key });
    }
}

/// Both are the caller's to free.
pub const Answer = union(enum) { text: []u8, failed: []u8 };

/// Once, before the first `ask`.
pub fn init(gpa: Allocator, io: std.Io) void {
    panto.init(gpa, io);
}

/// Ask, and wait for the whole answer. Blocks on the network: not for the main thread.
pub fn ask(gpa: Allocator, io: std.Io, s: Settings, system: []const u8, question: []const u8) Answer {
    var why: ?[]u8 = null;
    if (turn(gpa, io, s, system, question, &why)) |text| {
        return .{ .text = text };
    } else |err| {
        return .{ .failed = why orelse gpa.dupe(u8, plain(err)) catch &.{} };
    }
}

/// What went wrong, for a provider that gave no words of its own.
fn plain(err: anyerror) []const u8 {
    return switch (err) {
        error.ProviderAuthFailed => "The provider turned the API key down.",
        error.ProviderModelNotFound => "The provider knows no model by that name.",
        error.ProviderRateLimited, error.ProviderOverloaded => "The provider is too busy just now.",
        error.ProviderTransport, error.ProviderUnavailable => "The provider could not be reached.",
        error.ProviderBadRequest => "The provider would not take the request. Is the API style right?",
        else => @errorName(err),
    };
}

fn turn(gpa: Allocator, io: std.Io, s: Settings, system: []const u8, question: []const u8, why: *?[]u8) ![]u8 {
    const max_tokens = 4096; // three paragraphs at the most, and room for a model that thinks first
    const config: panto.LLMConfig = .{
        .provider = switch (s.style) {
            // One question and no follow-up: a cache write would never be read back.
            .anthropic_messages => .{ .anthropic_messages = .{ .api_key = s.api_key, .base_url = s.base_url, .model = s.model, .max_tokens = max_tokens, .prompt_cache = false } },
            .openai_chat => .{ .openai_chat = .{ .api_key = s.api_key, .base_url = s.base_url, .model = s.model, .max_tokens = max_tokens } },
            .openai_responses => .{ .openai_responses = .{ .api_key = s.api_key, .base_url = s.base_url, .model = s.model, .max_tokens = max_tokens } },
            .google_interactions => .{ .google_interactions = .{ .api_key = s.api_key, .base_url = s.base_url, .model = s.model, .max_tokens = max_tokens } },
        },
        .api_timeout_ms = 60_000,
        .retry = .{ .max_attempts = 2 },
    };

    var null_store = panto.NullStore.init(gpa); // nothing of the exchange is kept
    var session = null_store.store().create();
    const agent = panto.Agent.init(gpa, io, &config, session, null) catch |err| {
        session.info.deinit(gpa);
        return err;
    };
    defer agent.deinit();
    try agent.setSystemPrompt(system);

    var block: panto.ContentBlock = .{ .Text = .{ .text = try panto.textualBlockFromSlice(gpa, question) } };
    const stream = agent.run(.{ .blocks = (&block)[0..1] }) catch |err| {
        block.deinit(gpa);
        return err;
    };
    defer stream.deinit();

    var out: std.ArrayList(u8) = .empty;
    errdefer out.deinit(gpa);
    while (stream.next() catch |err| {
        if (stream.lastError()) |said| why.* = gpa.dupe(u8, said) catch null;
        return err;
    }) |event| switch (event) {
        .message_complete => |done| for (done.message.content.items) |b| switch (b) {
            .Text => |t| try out.appendSlice(gpa, t.text.items),
            else => {},
        },
        else => {},
    };
    return out.toOwnedSlice(gpa);
}