|
| 1 | +# llm_agent.omc — High-level LLM agent primitives for OMC |
| 2 | +# |
| 3 | +# Builds on: llm_call, llm_chat, llm_tools, batch_llm_call, eval_omc, |
| 4 | +# json_extract, str_format, substrate_embed |
| 5 | +# |
| 6 | +# Usage: |
| 7 | +# from "examples/lib/llm_agent.omc" import ask_json, react_agent, code_agent, ... |
| 8 | + |
| 9 | +# ── ask_json ───────────────────────────────────────────────────────────────── |
| 10 | +# Ask the LLM for JSON, extract and parse it from any surrounding prose. |
| 11 | + |
| 12 | +fn ask_json(prompt, example, model) { |
| 13 | + h sys = str_concat("Respond ONLY with valid JSON matching this structure: ", json_stringify(example)) |
| 14 | + h messages = [ |
| 15 | + {role: "system", content: sys}, |
| 16 | + {role: "user", content: prompt} |
| 17 | + ] |
| 18 | + h raw = llm_chat(messages, model) |
| 19 | + h parsed = json_extract(raw) |
| 20 | + if parsed == null { return example } |
| 21 | + return parsed |
| 22 | +} |
| 23 | + |
| 24 | +# ── chain_of_thought ────────────────────────────────────────────────────────── |
| 25 | + |
| 26 | +fn chain_of_thought(question, model) { |
| 27 | + h prompt = str_concat("Think through this step by step:\n\n", question, "\n\nReasoning:") |
| 28 | + return llm_call(prompt, model) |
| 29 | +} |
| 30 | + |
| 31 | +# ── self_critique + revise ──────────────────────────────────────────────────── |
| 32 | + |
| 33 | +fn self_critique(text, criteria, model) { |
| 34 | + h prompt = str_format( |
| 35 | + "Critique the following against: {criteria}\n\nText:\n{text}\n\nCritique:", |
| 36 | + {text: text, criteria: criteria} |
| 37 | + ) |
| 38 | + return llm_call(prompt, model) |
| 39 | +} |
| 40 | + |
| 41 | +fn critique_and_revise(text, criteria, model) { |
| 42 | + h critique = self_critique(text, criteria, model) |
| 43 | + h prompt = str_format( |
| 44 | + "Rewrite addressing this critique.\n\nOriginal:\n{text}\n\nCritique:\n{critique}\n\nRevised:", |
| 45 | + {text: text, critique: critique} |
| 46 | + ) |
| 47 | + return llm_call(prompt, model) |
| 48 | +} |
| 49 | + |
| 50 | +# ── parallel_research ───────────────────────────────────────────────────────── |
| 51 | + |
| 52 | +fn parallel_research(questions, model) { |
| 53 | + h prompts = par_map(questions, fn(q) { |
| 54 | + return str_concat("Research question: ", q, "\n\nAnswer concisely and factually.") |
| 55 | + }) |
| 56 | + return batch_llm_call(prompts, model) |
| 57 | +} |
| 58 | + |
| 59 | +fn research_and_synthesize(topic, sub_questions, model) { |
| 60 | + h answers = parallel_research(sub_questions, model) |
| 61 | + h parts = [] |
| 62 | + h i = 0 |
| 63 | + while i < arr_len(sub_questions) { |
| 64 | + arr_push(parts, str_format("Q: {q}\nA: {a}", {q: sub_questions[i], a: answers[i]})) |
| 65 | + i = i + 1 |
| 66 | + } |
| 67 | + h research = arr_join(parts, "\n\n") |
| 68 | + h prompt = str_format( |
| 69 | + "Topic: {topic}\n\nResearch:\n{research}\n\nWrite a comprehensive synthesis:", |
| 70 | + {topic: topic, research: research} |
| 71 | + ) |
| 72 | + return llm_call(prompt, model) |
| 73 | +} |
| 74 | + |
| 75 | +# ── react_agent ─────────────────────────────────────────────────────────────── |
| 76 | +# tools: array of {name, description, parameters, fn} |
| 77 | +# where fn(input_dict) -> string |
| 78 | + |
| 79 | +fn react_agent(goal, tools, model, max_turns) { |
| 80 | + h tool_defs = par_map(tools, fn(t) { |
| 81 | + return {name: t["name"], description: t["description"], parameters: t["parameters"]} |
| 82 | + }) |
| 83 | + h tool_map = dict_new() |
| 84 | + h i = 0 |
| 85 | + while i < arr_len(tools) { |
| 86 | + dict_set(tool_map, tools[i]["name"], tools[i]["fn"]) |
| 87 | + i = i + 1 |
| 88 | + } |
| 89 | + |
| 90 | + h messages = [{role: "user", content: goal}] |
| 91 | + h trace = [] |
| 92 | + h turn = 0 |
| 93 | + |
| 94 | + while turn < max_turns { |
| 95 | + h result = llm_tools(messages, tool_defs, model) |
| 96 | + |
| 97 | + if result["type"] == "text" { |
| 98 | + return {answer: result["content"], trace: trace, turns: turn} |
| 99 | + } |
| 100 | + |
| 101 | + h tool_name = result["name"] |
| 102 | + h tool_input = result["input"] |
| 103 | + arr_push(trace, str_format("[{n}] {i}", {n: tool_name, i: json_stringify(tool_input)})) |
| 104 | + |
| 105 | + h tool_fn = dict_get(tool_map, tool_name) |
| 106 | + h tool_result = "Error: unknown tool" |
| 107 | + if tool_fn != null { |
| 108 | + tool_result = tool_fn(tool_input) |
| 109 | + } |
| 110 | + |
| 111 | + arr_push(trace, str_format(" -> {r}", {r: str_slice(to_str(tool_result), 0, 100)})) |
| 112 | + arr_push(messages, {role: "assistant", content: str_format("Used: {n}", {n: tool_name})}) |
| 113 | + arr_push(messages, {role: "user", content: str_format("Tool result: {r}. Continue.", {r: to_str(tool_result)})}) |
| 114 | + turn = turn + 1 |
| 115 | + } |
| 116 | + |
| 117 | + return {answer: "Max turns reached", trace: trace, turns: turn} |
| 118 | +} |
| 119 | + |
| 120 | +# ── code_agent ──────────────────────────────────────────────────────────────── |
| 121 | +# Generate + test OMC code; repair until all tests pass. |
| 122 | +# tests: array of {check: "OMC code that throws on failure"} |
| 123 | + |
| 124 | +fn code_agent(task, tests, model, max_attempts) { |
| 125 | + h attempt = 0 |
| 126 | + h last_code = "" |
| 127 | + h last_error = "" |
| 128 | + |
| 129 | + while attempt < max_attempts { |
| 130 | + h prompt = if attempt == 0 { |
| 131 | + str_format( |
| 132 | + "Write an OMC function for:\n{task}\n\nOutput ONLY OMC code, no explanation.", |
| 133 | + {task: task} |
| 134 | + ) |
| 135 | + } else { |
| 136 | + str_format( |
| 137 | + "Fix this OMC code.\n\nCode:\n{code}\n\nError:\n{error}\n\nTask:\n{task}\n\nOutput ONLY fixed code.", |
| 138 | + {code: last_code, error: last_error, task: task} |
| 139 | + ) |
| 140 | + } |
| 141 | + |
| 142 | + h code = llm_call(prompt, model) |
| 143 | + last_code = code |
| 144 | + |
| 145 | + h all_pass = true |
| 146 | + h failures = [] |
| 147 | + h i = 0 |
| 148 | + while i < arr_len(tests) { |
| 149 | + h test = tests[i] |
| 150 | + h check_code = str_concat(code, "\n", test["check"]) |
| 151 | + h res = eval_omc(check_code) |
| 152 | + if res["error"] != null { |
| 153 | + all_pass = false |
| 154 | + arr_push(failures, str_format("Test {i}: {e}", {i: to_str(i), e: res["error"]})) |
| 155 | + } |
| 156 | + i = i + 1 |
| 157 | + } |
| 158 | + |
| 159 | + if all_pass { |
| 160 | + return {ok: true, code: code, attempts: attempt + 1} |
| 161 | + } |
| 162 | + last_error = arr_join(failures, "\n") |
| 163 | + attempt = attempt + 1 |
| 164 | + } |
| 165 | + return {ok: false, code: last_code, error: last_error, attempts: max_attempts} |
| 166 | +} |
| 167 | + |
| 168 | +# ── best_of_n ───────────────────────────────────────────────────────────────── |
| 169 | + |
| 170 | +fn best_of_n(task, n, model) { |
| 171 | + h blank = arr_fill(task, n) |
| 172 | + h prompts = par_map(blank, fn(t) { |
| 173 | + return str_concat("Solve this task concisely:\n", t) |
| 174 | + }) |
| 175 | + h solutions = batch_llm_call(prompts, model) |
| 176 | + |
| 177 | + h score_prompts = par_map(solutions, fn(sol) { |
| 178 | + return str_concat( |
| 179 | + "Rate this solution 0-10. Respond with JSON {\"score\": N, \"reason\": \"...\"}.\n\nSolution:\n", sol |
| 180 | + ) |
| 181 | + }) |
| 182 | + h scores_raw = batch_llm_call(score_prompts, model) |
| 183 | + h scores = par_map(scores_raw, fn(raw) { |
| 184 | + h j = json_extract(raw) |
| 185 | + if j != null { return j } |
| 186 | + return {score: 0, reason: raw} |
| 187 | + }) |
| 188 | + |
| 189 | + h best_idx = 0 |
| 190 | + h best_score = -1.0 |
| 191 | + h i = 0 |
| 192 | + while i < arr_len(scores) { |
| 193 | + h sv = to_float(to_str(scores[i]["score"])) |
| 194 | + if sv > best_score { |
| 195 | + best_score = sv |
| 196 | + best_idx = i |
| 197 | + } |
| 198 | + i = i + 1 |
| 199 | + } |
| 200 | + return {solution: solutions[best_idx], score: best_score, all_solutions: solutions} |
| 201 | +} |
| 202 | + |
| 203 | +# ── memory_agent ────────────────────────────────────────────────────────────── |
| 204 | +# Agent with short-term semantic memory via substrate_embed |
| 205 | + |
| 206 | +fn mem_agent_new() { |
| 207 | + return {memories: [], embeddings: []} |
| 208 | +} |
| 209 | + |
| 210 | +fn mem_store(agent, text) { |
| 211 | + arr_push(agent["memories"], text) |
| 212 | + arr_push(agent["embeddings"], substrate_embed(text, 16)) |
| 213 | + return agent |
| 214 | +} |
| 215 | + |
| 216 | +fn mem_recall(agent, query, top_k) { |
| 217 | + h qv = substrate_embed(query, 16) |
| 218 | + h n = arr_len(agent["memories"]) |
| 219 | + if n == 0 { return [] } |
| 220 | + |
| 221 | + h scored = [] |
| 222 | + h i = 0 |
| 223 | + while i < n { |
| 224 | + h ev = agent["embeddings"][i] |
| 225 | + h dot = 0.0 |
| 226 | + h j = 0 |
| 227 | + while j < arr_len(ev) { |
| 228 | + dot = dot + ev[j] * qv[j] |
| 229 | + j = j + 1 |
| 230 | + } |
| 231 | + arr_push(scored, {score: dot, text: agent["memories"][i]}) |
| 232 | + i = i + 1 |
| 233 | + } |
| 234 | + |
| 235 | + h sorted = arr_sort(scored, fn(a, b) { |
| 236 | + if a["score"] > b["score"] { return -1 } |
| 237 | + if a["score"] < b["score"] { return 1 } |
| 238 | + return 0 |
| 239 | + }) |
| 240 | + |
| 241 | + h result = [] |
| 242 | + h k = 0 |
| 243 | + while k < min(top_k, arr_len(sorted)) { |
| 244 | + arr_push(result, sorted[k]["text"]) |
| 245 | + k = k + 1 |
| 246 | + } |
| 247 | + return result |
| 248 | +} |
| 249 | + |
| 250 | +fn mem_agent_call(agent, question, model) { |
| 251 | + h context = mem_recall(agent, question, 3) |
| 252 | + h ctx_text = arr_join(context, "\n") |
| 253 | + h prompt = if str_len(ctx_text) > 0 { |
| 254 | + str_format("Context:\n{ctx}\n\nQuestion: {q}", {ctx: ctx_text, q: question}) |
| 255 | + } else { |
| 256 | + question |
| 257 | + } |
| 258 | + h answer = llm_call(prompt, model) |
| 259 | + mem_store(agent, str_concat("Q: ", question, "\nA: ", answer)) |
| 260 | + return answer |
| 261 | +} |
0 commit comments