Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 82 additions & 2 deletions agent/liii/pi/agent/loop.scm
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,84 @@
) ;let
) ;define

;; usage 是否携带有效 token 计数:错误占位消息(max-turns / 会话超时 / 请求异常)
;; usage 全零或仅含 cost 等非计数字段,不能用于上下文占比换算
(define (%usage-has-tokens? usage)
(and (pair? usage)
(let loop
((rest usage))
(and (pair? rest)
(or (and (pair? (car rest))
(memq (caar rest) '(input output totalTokens total cacheRead
cacheWrite))
(number? (cdar rest))
(> (cdar rest) 0)
) ;and
(loop (cdr rest))
) ;or
) ;and
) ;let
) ;and
) ;define

;; 最近一条携带有效 usage 的 assistant 消息的 usage(无则 #f):
;; 全零占位消息结算时回退沿用,避免页脚上下文占比闪回 0.0%
(define (%last-known-usage msgs)
(let loop
((rest (reverse msgs)))
(cond ((null? rest) #f)
((and (pi-assistant-message? (car rest))
(%usage-has-tokens? (pi-assistant-message-usage (car rest)))
) ;and
(pi-assistant-message-usage (car rest))
) ;
((and (pair? (car rest))
(%usage-has-tokens? (pi-agent-assoc-val 'usage "usage" (car rest) '()))
) ;and
(pi-agent-assoc-val 'usage "usage" (car rest) '())
) ;
(else (loop (cdr rest)))
) ;cond
) ;let
) ;define

;; 结算响应 usage 全零/缺失时回填最近已知 usage:
;; 请求并未消耗上下文,沿用已知值可避免 message_usage 把占比打回 0.0%。
;; 仅作用于内存结算与事件上报,不改动落盘消息
(define (%carry-last-usage resp msgs)
(let* ((u (if (pi-assistant-message? resp)
(pi-assistant-message-usage resp)
(and (pair? resp) (pi-agent-assoc-val 'usage "usage" resp #f))
) ;if
) ;u
(last (and (not (%usage-has-tokens? u)) (%last-known-usage msgs)))
) ;
(cond ((not last) resp)
((pi-assistant-message? resp)
(pi-assistant-message (pi-assistant-message-content resp)
:stop-reason (pi-assistant-message-stop-reason resp)
:error-message (pi-assistant-message-error-message resp)
:usage last
:timestamp (pi-assistant-message-timestamp resp)
:provider (pi-assistant-message-provider resp)
:model (pi-assistant-message-model resp)
:api (pi-assistant-message-api resp)
) ;pi-assistant-message
) ;
((pair? resp)
(append
(remove
(lambda (x) (and (pair? x) (or (eq? (car x) 'usage) (equal? (car x) "usage"))))
resp
) ;remove
(list (cons 'usage last))
) ;append
) ;
(else resp)
) ;cond
) ;let*
) ;define

(define* (pi-step-agent-turn config msgs system-prompt emit timeout request-fn)
(let* ((eff-cfg (%resolve-effective-cfg config))
(active-tools (pi-cfg-ref eff-cfg 'tools '()))
Expand All @@ -60,7 +138,8 @@
) ;
(when (procedure? emit)
(emit 'message_start resp)
(emit 'message_end resp)
;; 结算事件用回填后的副本;落盘历史(new-msgs)保留原始 usage
(emit 'message_end (%carry-last-usage resp msgs))
) ;when
(let* ((new-msgs (append msgs (list resp)))
(stop-reason (if (pi-assistant-message? resp)
Expand Down Expand Up @@ -129,7 +208,8 @@
(when (procedure? emit)
(emit 'turn_start)
(emit 'message_start resp)
(emit 'message_end resp)
;; 事件上报使用回填后的 resp;返回/落盘保留原始占位 usage
(emit 'message_end (%carry-last-usage resp msgs))
(emit 'turn_end resp #())
(pi-emit-agent-end emit final-msgs "error" config)
) ;when
Expand Down
136 changes: 136 additions & 0 deletions agent/tests/liii/pi/agent/loop/run-agent-loop-zero-usage-test.scm
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
;; run-agent-loop
;; 全零 usage 结算消息的上下文回退:模型返回或错误占位消息 usage 全零时,
;; 结算响应回填最近一条已知 usage,避免 message_usage 把页脚占比打回 0.0%。
;;
;; 语法
;; ----
;; (run-agent-loop config initial-messages system-prompt (emit #f) (timeout 600)
;; (max-turns 0) (session-timeout 0) (compaction #f)
;; (request-fn pi-request-provider-stream) (emit-initial? #t))
;;
;; 参数
;; ----
;; 同 run-agent-loop-test.scm;本文件聚焦 usage 回退行为。
;;
;; 返回值
;; ----
;; list?,执行完成后的完整消息历史列表。
;; 注意:回退仅作用于事件上报,落盘消息保留原始全零 usage。

(import (scheme base) (liii check) (liii pi ai message) (liii pi agent loop))

(check-set-mode! 'report-failed)

(define %known-usage '((input . 100) (output . 20) (totalTokens . 120)))

(define %zero-usage '((input . 0) (output . 0) (total . 0)))

;; 1. 第二轮响应 usage 全零:message_end 结算响应回填上一轮已知 usage
(let* ((round 0)
(end-usages '())
(emit
(lambda (ev-type . args)
(when (and (eq? ev-type 'message_end) (pair? args) (pi-assistant-message? (car args)))
(set! end-usages (cons (pi-assistant-message-usage (car args)) end-usages))
) ;when
) ;lambda
) ;emit
(mock-req
(lambda (provider cfg msgs sp tools on-stream to)
(set! round (+ round 1))
(pi-assistant-message (list (list (cons 'type "text") (cons 'text "ok")))
:stop-reason "stop"
:usage (if (= round 1) %known-usage %zero-usage)
) ;pi-assistant-message
) ;lambda
) ;mock-req
(cfg '((tools) (provider . "google") (model-id . "m") (models-store)))
;; 第一轮后以 follow-up 注入驱动第二轮(无工具调用也可续跑)
(follow-ups (list (list (pi-user-message "again"))))
(cfg2
(append cfg
(list
(cons 'get-follow-up-messages
(lambda ()
(if (pair? follow-ups)
(let ((m (car follow-ups)))
(set! follow-ups (cdr follow-ups))
(list m)
) ;let
'()
) ;if
) ;lambda
) ;cons
) ;list
) ;append
) ;cfg2
(res (run-agent-loop cfg2 (list (pi-user-message "hi")) "" emit 10 0 0 #f mock-req)
) ;res
) ;
(check round => 2)
;; 第二轮结算事件(最新一条)的 usage 应回填为已知值
(check (cdr (assoc 'input (car end-usages))) => 100)
;; 落盘历史保留原始全零 usage
(check
(cdr (assoc 'input (pi-assistant-message-usage (list-ref res 3))))
=>
0
) ;check
) ;let*

;; 2. 会话超时错误占位(usage 全零):结算沿用最近已知 usage
(let* ((end-usages '())
(emit
(lambda (ev-type . args)
(when (and (eq? ev-type 'message_end) (pair? args) (pi-assistant-message? (car args)))
(set! end-usages (cons (pi-assistant-message-usage (car args)) end-usages))
) ;when
) ;lambda
) ;emit
(mock-req
(lambda (provider cfg msgs sp tools on-stream to)
(pi-assistant-message (list (list (cons 'type "text") (cons 'text "ok")))
:stop-reason "stop"
:usage %known-usage
) ;pi-assistant-message
) ;lambda
) ;mock-req
(cfg '((tools) (provider . "google") (model-id . "m") (models-store)))
(history (list (pi-user-message "hi")
(pi-assistant-message '() :stop-reason "stop" :usage %known-usage)
) ;list
) ;history
;; session-timeout 为负数:立即以超时错误占位结算
(res (run-agent-loop cfg history "" emit 10 0 -1 #f mock-req #f))
) ;
(check (length end-usages) => 1)
(check (cdr (assoc 'input (car end-usages))) => 100)
;; 落盘的错误占位消息仍为全零 usage
(check
(cdr (assoc 'input (pi-assistant-message-usage (list-ref res 2))))
=>
0
) ;check
) ;let*

;; 3. 无任何已知 usage 时:全零结算保持原样(首条消息即全零不误填)
(let* ((end-usages '())
(emit
(lambda (ev-type . args)
(when (and (eq? ev-type 'message_end) (pair? args) (pi-assistant-message? (car args)))
(set! end-usages (cons (pi-assistant-message-usage (car args)) end-usages))
) ;when
) ;lambda
) ;emit
(mock-req (lambda (provider cfg msgs sp tools on-stream to)
(pi-assistant-message '() :stop-reason "stop" :usage %zero-usage)
) ;lambda
) ;mock-req
(cfg '((tools) (provider . "google") (model-id . "m") (models-store)))
(res (run-agent-loop cfg (list (pi-user-message "hi")) "" emit 10 0 0 #f mock-req)
) ;res
) ;
(check (cdr (assoc 'input (car end-usages))) => 0)
) ;let*

(check-report)
3 changes: 3 additions & 0 deletions ai/liii/pi/ai/api/openai-completions/msg.scm
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,9 @@
(pairs
(append thinking-pairs
(list (and stream? (cons "stream" #t))
;; 流式请求声明返回 usage:OpenAI/DashScope 兼容端点缺省
;; 不在流末 chunk 携带 usage,导致上下文占比/费用统计全零
(and stream? (cons "stream_options" '(("include_usage" . #t))))
(and (integer? max-tokens) (> max-tokens 0) (cons "max_tokens" max-tokens))
(and (pair? tool-decls)
(> (length tool-decls) 0)
Expand Down
33 changes: 32 additions & 1 deletion ai/liii/pi/ai/api/openai-completions/stream-parse.scm
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,31 @@
) ;let
) ;define

;; 映射后的 usage 是否携带有效 token 计数(四项之和 > 0)
(define (%usage-has-tokens? usage)
(and (pair? usage)
(>
(let loop
((rest usage) (sum 0))
(if (null? rest)
sum
(loop (cdr rest)
(+ sum
(if (and (memq (caar rest) '(input output cacheRead cacheWrite))
(number? (cdar rest))
) ;and
(cdar rest)
0
) ;if
) ;+
) ;loop
) ;if
) ;let
0
) ;>
) ;and
) ;define

(define (process-openai-chunk json-obj stream-state on-event)
(let* ((top-usage (if (json-object? json-obj) (json-ref json-obj "usage") #f))
(choices (if (json-object? json-obj) (json-ref json-obj "choices") #()))
Expand All @@ -319,8 +344,14 @@
) ;raw-stop
(delta (if (json-object? choice) (json-ref choice "delta") '()))
) ;
;; 仅非零 usage 才覆盖:部分网关逐 chunk 下发全零 usage 占位,
;; 若末 chunk 缺失 usage 会把已累积的真实用量清零(页脚闪回 0.0%)
(when (json-object? eff-usage)
(openai-stream-state-usage-set! stream-state (openai-map-usage eff-usage))
(let ((mapped (openai-map-usage eff-usage)))
(when (%usage-has-tokens? mapped)
(openai-stream-state-usage-set! stream-state mapped)
) ;when
) ;let
) ;when
(when (and (string? raw-stop) (not (string-null? raw-stop)))
(openai-stream-state-stop-reason-set! stream-state
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@
(check (cdr (assoc "stream" body)) => #t)
(check (cdr (assoc "max_tokens" body)) => 4096)
(check (cdr (assoc "tools" body)) => (list->vector tools))
;; 流式请求必须声明 stream_options.include_usage,否则兼容端点不回传 usage
(check
(cdr (assoc "include_usage" (cdr (assoc "stream_options" body))))
=>
#t
) ;check
) ;let*

;; 无 tools 和非流式
Expand All @@ -54,6 +60,7 @@
) ;
(check (cdr (assoc "model" body)) => "kimi-for-coding")
(check (assoc "stream" body) => #f)
(check (assoc "stream_options" body) => #f)
(check (assoc "tools" body) => #f)
) ;let*

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,24 @@
(check (openai-stream-state-stop-reason stream-state) => "length")
) ;let

;; 全零 usage 占位 chunk 不得覆盖已累积的真实用量:
;; 部分网关逐 chunk 下发全零 usage,若末 chunk 缺失 usage 会清零统计
(let* ((stream-state (make-openai-stream-state '() #f '() "stop" #f '()))
(real-chunk
(list (cons "usage" (list (cons "prompt_tokens" 100) (cons "completion_tokens" 20)))
) ;list
) ;real-chunk
(zero-chunk
(list (cons "choices" (vector))
(cons "usage" (list (cons "prompt_tokens" 0) (cons "completion_tokens" 0)))
) ;list
) ;zero-chunk
) ;
(process-openai-chunk real-chunk stream-state #f)
(check (cdr (assoc 'input (openai-stream-state-usage stream-state))) => 100)
(process-openai-chunk zero-chunk stream-state #f)
(check (cdr (assoc 'input (openai-stream-state-usage stream-state))) => 100)
(check (cdr (assoc 'output (openai-stream-state-usage stream-state))) => 20)
) ;let*

(check-report)
7 changes: 6 additions & 1 deletion app/liii/pi/app/interactive/app-events.scm
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,12 @@
(tokens (pi-app-tokens app))
(latest-rate (pi-calculate-cache-hit-rate usage))
(context-tokens (pi-calculate-context-tokens usage))
(context (make-pi-context-usage (pi-context-percent context-tokens window) window #t)
;; 全零 usage(错误占位/异常结算):不消耗上下文,
;; 沿用页脚当前占比描述,避免闪回 "0.0%"
(context (if (> context-tokens 0)
(make-pi-context-usage (pi-context-percent context-tokens window) window #t)
#f
) ;if
) ;context
) ;
(pi-session-token-stats-add-usage! tokens usage)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,29 @@
) ;check-false
) ;let*

;; 5. 全零 usage(错误占位/异常结算/网关缺失 usage):不消耗上下文,
;; 占比应沿用上一次已知值,而非闪回 "0.0%"
(let* ((app (make-pi-app :terminal (make-virtual-terminal :width 80 :height 24)))
(ch (pi-app-event-chan app))
(usage '((input . 250000) (output . 0) (cacheRead . 0) (cacheWrite . 0)))
(zero-usage '((input . 0)
(output . 0)
(cacheRead . 0)
(cacheWrite . 0)
(totalTokens . 0)
(cost . 0))
) ;zero-usage
) ;
(chan-send! ch (list 'message_usage usage 1000000))
(pi-app-poll-events! app)
(check-true (string-contains (pi-footer-stats (%pi-app-footer app)) "25.0%/1.0M (auto)")
) ;check-true
(chan-send! ch (list 'message_usage zero-usage 1000000))
(pi-app-poll-events! app)
(check-true (string-contains (pi-footer-stats (%pi-app-footer app)) "25.0%/1.0M (auto)")
) ;check-true
(check-false (string-contains (pi-footer-stats (%pi-app-footer app)) "0.0%/1.0M (auto)")
) ;check-false
) ;let*

(check-report)
Loading