// packages/ai_llm/examples/demo.vk // Verification suite for `ai_llm` (Gemini, Anthropic, OpenAI, Ollama wire adapters, // SSE delta streaming, and multi-turn deterministic agent tool loop). use [llm = ai_llm] assert-eq = fn [label str, got any, want any] [ if got != want [ println `[FAIL] {label}: got {mold got}, expected {mold want}` return (err `assertion failed: {label}`) ] println `[PASS] {label}` .ok ] assert-true = fn [label str, cond bool] [ if not cond [ println `[FAIL] {label}` return (err `assertion failed: {label}`) ] println `[PASS] {label}` .ok ] weather-tool-def = fn [] llm/ToolDef [ llm/tool-def 'get_weather' 'Fetch current weather for a city' { type = 'object' properties = { city = { type = 'string' } } required = ['city'] } ] main = fn [] any [ wtool = weather-tool-def // 1. Gemini wire request & response translation gem_req = llm/ChatRequest { provider = .gemini model = 'gemini-2.5-pro' system = 'You are concise.' messages = [(llm/user-msg 'Weather in Tokyo?')] tools = [wtool] temperature = 0.2 max_tokens = 512 } gem_wire = llm/build-provider-request/api-key/or gem_req 'gem-test-key' [e -> return e] _ = assert-true/or 'Gemini URL contains :generateContent' (str/contains? (map/get gem_wire 'url') 'gemini-2.5-pro:generateContent') [e -> return e] gem_body = map/get gem_wire 'body' _ = assert-true/or 'Gemini has systemInstruction' (map/has? gem_body 'systemInstruction') [e -> return e] gem_tools = map/get gem_body 'tools' _ = assert-eq/or 'Gemini functionDeclarations[0].name' (map/get (map/get gem_tools[0] 'functionDeclarations')[0] 'name') 'get_weather' [e -> return e] gem_resp_raw = json/encode { candidates = [{ finishReason = 'STOP' content = { role = 'model' parts = [ { text = 'Checking Tokyo weather...' } { functionCall = { name = 'get_weather', args = { city = 'Tokyo' } } } ] } }] usageMetadata = { promptTokenCount = 20 candidatesTokenCount = 12 totalTokenCount = 32 } } gem_parsed = llm/parse-provider-response/or .gemini gem_resp_raw [e -> return e] _ = assert-eq/or 'Gemini response text' gem_parsed.content 'Checking Tokyo weather...' [e -> return e] _ = assert-eq/or 'Gemini response tool_calls count' (len gem_parsed.tool_calls) 1 [e -> return e] _ = assert-eq/or 'Gemini response tool_call city' (map/get gem_parsed.tool_calls[0].arguments 'city') 'Tokyo' [e -> return e] _ = assert-eq/or 'Gemini usage total_tokens' (map/get gem_parsed.usage 'total_tokens') 32 [e -> return e] // 2. Anthropic wire request & response translation (`tool_use` + `tool_result`) ant_req = llm/ChatRequest { provider = .anthropic model = 'claude-sonnet-4-20250514' system = 'Use tools accurately.' messages = [ (llm/user-msg 'Weather in Paris?') (llm/assistant-tool-msg 'Calling tool' [(llm/ToolCall { id = 'toolu_01', name = 'get_weather', arguments = { city = 'Paris' } })]) (llm/tool-result-msg 'toolu_01' 'get_weather' '{"temp_c":18}') ] tools = [wtool] } ant_wire = llm/build-provider-request/api-key/or ant_req 'ant-key' [e -> return e] ant_body = map/get ant_wire 'body' ant_msgs = map/get ant_body 'messages' _ = assert-eq/or 'Anthropic message count' (len ant_msgs) 3 [e -> return e] _ = assert-eq/or 'Anthropic tool_result block type' (map/get (map/get ant_msgs[2] 'content')[0] 'type') 'tool_result' [e -> return e] _ = assert-eq/or 'Anthropic input_schema mapped' (map/get (map/get ant_body 'tools')[0] 'name') 'get_weather' [e -> return e] ant_resp = llm/parse-provider-response/or .anthropic { model = 'claude-sonnet-4-20250514' stop_reason = 'tool_use' content = [ { type = 'text', text = 'Fetching...' } { type = 'tool_use', id = 'toolu_99', name = 'get_weather', input = { city = 'Berlin' } } ] usage = { input_tokens = 40, output_tokens = 15 } } [e -> return e] _ = assert-eq/or 'Anthropic parsed tool_use id' ant_resp.tool_calls[0].id 'toolu_99' [e -> return e] _ = assert-eq/or 'Anthropic parsed finish_reason' ant_resp.finish_reason 'tool_calls' [e -> return e] // 3. OpenAI & Ollama wire request & response translation oai_req = llm/ChatRequest { provider = .openai model = 'gpt-4.1' system = 'System prompt' messages = [(llm/user-msg 'Ping')] tools = [wtool] } oai_wire = llm/build-provider-request/api-key/or oai_req 'sk-test' [e -> return e] oai_body = map/get oai_wire 'body' oai_msgs = map/get oai_body 'messages' _ = assert-eq/or 'OpenAI prepends system message' (map/get oai_msgs[0] 'role') 'system' [e -> return e] _ = assert-eq/or 'OpenAI Bearer header' (map/get (map/get oai_wire 'headers') 'Authorization') 'Bearer sk-test' [e -> return e] ollama_wire = llm/build-provider-request/or (llm/ChatRequest { provider = .ollama model = 'qwen2.5-coder:7b' messages = [(llm/user-msg 'Local ping')] }) [e -> return e] _ = assert-eq/or 'Ollama default endpoint' (map/get ollama_wire 'url') 'http://127.0.0.1:11434/v1/chat/completions' [e -> return e] oai_resp = llm/parse-provider-response/or .openai { model = 'gpt-4.1' choices = [{ finish_reason = 'tool_calls' message = { role = 'assistant' content = .null tool_calls = [{ id = 'call_abc' type = 'function' function = { name = 'get_weather', arguments = '{"city":"Madrid"}' } }] } }] usage = { prompt_tokens = 10, completion_tokens = 8, total_tokens = 18 } } [e -> return e] _ = assert-eq/or 'OpenAI null content normalized to empty str' oai_resp.content '' [e -> return e] _ = assert-eq/or 'OpenAI decoded JSON string arguments' (map/get oai_resp.tool_calls[0].arguments 'city') 'Madrid' [e -> return e] // 4. Streaming SSE parser (`parse-sse-events` + `assemble-sse-response`) sse_stream = str/join [ ': keepalive\n\n' 'data: {"choices":[{"delta":{"content":"Hello "},"finish_reason":null}]}\n\n' 'data: {"choices":[{"delta":{"content":"Veko!","tool_calls":[{"index":0,"id":"call_s1","function":{"name":"get_weather","arguments":"{\\"city\\":"}}]},"finish_reason":null}]}\n\n' 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\\"Oslo\\"}"}}]},"finish_reason":"tool_calls"}]}\n\n' 'data: [DONE]\n\n' ] '' deltas = llm/parse-sse-events .openai sse_stream _ = assert-eq/or 'SSE event count (ignoring comments)' (len deltas) 4 [e -> return e] _ = assert-true/or 'SSE final [DONE] flag' deltas[3].done [e -> return e] assembled = llm/assemble-sse-response .openai deltas _ = assert-eq/or 'SSE assembled text' assembled.content 'Hello Veko!' [e -> return e] _ = assert-eq/or 'SSE assembled streamed tool_call city' (map/get assembled.tool_calls[0].arguments 'city') 'Oslo' [e -> return e] // 5. Multi-turn deterministic `run-tool-loop` against a mock provider agent_tools = [ (llm/agent-tool wtool fn [args map] any [ city = str/append '' (map/get args 'city') { city = city, temp_c = 21, sky = 'clear' } ]) (llm/agent-tool (llm/tool-def 'convert_c_to_f' 'Convert Celsius to Fahrenheit' { type = 'object' properties = { c = { type = 'integer' } } required = ['c'] }) fn [args map] any [ c = as-i64 (map/get args 'c') { fahrenheit = ((c * 9 / 5) + 32) } ]) ] mock_sender = fn [creq llm/ChatRequest] any [ n = len creq.messages // Turn 1: user message -> request `get_weather` if n == 1 [ return (llm/ChatResponse { provider = creq.provider model = creq.model content = '' tool_calls = [(llm/ToolCall { id = 'c1', name = 'get_weather', arguments = { city = 'Lisbon' } })] finish_reason = 'tool_calls' }) ] // Turn 2: after `get_weather` result -> request `convert_c_to_f` if n == 3 [ t0_json = json/decode creq.messages[2].content c_val = as-i64 (map/get t0_json 'temp_c') return (llm/ChatResponse { provider = creq.provider model = creq.model content = '' tool_calls = [(llm/ToolCall { id = 'c2', name = 'convert_c_to_f', arguments = { c = c_val } })] finish_reason = 'tool_calls' }) ] // Turn 3: after `convert_c_to_f` -> emit final natural-language answer t1_json = json/decode creq.messages[4].content f_val = as-i64 (map/get t1_json 'fahrenheit') llm/ChatResponse { provider = creq.provider model = creq.model content = `Lisbon is 21C ({mold f_val}F) and clear.` tool_calls = [] finish_reason = 'stop' } ] init_loop_req = llm/ChatRequest { provider = .openai model = 'gpt-4.1-mini' messages = [(llm/user-msg 'What is the weather in Lisbon in C and F?')] } loop_res = llm/run-tool-loop/or init_loop_req agent_tools fn [r llm/ChatRequest] any [ mock_sender r ] [e -> return e] _ = assert-eq/or 'Agent loop turn count' loop_res.turns 3 [e -> return e] _ = assert-eq/or 'Agent loop executed 2 tool calls' (len loop_res.tool_log) 2 [e -> return e] _ = assert-eq/or 'Agent loop final answer' loop_res.response.content 'Lisbon is 21C (69F) and clear.' [e -> return e] _ = assert-eq/or 'Agent loop full conversation length' (len loop_res.messages) 6 [e -> return e] println 'ai_llm demo: all checks passed.' 0 ] main