-
Notifications
You must be signed in to change notification settings - Fork 8
/
llm_tracer.jl
300 lines (261 loc) · 13.4 KB
/
llm_tracer.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# Tracing infrastructure for logging and other callbacks
# - Define your own schema that is subtype of AbstractTracerSchema and wraps the underlying LLM provider schema
# - Customize initialize_tracer and finalize_tracer with your custom callback
# - Call your ai* function with the tracer schema as usual
# Simple passthrough, do nothing
function role4render(schema::AbstractTracerSchema, msg::SystemMessage)
role4render(schema.schema, msg)
end
function role4render(schema::AbstractTracerSchema, msg::UserMessage)
role4render(schema.schema, msg)
end
function role4render(schema::AbstractTracerSchema, msg::UserMessageWithImages)
role4render(schema.schema, msg)
end
function role4render(schema::AbstractTracerSchema, msg::AIMessage)
role4render(schema.schema, msg)
end
"""
render(tracer_schema::AbstractTracerSchema,
conv::AbstractVector{<:AbstractMessage}; kwargs...)
Passthrough. No changes.
"""
function render(tracer_schema::AbstractTracerSchema,
conv::AbstractVector{<:AbstractMessage}; kwargs...)
return conv
end
"""
initialize_tracer(
tracer_schema::AbstractTracerSchema; model = "", tracer_kwargs = NamedTuple(),
prompt::ALLOWED_PROMPT_TYPE = "", kwargs...)
Initializes `tracer`/callback (if necessary). Can provide any keyword arguments in `tracer_kwargs` (eg, `parent_id`, `thread_id`, `run_id`).
Is executed prior to the `ai*` calls.
By default it captures:
- `time_sent`: the time the request was sent
- `model`: the model to use
- `meta`: a dictionary of additional metadata that is not part of the tracer itself
- `template_name`: the template to use if any
- `template_version`: the template version to use if any
- expanded `api_kwargs`, ie, the keyword arguments to pass to the API call
In the default implementation, we just collect the necessary data to build the tracer object in `finalize_tracer`.
See also: `meta`, `unwrap`, `TracerSchema`, `SaverSchema`, `finalize_tracer`
"""
function initialize_tracer(
tracer_schema::AbstractTracerSchema; model = "", tracer_kwargs = NamedTuple(),
prompt::ALLOWED_PROMPT_TYPE = "", api_kwargs::NamedTuple = NamedTuple(),
kwargs...)
meta = Dict{Symbol, Any}(k => v for (k, v) in pairs(api_kwargs))
if haskey(kwargs, :_tracer_template)
tpl = get(kwargs, :_tracer_template, nothing)
meta[:template_name] = tpl.name
metadata = aitemplates(tpl.name)
if !isempty(metadata)
meta[:template_version] = metadata[1].version
end
end
return (; time_sent = now(), model, meta,
tracer_kwargs...)
end
function finalize_tracer(
tracer_schema::AbstractTracerSchema, tracer, msg_or_conv;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
# default is a passthrough
return msg_or_conv
end
"""
finalize_tracer(
tracer_schema::AbstractTracerSchema, tracer, msg_or_conv::Union{
AbstractMessage, AbstractVector{<:AbstractMessage}};
tracer_kwargs = NamedTuple(), model = "", kwargs...)
Finalizes the calltracer of whatever is nedeed after the `ai*` calls. Use `tracer_kwargs` to provide any information necessary (eg, `parent_id`, `thread_id`, `run_id`).
In the default implementation, we convert all non-tracer messages into `TracerMessage`.
See also: `meta`, `unwrap`, `SaverSchema`, `initialize_tracer`
"""
function finalize_tracer(
tracer_schema::AbstractTracerSchema, tracer, msg_or_conv::Union{
AbstractMessage, AbstractVector{<:AbstractMessage}};
tracer_kwargs = NamedTuple(), model = "", kwargs...)
# We already captured all kwargs, they are already in `tracer`, we can ignore them in this implementation
time_received = now()
# work with arrays for unified processing
is_vector = msg_or_conv isa AbstractVector
conv = msg_or_conv isa AbstractVector{<:AbstractMessage} ?
convert(Vector{AbstractMessage}, msg_or_conv) :
AbstractMessage[msg_or_conv]
# extract the relevant properties from the tracer
tracer_subset = [f => get(tracer, f, nothing)
for f in fieldnames(TracerMessage) if haskey(tracer, f)]
# all msg non-traced, set times
for i in eachindex(conv)
msg = conv[i]
# change into TracerMessage if not already, use the current kwargs
if !istracermessage(msg)
# we saved our data for `tracer`
conv[i] = TracerMessage(; object = msg, tracer_subset..., time_received)
end
end
return is_vector ? conv : first(conv)
end
## Specialized finalizer to save the response to the disk
"""
finalize_tracer(
tracer_schema::SaverSchema, tracer, msg_or_conv::Union{
AbstractMessage, AbstractVector{<:AbstractMessage}};
tracer_kwargs = NamedTuple(), model = "", kwargs...)
Finalizes the calltracer by saving the provided conversation `msg_or_conv` to the disk.
Path is `LOG_DIR/conversation__<first_msg_hash>__<time_received_str>.json`,
where `LOG_DIR` is set by user preferences or ENV variable (defaults to `log/` in current working directory).
It can be composed with `TracerSchema` to also attach necessary metadata (see below).
# Example
```julia
wrap_schema = PT.SaverSchema(PT.TracerSchema(PT.OpenAISchema()))
conv = aigenerate(wrap_schema,:BlankSystemUser; system="You're a French-speaking assistant!",
user="Say hi!"; model="gpt-4", api_kwargs=(;temperature=0.1), return_all=true)
# conv is a vector of messages that will be saved to a JSON together with metadata about the template and api_kwargs
```
See also: `meta`, `unwrap`, `TracerSchema`, `initialize_tracer`
"""
function finalize_tracer(
tracer_schema::SaverSchema, tracer, msg_or_conv::Union{
AbstractMessage, AbstractVector{<:AbstractMessage}};
tracer_kwargs = NamedTuple(), model = "", kwargs...)
# We already captured all kwargs, they are already in `tracer`, we can ignore them in this implementation
time_received = now()
# work with arrays for unified processing
is_vector = msg_or_conv isa AbstractVector
conv = msg_or_conv isa AbstractVector{<:AbstractMessage} ?
convert(Vector{AbstractMessage}, msg_or_conv) :
AbstractMessage[msg_or_conv]
# Log the conversation to disk, save by hash of the first convo message + timestamp
first_msg_hash = hash(first(conv).content)
time_received_str = Dates.format(
time_received, dateformat"YYYYmmdd_HHMMSS")
path = joinpath(
LOG_DIR,
"conversation__$(first_msg_hash)__$(time_received_str).json")
mkpath(dirname(path))
save_conversation(path, conv)
return is_vector ? conv : first(conv)
end
"""
aigenerate(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", return_all::Bool = false, kwargs...)
Wraps the normal `aigenerate` call in a tracing/callback system. Use `tracer_kwargs` to provide any information necessary to the tracer/callback system only (eg, `parent_id`, `thread_id`, `run_id`).
Logic:
- calls `initialize_tracer`
- calls `aigenerate` (with the `tracer_schema.schema`)
- calls `finalize_tracer`
# Example
```julia
wrap_schema = PT.TracerSchema(PT.OpenAISchema())
msg = aigenerate(wrap_schema, "Say hi!"; model = "gpt4t")
msg isa TracerMessage # true
msg.content # access content like if it was the message
PT.pprint(msg) # pretty-print the message
```
It works on a vector of messages and converts only the non-tracer ones, eg,
```julia
wrap_schema = PT.TracerSchema(PT.OpenAISchema())
conv = aigenerate(wrap_schema, "Say hi!"; model = "gpt4t", return_all = true)
all(PT.istracermessage, conv) #true
```
"""
function aigenerate(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", return_all::Bool = false, kwargs...)
tracer = initialize_tracer(tracer_schema; model, tracer_kwargs, prompt, kwargs...)
# Force to return all convo and then subset as necessary
merged_kwargs = isempty(model) ? kwargs : (; model, kwargs...) # to not override default model for each schema if not provided
msg_or_conv = aigenerate(
tracer_schema.schema, prompt; tracer_kwargs, return_all = true, merged_kwargs...)
output = finalize_tracer(
tracer_schema, tracer, msg_or_conv; model, tracer_kwargs, kwargs...)
return return_all ? output : last(output)
end
"""
aiembed(tracer_schema::AbstractTracerSchema,
doc_or_docs::Union{AbstractString, AbstractVector{<:AbstractString}}, postprocess::Function = identity;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
Wraps the normal `aiembed` call in a tracing/callback system. Use `tracer_kwargs` to provide any information necessary to the tracer/callback system only (eg, `parent_id`, `thread_id`, `run_id`).
Logic:
- calls `initialize_tracer`
- calls `aiembed` (with the `tracer_schema.schema`)
- calls `finalize_tracer`
"""
function aiembed(tracer_schema::AbstractTracerSchema,
doc_or_docs::Union{AbstractString, AbstractVector{<:AbstractString}}, postprocess::Function = identity;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
tracer = initialize_tracer(tracer_schema; model, tracer_kwargs..., kwargs...)
merged_kwargs = isempty(model) ? kwargs : (; model, kwargs...) # to not override default model for each schema if not provided
embed_or_conv = aiembed(
tracer_schema.schema, doc_or_docs, postprocess; merged_kwargs...)
return finalize_tracer(
tracer_schema, tracer, embed_or_conv; model, tracer_kwargs..., kwargs...)
end
"""
aiclassify(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
Wraps the normal `aiclassify` call in a tracing/callback system. Use `tracer_kwargs` to provide any information necessary to the tracer/callback system only (eg, `parent_id`, `thread_id`, `run_id`).
Logic:
- calls `initialize_tracer`
- calls `aiclassify` (with the `tracer_schema.schema`)
- calls `finalize_tracer`
"""
function aiclassify(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
tracer = initialize_tracer(tracer_schema; model, prompt, tracer_kwargs..., kwargs...)
merged_kwargs = isempty(model) ? kwargs : (; model, kwargs...) # to not override default model for each schema if not provided
classify_or_conv = aiclassify(tracer_schema.schema, prompt; merged_kwargs...)
return finalize_tracer(
tracer_schema, tracer, classify_or_conv; model, tracer_kwargs..., kwargs...)
end
"""
aiextract(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
Wraps the normal `aiextract` call in a tracing/callback system. Use `tracer_kwargs` to provide any information necessary to the tracer/callback system only (eg, `parent_id`, `thread_id`, `run_id`).
Logic:
- calls `initialize_tracer`
- calls `aiextract` (with the `tracer_schema.schema`)
- calls `finalize_tracer`
"""
function aiextract(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
tracer = initialize_tracer(tracer_schema; model, prompt, tracer_kwargs..., kwargs...)
merged_kwargs = isempty(model) ? kwargs : (; model, kwargs...) # to not override default model for each schema if not provided
extract_or_conv = aiextract(tracer_schema.schema, prompt; merged_kwargs...)
return finalize_tracer(
tracer_schema, tracer, extract_or_conv; model, tracer_kwargs..., kwargs...)
end
"""
aiscan(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
Wraps the normal `aiscan` call in a tracing/callback system. Use `tracer_kwargs` to provide any information necessary to the tracer/callback system only (eg, `parent_id`, `thread_id`, `run_id`).
Logic:
- calls `initialize_tracer`
- calls `aiscan` (with the `tracer_schema.schema`)
- calls `finalize_tracer`
"""
function aiscan(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
tracer = initialize_tracer(tracer_schema; model, prompt, tracer_kwargs..., kwargs...)
merged_kwargs = isempty(model) ? kwargs : (; model, kwargs...) # to not override default model for each schema if not provided
scan_or_conv = aiscan(tracer_schema.schema, prompt; merged_kwargs...)
return finalize_tracer(
tracer_schema, tracer, scan_or_conv; model, tracer_kwargs..., kwargs...)
end
"""
aiimage(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
Wraps the normal `aiimage` call in a tracing/callback system. Use `tracer_kwargs` to provide any information necessary to the tracer/callback system only (eg, `parent_id`, `thread_id`, `run_id`).
Logic:
- calls `initialize_tracer`
- calls `aiimage` (with the `tracer_schema.schema`)
- calls `finalize_tracer`
"""
function aiimage(tracer_schema::AbstractTracerSchema, prompt::ALLOWED_PROMPT_TYPE;
tracer_kwargs = NamedTuple(), model = "", kwargs...)
tracer = initialize_tracer(tracer_schema; model, prompt, tracer_kwargs..., kwargs...)
merged_kwargs = isempty(model) ? kwargs : (; model, kwargs...) # to not override default model for each schema if not provided
image_or_conv = aiimage(tracer_schema.schema, prompt; merged_kwargs...)
return finalize_tracer(
tracer_schema, tracer, image_or_conv; model, tracer_kwargs..., kwargs...)
end