33using Chats . BE . Services . Models . Dtos ;
44using Mscc . GenerativeAI ;
55using OpenAI . Chat ;
6+ using System . Diagnostics ;
67using System . Runtime . CompilerServices ;
78using System . Text . Json . Nodes ;
89using ChatMessage = OpenAI . Chat . ChatMessage ;
@@ -87,6 +88,8 @@ var x when x.IsLowOrMinimal() => 1024,
8788 SafetySettings = _safetySettings ,
8889 Tools = tool == null ? null : [ tool ] ,
8990 } ;
91+ Stopwatch codeExecutionSw = new ( ) ;
92+ string ? codeExecutionId = null ;
9093 await foreach ( GenerateContentResponse response in _generativeModel . GenerateContentStream ( gcr , new RequestOptions ( null , NetworkTimeout ) , cancellationToken ) )
9194 {
9295 if ( response . Candidates != null && response . Candidates . Count > 0 )
@@ -96,29 +99,27 @@ var x when x.IsLowOrMinimal() => 1024,
9699 {
97100 if ( part . ExecutableCode != null )
98101 {
99- items . Add ( ChatSegmentItem . FromText ( $ """
100- ```{ part . ExecutableCode . Language }
101- { part . ExecutableCode . Code }
102- ```
103-
104- """ ) ) ;
105- //items.Add(ChatSegmentItem.FromToolCall(0, new FunctionCall()
106- //{
107- // Name = "code_execution",
108- // Args = new JsonObject
109- // {
110- // ["code"] = part.ExecutableCode.Code,
111- // },
112- //}));
102+ codeExecutionId = "ce-" + DateTimeOffset . UtcNow . ToUnixTimeMilliseconds ( ) ;
103+ items . Add ( ChatSegmentItem . FromToolCall ( 0 , new FunctionCall ( )
104+ {
105+ Id = codeExecutionId ,
106+ Name = part . ExecutableCode . Language . ToString ( ) ,
107+ Args = new
108+ {
109+ code = part . ExecutableCode . Code ,
110+ } ,
111+ } ) ) ;
112+ codeExecutionSw = Stopwatch . StartNew ( ) ;
113113 }
114114 else if ( part . CodeExecutionResult != null )
115115 {
116- items . Add ( ChatSegmentItem . FromText ( $ """
117- ```
118- { part . CodeExecutionResult . Output }
119- ```
120-
121- """ ) ) ;
116+ if ( codeExecutionId == null )
117+ {
118+ throw new InvalidOperationException ( "CodeExecutionResult received without prior ExecutableCode." ) ;
119+ }
120+ items . Add ( ChatSegmentItem . FromToolCallResponse ( codeExecutionId , part . CodeExecutionResult . Output ,
121+ ( int ) codeExecutionSw . ElapsedMilliseconds ,
122+ isSuccess : part . CodeExecutionResult . Outcome == Outcome . OutcomeOk ) ) ;
122123 }
123124 else if ( part . Text != null )
124125 {
0 commit comments