7814
Ta
tiny-c-agent / files
tiny-c-agent / src / provider.c
2.9 KB
1#include "provider.h" 2 3#include <stdlib.h> 4#include <string.h> 5 6#include <yyjson.h> 7 8#include "api.h" 9#include "util.h" 10 11void tiny_json_tool(yyjson_mut_doc *doc, yyjson_mut_val *obj, const tiny_tool *t, 12 const char *params_key) { 13 yyjson_mut_obj_add_strcpy(doc, obj, "name", t->name); 14 yyjson_mut_obj_add_strcpy(doc, obj, "description", t->description ? t->description : ""); 15 const char *params = t->parameters ? t->parameters : "{}"; 16 yyjson_doc *pdoc = yyjson_read(params, strlen(params), 0); 17 if (!pdoc) return; 18 yyjson_mut_val *copy = yyjson_val_mut_copy(doc, yyjson_doc_get_root(pdoc)); 19 yyjson_mut_obj_add_val(doc, obj, params_key, copy); 20 yyjson_doc_free(pdoc); 21} 22 23void tiny_emit_delta(tiny_stream_fn emit, void *user, tiny_stream_type type, const char *delta) { 24 if (!emit) return; 25 tiny_stream_event ev = {.type = type, .delta = delta}; 26 emit(&ev, user); 27} 28 29void tiny_emit_tool_start(tiny_stream_fn emit, void *user, const char *id, const char *name) { 30 if (!emit) return; 31 tiny_stream_event ev = { 32 .type = TINY_STREAM_TOOL_CALL_START, 33 .tool_call_id = id, 34 .tool_name = name, 35 }; 36 emit(&ev, user); 37} 38 39void tiny_add_text_block(tiny_message *out, tiny_block_type type, const char *text) { 40 if (!text || !text[0]) return; 41 tiny_block *b = tiny_message_add_block(out, type); 42 b->text = xstrdup(text); 43} 44 45void tiny_add_tool_block(tiny_message *out, const char *id, const char *name, 46 const char *args, tiny_stream_fn emit, void *user) { 47 tiny_block *b = tiny_message_add_block(out, TINY_BLOCK_TOOL_CALL); 48 b->tool_call_id = xstrdup(id ? id : ""); 49 b->tool_name = xstrdup(name ? name : ""); 50 b->arguments = xstrdup(args ? args : "{}"); 51 if (!emit) return; 52 tiny_stream_event ev = { 53 .type = TINY_STREAM_TOOL_CALL, 54 .tool_call_id = b->tool_call_id, 55 .tool_name = b->tool_name, 56 .tool_arguments = b->arguments, 57 }; 58 emit(&ev, user); 59} 60 61int tiny_provider_stream(const tiny_model *model, const tiny_context *ctx, 62 const tiny_stream_opts *opts, 63 tiny_stream_fn emit, void *user, 64 const volatile bool *cancel, 65 tiny_message *out, char **err) { 66 switch (model->api) { 67 case TINY_API_OPENAI_COMPLETIONS: 68 return tiny_openai_completions_stream(model, ctx, opts, emit, user, cancel, out, err); 69 case TINY_API_OPENAI_RESPONSES: 70 return tiny_openai_responses_stream(model, ctx, opts, emit, user, cancel, out, err); 71 case TINY_API_ANTHROPIC_MESSAGES: 72 return tiny_anthropic_messages_stream(model, ctx, opts, emit, user, cancel, out, err); 73 case TINY_API_GOOGLE_GENERATIVE_AI: 74 return tiny_google_generative_ai_stream(model, ctx, opts, emit, user, cancel, out, err); 75 } 76 *err = strdup("provider: unsupported api"); 77 return -1; 78}