Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

providers.zig

297 lines9.4 KB

1const std = @import("std");
2const agui = @import("agui.zig");
3​
4pub const MissingOpenAIKey = error.MissingOpenAIKey;
5pub const MissingAnthropicKey = error.MissingAnthropicKey;
6pub const UnsupportedProvider = error.UnsupportedProvider;
7pub const ProviderRequestFailed = error.ProviderRequestFailed;
8pub const UnsupportedCompressionMethod = error.UnsupportedCompressionMethod;
9​
10const EmitFn = *const fn (ctx: *anyopaque, delta: []const u8) anyerror!void;
11const HandleDataLineFn = *const fn (allocator: std.mem.Allocator, data: []const u8, ctx: *anyopaque, emit: EmitFn) anyerror!void;
12​
13const OpenAIChunk = struct {
14 choices: []struct {
15 delta: struct {
16 content: ?[]const u8 = null,
17 },
18 },
19};
20​
21const AnthropicChunk = struct {
22 type: []const u8,
23 delta: ?struct {
24 type: []const u8,
25 text: ?[]const u8 = null,
26 } = null,
27};
28​
29fn shiftLine(remaining: *std.ArrayList(u8), line_end: usize) void {
30 const remainder_start = line_end + 1;
31 const remainder_len = remaining.items.len - remainder_start;
32 if (remainder_len > 0) {
33 std.mem.copyForwards(u8, remaining.items[0..remainder_len], remaining.items[remainder_start..]);
34 }
35 remaining.items.len = remainder_len;
37​
38fn handleOpenAILine(allocator: std.mem.Allocator, data: []const u8, ctx: *anyopaque, emit: EmitFn) !void {
39 var parsed = std.json.parseFromSlice(OpenAIChunk, allocator, data, .{
40 .ignore_unknown_fields = true,
41 }) catch return;
42 defer parsed.deinit();
43 if (parsed.value.choices.len == 0) return;
44 if (parsed.value.choices[0].delta.content) |content| {
45 if (content.len > 0) try emit(ctx, content);
46 }
48​
49fn handleAnthropicLine(allocator: std.mem.Allocator, data: []const u8, ctx: *anyopaque, emit: EmitFn) !void {
50 var parsed = std.json.parseFromSlice(AnthropicChunk, allocator, data, .{
51 .ignore_unknown_fields = true,
52 }) catch return;
53 defer parsed.deinit();
54 if (!std.mem.eql(u8, parsed.value.type, "content_block_delta")) return;
55 const delta = parsed.value.delta orelse return;
56 if (!std.mem.eql(u8, delta.type, "text_delta")) return;
57 if (delta.text) |text| {
58 if (text.len > 0) try emit(ctx, text);
59 }
61​
62fn processSseLine(
63 allocator: std.mem.Allocator,
64 line: []const u8,
65 ctx: *anyopaque,
66 emit: EmitFn,
67 handleDataLine: HandleDataLineFn,
68) !bool {
69 if (!std.mem.startsWith(u8, line, "data: ")) return false;
70 const data = std.mem.trim(u8, line[6..], " \t");
71 if (std.mem.eql(u8, data, "[DONE]")) return true;
72 try handleDataLine(allocator, data, ctx, emit);
73 return false;
75​
76fn processSseBuffer(
77 allocator: std.mem.Allocator,
78 remaining: *std.ArrayList(u8),
79 ctx: *anyopaque,
80 emit: EmitFn,
81 handleDataLine: HandleDataLineFn,
82) !bool {
83 while (std.mem.indexOfScalar(u8, remaining.items, '\n')) |line_end| {
84 const line = std.mem.trimEnd(u8, remaining.items[0..line_end], "\r");
85 if (try processSseLine(allocator, line, ctx, emit, handleDataLine)) return true;
86 shiftLine(remaining, line_end);
87 }
88 return false;
90​
91fn streamProviderSse(
92 allocator: std.mem.Allocator,
93 io: std.Io,
94 url: []const u8,
95 headers: []const std.http.Header,
96 payload: []const u8,
97 handleDataLine: HandleDataLineFn,
98 ctx: *anyopaque,
99 emit: EmitFn,
100) !void {
101 var client: std.http.Client = .{
102 .allocator = allocator,
103 .io = io,
104 };
105 defer client.deinit();
106​
107 const uri = try std.Uri.parse(url);
108 var req = try std.http.Client.request(&client, .POST, uri, .{
109 .extra_headers = headers,
110 });
111 defer req.deinit();
112​
113 req.transfer_encoding = .{ .content_length = payload.len };
114 var body = try req.sendBodyUnflushed(&.{});
115 try body.writer.writeAll(payload);
116 try body.end();
117 try req.connection.?.flush();
118​
119 var response = try req.receiveHead(&.{});
120 if (response.head.status.class() != .success) {
121 var error_buffer: [4096]u8 = undefined;
122 var transfer_buffer: [4096]u8 = undefined;
123 const reader = response.reader(&transfer_buffer);
124 const error_len = reader.readSliceShort(&error_buffer) catch 0;
125 if (error_len > 0) {
126 std.log.err("[zig] provider request failed ({d}): {s}", .{
127 @intFromEnum(response.head.status),
128 error_buffer[0..error_len],
129 });
130 }
131 return error.ProviderRequestFailed;
132 }
133​
134 var transfer_buffer: [4096]u8 = undefined;
135 var decompress: std.http.Decompress = undefined;
136 const decompress_buffer: []u8 = switch (response.head.content_encoding) {
137 .identity => &.{},
138 .zstd => try allocator.alloc(u8, std.compress.zstd.default_window_len),
139 .deflate, .gzip => try allocator.alloc(u8, std.compress.flate.max_window_len),
140 .compress => return error.UnsupportedCompressionMethod,
141 };
142 defer if (decompress_buffer.len > 0) allocator.free(decompress_buffer);
143​
144 const reader = response.readerDecompressing(&transfer_buffer, &decompress, decompress_buffer);
145​
146 var carry: std.ArrayList(u8) = .empty;
147 defer carry.deinit(allocator);
148​
149 var read_buffer: [4096]u8 = undefined;
150 while (true) {
151 const n = reader.readSliceShort(&read_buffer) catch |err| switch (err) {
152 error.ReadFailed => return response.bodyErr().?,
153 };
154 if (n == 0) break;
155 try carry.appendSlice(allocator, read_buffer[0..n]);
156​
157 if (try processSseBuffer(allocator, &carry, ctx, emit, handleDataLine)) return;
158 }
159​
160 _ = try processSseBuffer(allocator, &carry, ctx, emit, handleDataLine);
162​
163fn encodeChatPayload(
164 allocator: std.mem.Allocator,
165 model: []const u8,
166 system: []const u8,
167 messages: []const agui.ChatMessage,
168 provider: []const u8,
169) ![]const u8 {
170 const OpenAIMessage = struct { role: []const u8, content: []const u8 };
171 var openai_messages: std.ArrayList(OpenAIMessage) = .empty;
172 defer openai_messages.deinit(allocator);
173​
174 if (system.len > 0) {
175 try openai_messages.append(allocator, .{ .role = "system", .content = system });
176 }
177 for (messages) |message| {
178 try openai_messages.append(allocator, .{
179 .role = message.role,
180 .content = message.content,
181 });
182 }
183​
184 if (std.mem.eql(u8, provider, "anthropic")) {
185 const Payload = struct {
186 model: []const u8,
187 max_tokens: u16 = 4096,
188 messages: []OpenAIMessage,
189 stream: bool = true,
190 system: ?[]const u8 = null,
191 };
192 return std.json.Stringify.valueAlloc(allocator, Payload{
193 .model = model,
194 .messages = openai_messages.items,
195 .system = if (system.len > 0) system else null,
196 }, .{});
197 }
198​
199 const Payload = struct {
200 model: []const u8,
201 messages: []OpenAIMessage,
202 stream: bool = true,
203 };
204 return std.json.Stringify.valueAlloc(allocator, Payload{
205 .model = model,
206 .messages = openai_messages.items,
207 }, .{});
209​
210fn requireEnv(comptime name: [:0]const u8, missing: anyerror) ![:0]const u8 {
211 const value = std.c.getenv(name) orelse return missing;
212 return std.mem.span(value);
214​
215pub fn streamOpenAI(
216 allocator: std.mem.Allocator,
217 io: std.Io,
218 model: []const u8,
219 system: []const u8,
220 messages: []const agui.ChatMessage,
221 ctx: *anyopaque,
222 emit: EmitFn,
223) !void {
224 const api_key = try requireEnv("OPENAI_API_KEY", error.MissingOpenAIKey);
225​
226 const payload = try encodeChatPayload(allocator, model, system, messages, "openai");
227 defer allocator.free(payload);
228​
229 const auth_header = try std.fmt.allocPrint(allocator, "Bearer {s}", .{api_key});
230 defer allocator.free(auth_header);
231​
232 const headers = [_]std.http.Header{
233 .{ .name = "authorization", .value = auth_header },
234 .{ .name = "content-type", .value = "application/json" },
235 };
236​
237 try streamProviderSse(
238 allocator,
239 io,
240 "https://api.openai.com/v1/chat/completions",
241 &headers,
242 payload,
243 handleOpenAILine,
244 ctx,
245 emit,
246 );
248​
249pub fn streamAnthropic(
250 allocator: std.mem.Allocator,
251 io: std.Io,
252 model: []const u8,
253 system: []const u8,
254 messages: []const agui.ChatMessage,
255 ctx: *anyopaque,
256 emit: EmitFn,
257) !void {
258 const api_key = try requireEnv("ANTHROPIC_API_KEY", error.MissingAnthropicKey);
259​
260 const payload = try encodeChatPayload(allocator, model, system, messages, "anthropic");
261 defer allocator.free(payload);
262​
263 const headers = [_]std.http.Header{
264 .{ .name = "x-api-key", .value = api_key },
265 .{ .name = "anthropic-version", .value = "2023-06-01" },
266 .{ .name = "content-type", .value = "application/json" },
267 };
268​
269 try streamProviderSse(
270 allocator,
271 io,
272 "https://api.anthropic.com/v1/messages",
273 &headers,
274 payload,
275 handleAnthropicLine,
276 ctx,
277 emit,
278 );
280​
281pub fn streamCompletion(
282 allocator: std.mem.Allocator,
283 io: std.Io,
284 config: agui.ProviderConfig,
285 system: []const u8,
286 messages: []const agui.ChatMessage,
287 ctx: *anyopaque,
288 emit: EmitFn,
289) !void {
290 if (std.mem.eql(u8, config.provider, "openai")) {
291 return streamOpenAI(allocator, io, config.model, system, messages, ctx, emit);
292 }
293 if (std.mem.eql(u8, config.provider, "anthropic")) {
294 return streamAnthropic(allocator, io, config.model, system, messages, ctx, emit);
295 }
296 return error.UnsupportedProvider;