Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

refactor: improve model stream processing with reasoning support and better state handling

Dane Schneider7941d6cd3d38
diff --git a/app/server/model/plan/tell_build_pending.go b/app/server/model/plan/tell_build_pending.go
index fbf4ef2f..a6d91697 100644
--- a/app/server/model/plan/tell_build_pending.go
+++ b/app/server/model/plan/tell_build_pending.go
@@ -43,7 +43,7 @@ func (state *activeTellStreamState) queuePendingBuilds() {
// spew.Dump(pendingBuildsByPath)
buildState := &activeBuildStreamState{
- tellState: state,
+ modelStreamId: active.ModelStreamId,
clients: clients,
auth: auth,
currentOrgId: currentOrgId,
diff --git a/app/server/model/plan/tell_state.go b/app/server/model/plan/tell_state.go
index 5c475c16..d0fab7f7 100644
--- a/app/server/model/plan/tell_state.go
+++ b/app/server/model/plan/tell_state.go
@@ -15,6 +15,7 @@ const NumTellStreamRetries = 4
type activeTellStreamState struct {
activePlan *types.ActivePlan
+ modelStreamId string
execTellPlanParams execTellPlanParams
clients map[string]model.ClientInfo
req *shared.TellPlanRequest
diff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.go
index 02a1705d..80cbc76e 100644
--- a/app/server/model/plan/tell_stream_finish.go
+++ b/app/server/model/plan/tell_stream_finish.go
@@ -130,14 +130,13 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
if len(autoLoadPaths) > 0 {
log.Println("Sending stream message to load context files")
- active.Stream(shared.StreamMessage{
- Type: shared.StreamMessageLoadContext,
- LoadContextFiles: autoLoadPaths,
- })
- active.FlushStreamBuffer()
-
- // Force a small delay to ensure message is processed
- time.Sleep(100 * time.Millisecond)
+ go func() {
+ active.Stream(shared.StreamMessage{
+ Type: shared.StreamMessageLoadContext,
+ LoadContextFiles: autoLoadPaths,
+ })
+ active.FlushStreamBuffer()
+ }()
log.Println("Waiting for client to auto load context (30s timeout)")
diff --git a/app/server/model/plan/tell_stream_main.go b/app/server/model/plan/tell_stream_main.go
index b5f50d7a..7b54834c 100644
--- a/app/server/model/plan/tell_stream_main.go
+++ b/app/server/model/plan/tell_stream_main.go
@@ -37,7 +37,6 @@ func (state *activeTellStreamState) listenStream(stream *model.ExtendedChatCompl
// Create a timer that will trigger if no chunk is received within the specified duration
timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)
defer timer.Stop()
-
streamFinished := false
mainLoop:
@@ -97,6 +96,8 @@ mainLoop:
return
}
+ // log.Println("tell stream main: received stream response", spew.Sdump(response))
+
if response.ID != "" && state.generationId == "" {
state.generationId = response.ID
}
diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.go
index 2280e98f..404d602a 100644
--- a/app/server/model/plan/tell_stream_processor.go
+++ b/app/server/model/plan/tell_stream_processor.go
@@ -13,7 +13,6 @@ import (
shared "plandex-shared"
"github.com/davecgh/go-spew/spew"
- "github.com/sashabaranov/go-openai"
)
const verboseLogging = false
@@ -24,7 +23,7 @@ type processChunkResult struct {
shouldReturn bool
}
-func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStreamChoice) processChunkResult {
+func (state *activeTellStreamState) processChunk(choice types.ExtendedChatCompletionStreamChoice) processChunkResult {
req := state.req
// missingFileResponse := state.missingFileResponse
processor := state.chunkProcessor
@@ -42,6 +41,10 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStr
delta := choice.Delta
content := delta.Content
+ if delta.Reasoning != "" {
+ content = delta.Reasoning
+ }
+
if content == "" {
return processChunkResult{}
}
@@ -462,7 +465,7 @@ func (state *activeTellStreamState) handleNewOperations(parserRes *types.ReplyPa
// log.Println(fileContents[i])
buildState := &activeBuildStreamState{
- tellState: state,
+ modelStreamId: state.modelStreamId,
clients: clients,
auth: auth,
currentOrgId: currentOrgId,
diff --git a/app/server/model/plan/tell_stream_status.go b/app/server/model/plan/tell_stream_status.go
index df952d5b..4e83ef98 100644
--- a/app/server/model/plan/tell_stream_status.go
+++ b/app/server/model/plan/tell_stream_status.go
@@ -113,6 +113,8 @@ func (state *activeTellStreamState) willContinuePlan(params willContinuePlanPara
allSubtasksFinished := params.allSubtasksFinished
activatePaths := params.activatePaths
+ log.Printf("[willContinuePlan] currentStage: %v", state.currentStage)
+
log.Printf("[willContinuePlan] Initial state - hasNewSubtasks: %v, allSubtasksFinished: %v, tellStage: %v, planningPhase: %v, iteration: %d, autoContinue: %v",
hasNewSubtasks, allSubtasksFinished, state.currentStage.TellStage, state.currentStage.PlanningPhase, state.iteration, state.req.AutoContinue)
@@ -153,6 +155,7 @@ func (state *activeTellStreamState) willContinuePlan(params willContinuePlanPara
// otherwise, continue to implementation phase
log.Printf("[willContinuePlan] Checking subtasks finished - allSubtasksFinished: %v, will continue: %v",
allSubtasksFinished, !allSubtasksFinished)
+
return !allSubtasksFinished
} else if state.currentStage.TellStage == shared.TellStageImplementation {
diff --git a/app/server/model/plan/tell_stream_store.go b/app/server/model/plan/tell_stream_store.go
index 3598101d..de533cd7 100644
--- a/app/server/model/plan/tell_stream_store.go
+++ b/app/server/model/plan/tell_stream_store.go
@@ -129,6 +129,9 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
log.Println("[storeOnFinished] No new current subtask set")
}
log.Printf("[storeOnFinished] All subtasks finished: %v", allSubtasksFinished)
+ } else if state.currentSubtask != nil && !subtaskFinished {
+ log.Printf("[storeOnFinished] Current subtask is not finished: %q", state.currentSubtask.Title)
+ state.currentSubtask.NumTries++
}
var flags shared.ConvoMessageFlags
@@ -144,7 +147,7 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
if len(removedSubtasks) > 0 {
flags.DidRemoveTasks = true
}
- if len(autoLoadContextResult.activatePaths) > 0 {
+ if len(autoLoadContextResult.autoLoadPaths) > 0 {
flags.DidLoadContext = true
}
if subtaskFinished && state.currentSubtask != nil {
@@ -204,19 +207,17 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
}
log.Println("[storeOnFinished] Description stored")
- // store subtasks if we've finished a subtask or added new ones
- if hasNewSubtasks || subtaskFinished {
- err = db.StorePlanSubtasks(currentOrgId, planId, state.subtasks)
- if err != nil {
- log.Printf("Error storing plan subtasks: %v\n", err)
- state.onError(onErrorParams{
- streamErr: fmt.Errorf("failed to store plan subtasks: %v", err),
- storeDesc: false,
- convoMessageId: assistantMsg.Id,
- commitMsg: convoCommitMsg,
- })
- return err
- }
+ // store subtasks
+ err = db.StorePlanSubtasks(currentOrgId, planId, state.subtasks)
+ if err != nil {
+ log.Printf("Error storing plan subtasks: %v\n", err)
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to store plan subtasks: %v", err),
+ storeDesc: false,
+ convoMessageId: assistantMsg.Id,
+ commitMsg: convoCommitMsg,
+ })
+ return err
}
log.Println("Comitting after store on finished")
diff --git a/app/server/model/plan/tell_stream_usage.go b/app/server/model/plan/tell_stream_usage.go
index 0ecdacd7..c18dd423 100644
--- a/app/server/model/plan/tell_stream_usage.go
+++ b/app/server/model/plan/tell_stream_usage.go
@@ -18,6 +18,11 @@ func (state *activeTellStreamState) handleUsageChunk(usage *openai.Usage) {
log.Println("Tell stream usage:")
log.Println(spew.Sdump(usage))
+ var cachedTokens int
+ if usage.PromptTokensDetails != nil {
+ cachedTokens = usage.PromptTokensDetails.CachedTokens
+ }
+
go func() {
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
Auth: auth,
@@ -25,6 +30,7 @@ func (state *activeTellStreamState) handleUsageChunk(usage *openai.Usage) {
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: usage.PromptTokens,
OutputTokens: usage.CompletionTokens,
+ CachedTokens: cachedTokens,
ModelName: state.settings.ModelPack.Planner.BaseModelConfig.ModelName,
ModelProvider: state.settings.ModelPack.Planner.BaseModelConfig.Provider,
ModelPackName: state.settings.ModelPack.Name,
@@ -32,7 +38,7 @@ func (state *activeTellStreamState) handleUsageChunk(usage *openai.Usage) {
Purpose: "Generated plan reply",
GenerationId: generationId,
PlanId: plan.Id,
- ModelStreamId: state.activePlan.ModelStreamId,
+ ModelStreamId: state.modelStreamId,
ConvoMessageId: state.replyId,
RequestStartedAt: state.requestStartedAt,
@@ -80,7 +86,7 @@ func (state *activeTellStreamState) execHookOnStop(sendStreamErr bool) {
Purpose: "Generated plan reply (stopped)",
GenerationId: generationId,
PlanId: plan.Id,
- ModelStreamId: state.activePlan.ModelStreamId,
+ ModelStreamId: state.modelStreamId,
ConvoMessageId: state.replyId,
StoppedEarly: true,
UserCancelled: !sendStreamErr,