2026-04-13 19:59:47 +02:00
|
|
|
package chatdebug
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"sync"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type (
|
2026-09-14 10:51:22 +02:00
|
|
|
runContextKey struct{}
|
|
|
|
|
reuseStepKey struct{}
|
|
|
|
|
reuseHolder struct {
|
2026-04-13 19:59:47 +02:00
|
|
|
mu sync.Mutex
|
|
|
|
|
handle *stepHandle
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// ContextWithRun stores rc in ctx.
|
|
|
|
|
func ContextWithRun(ctx context.Context, rc *RunContext) context.Context {
|
|
|
|
|
if rc == nil {
|
|
|
|
|
panic("chatdebug: nil RunContext")
|
|
|
|
|
}
|
2026-10-22 09:17:24 +02:00
|
|
|
return context.WithValue(ctx, runContextKey{}, rc)
|
2026-04-13 19:59:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RunFromContext returns the debug run context stored in ctx.
|
|
|
|
|
func RunFromContext(ctx context.Context) (*RunContext, bool) {
|
|
|
|
|
rc, ok := ctx.Value(runContextKey{}).(*RunContext)
|
|
|
|
|
if !ok {
|
|
|
|
|
return nil, false
|
|
|
|
|
}
|
|
|
|
|
return rc, true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ReuseStep marks ctx so wrapped model calls under it share one debug step.
|
|
|
|
|
func ReuseStep(ctx context.Context) context.Context {
|
|
|
|
|
if holder, ok := reuseHolderFromContext(ctx); ok {
|
|
|
|
|
return context.WithValue(ctx, reuseStepKey{}, holder)
|
|
|
|
|
}
|
|
|
|
|
return context.WithValue(ctx, reuseStepKey{}, &reuseHolder{})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func reuseHolderFromContext(ctx context.Context) (*reuseHolder, bool) {
|
|
|
|
|
holder, ok := ctx.Value(reuseStepKey{}).(*reuseHolder)
|
|
|
|
|
if !ok {
|
|
|
|
|
return nil, false
|
|
|
|
|
}
|
|
|
|
|
return holder, true
|
|
|
|
|
}
|