| 1 |
|
defmodule Agent.Jsonl do |
| 2 |
|
import File, only: [exists?: 1, read!: 1] |
| 3 |
|
import String, only: [split: 2] |
| 4 |
|
import Enum, only: [drop: 2, with_index: 2, find_value: 3, count: 1] |
| 5 |
|
import Jason, only: [decode: 1] |
| 6 |
|
import Agent.Jsonl.Locate, only: [find: 1] |
| 7 |
|
|
| 8 |
|
def find(question, folder, pos) when is_binary(folder) do |
| 9 |
:-( |
source(folder) |> load(question, pos) |
| 10 |
|
end |
| 11 |
|
|
| 12 |
|
def find(question, nil, pos) do |
| 13 |
:-( |
source(nil) |> load(question, pos) |
| 14 |
|
end |
| 15 |
|
|
| 16 |
|
def find(question, pos) do |
| 17 |
:-( |
source(nil) |> load(question, pos) |
| 18 |
|
end |
| 19 |
|
|
| 20 |
|
defp source(folder) do |
| 21 |
:-( |
find(folder) |
| 22 |
|
end |
| 23 |
|
|
| 24 |
:-( |
defp load(nil, _, _), do: :wait |
| 25 |
|
|
| 26 |
:-( |
defp load(p, q, pos) do |
| 27 |
:-( |
ok(exists?(p), p, q, pos) |
| 28 |
|
catch |
| 29 |
:-( |
_, _ -> :wait |
| 30 |
|
end |
| 31 |
|
|
| 32 |
:-( |
defp ok(true, p, q, pos), do: p |> read!() |> split("\n") |> scan(q, pos) |
| 33 |
:-( |
defp ok(false, _, _, _), do: :wait |
| 34 |
|
|
| 35 |
|
defp scan(lines, q, pos) do |
| 36 |
:-( |
lines |> drop(pos) |> with_index(pos) |> rows(q) |
| 37 |
|
end |
| 38 |
|
|
| 39 |
|
defp rows(indexed, q) do |
| 40 |
:-( |
find_value(indexed, {:continue, count(indexed)}, &row(&1, q)) |
| 41 |
|
end |
| 42 |
|
|
| 43 |
:-( |
defp row({line, _}, _) when byte_size(line) < 10, do: nil |
| 44 |
|
|
| 45 |
|
defp row({line, _}, _) do |
| 46 |
:-( |
line |> decode() |> type() |
| 47 |
|
end |
| 48 |
|
|
| 49 |
|
defp type({:ok, %{"type" => "assistant", "message" => %{"content" => c}}}), |
| 50 |
:-( |
do: text(c) |
| 51 |
|
|
| 52 |
:-( |
defp type({:ok, %{"type" => "assistant", "content" => c}}), do: text(c) |
| 53 |
|
|
| 54 |
:-( |
defp type(_), do: nil |
| 55 |
|
|
| 56 |
|
defp text(c) when is_list(c) do |
| 57 |
:-( |
t = find_value(c, "", &pick/1) |
| 58 |
:-( |
empty(t) |
| 59 |
|
end |
| 60 |
|
|
| 61 |
:-( |
defp text(_), do: nil |
| 62 |
|
|
| 63 |
:-( |
defp empty(t) when byte_size(t) > 0, do: {:found, t} |
| 64 |
:-( |
defp empty(_), do: nil |
| 65 |
|
|
| 66 |
:-( |
defp pick(%{"text" => t}) when is_binary(t), do: t |
| 67 |
:-( |
defp pick(%{"type" => "text", "text" => t}), do: t |
| 68 |
:-( |
defp pick(_), do: nil |
| 69 |
|
end |