Skip to content

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

refactor token counting, follow up prompting classification step, stream processor fix, stream processor logging, subtask handling updates, some other minor refactoring and cleanup

Dane Schneider738a35eea4c4
diff --git a/app/cli/cmd/convo.go b/app/cli/cmd/convo.go
index c4bb5220..da018728 100644
--- a/app/cli/cmd/convo.go
+++ b/app/cli/cmd/convo.go
@@ -15,6 +15,7 @@ import (
)
var plainTextOutput bool
+var convoRaw bool
// convoCmd represents the convo command
var convoCmd = &cobra.Command{
@@ -28,6 +29,10 @@ func init() {
RootCmd.AddCommand(convoCmd)
convoCmd.Flags().BoolVarP(&plainTextOutput, "plain", "p", false, "Output conversation in plain text with no ANSI codes")
+
+ // for debugging output
+ convoCmd.Flags().BoolVar(&convoRaw, "raw", false, "Output conversation in raw format")
+ convoCmd.Flags().MarkHidden("raw")
}
const stoppedEarlyMsg = "You stopped the reply early"
@@ -114,7 +119,10 @@ func convo(cmd *cobra.Command, args []string) {
header := fmt.Sprintf("#### %d | %s | %s | %d 🪙 ", i+1,
author, formattedTs, msg.Tokens)
- txt := convertCodeBlocks(msg.Message)
+ txt := msg.Message
+ if !convoRaw {
+ txt = convertCodeBlocks(msg.Message)
+ }
if plainTextOutput {
convo += header + "\n" + txt + "\n\n"
diff --git a/app/cli/lib/context_update.go b/app/cli/lib/context_update.go
index a94ddf88..3a7098ea 100644
--- a/app/cli/lib/context_update.go
+++ b/app/cli/lib/context_update.go
@@ -279,11 +279,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
body := string(fileContent)
- numTokens, err := shared.GetNumTokens(body)
- if err != nil {
- errs = append(errs, fmt.Errorf("failed to get the number of tokens in the file %s: %v", context.FilePath, err))
- return
- }
+ numTokens := shared.GetNumTokensEstimate(body)
tokenDiffsById[context.Id] = numTokens - context.NumTokens
numFiles++
@@ -345,11 +341,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
sha := hex.EncodeToString(hash[:])
if sha != context.Sha {
- numTokens, err := shared.GetNumTokens(body)
- if err != nil {
- errs = append(errs, fmt.Errorf("failed to get the number of tokens in the file %s: %v", context.FilePath, err))
- return
- }
+ numTokens := shared.GetNumTokensEstimate(body)
tokenDiffsById[context.Id] = numTokens - context.NumTokens
numTrees++
@@ -473,11 +465,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
updatedParts[path] = body
prevTokens := context.MapTokens[path]
- numTokens, err := shared.GetNumTokens(body)
- if err != nil {
- errs = append(errs, fmt.Errorf("failed to get the number of tokens in the file %s: %v", path, err))
- return
- }
+ numTokens := shared.GetNumTokensEstimate(body)
// fmt.Println("path", path, "numTokens", numTokens, "prevTokens", prevTokens)
@@ -520,11 +508,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
sha := hex.EncodeToString(hash[:])
if sha != context.Sha {
- numTokens, err := shared.GetNumTokens(body)
- if err != nil {
- errs = append(errs, fmt.Errorf("failed to get the number of tokens in the file %s: %v", context.FilePath, err))
- return
- }
+ numTokens := shared.GetNumTokensEstimate(body)
tokenDiffsById[context.Id] = numTokens - context.NumTokens
numUrls++
diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.go
index 18a7be4f..e46b64be 100644
--- a/app/cli/stream_tui/update.go
+++ b/app/cli/stream_tui/update.go
@@ -538,14 +538,7 @@ func (m *streamUIModel) checkMissingFile(msg *shared.StreamMessage) (tea.Model,
}
m.missingFileContent = string(bytes)
- numTokens, err := shared.GetNumTokens(m.missingFileContent)
-
- if err != nil {
- log.Println("failed to get num tokens:", err)
- m.err = fmt.Errorf("failed to get num tokens: %w", err)
- return m, nil
- }
-
+ numTokens := shared.GetNumTokensEstimate(m.missingFileContent)
m.missingFileTokens = numTokens
}
diff --git a/app/server/db/context_helpers.go b/app/server/db/context_helpers.go
index bdea1eaa..f533f0ee 100644
--- a/app/server/db/context_helpers.go
+++ b/app/server/db/context_helpers.go
@@ -126,8 +126,28 @@ func GetContext(orgId, planId, contextId string, includeBody, includeMapParts bo
}
func ContextRemove(orgId, planId string, contexts []*Context) error {
+ return contextRemove(contextRemoveParams{
+ orgId: orgId,
+ planId: planId,
+ contexts: contexts,
+ })
+}
+
+type contextRemoveParams struct {
+ orgId string
+ planId string
+ contexts []*Context
+ descriptions []*ConvoMessageDescription
+ currentPlan *shared.CurrentPlanState
+}
+
+func contextRemove(params contextRemoveParams) error {
+ orgId := params.orgId
+ planId := params.planId
+ contexts := params.contexts
+
// remove files
- numFiles := len(contexts) * 2
+ numFiles := 0
filesToUpdate := make(map[string]string)
@@ -136,6 +156,7 @@ func ContextRemove(orgId, planId string, contexts []*Context) error {
filesToUpdate[context.FilePath] = ""
contextDir := getPlanContextDir(orgId, planId)
for _, ext := range []string{".meta", ".body", ".map-parts"} {
+ numFiles++
go func(context *Context, dir, ext string) {
errCh <- os.Remove(filepath.Join(dir, context.Id+ext))
}(context, contextDir, ext)
@@ -149,7 +170,13 @@ func ContextRemove(orgId, planId string, contexts []*Context) error {
}
}
- err := invalidateConflictedResults(orgId, planId, filesToUpdate)
+ err := invalidateConflictedResults(invalidateConflictedResultsParams{
+ orgId: orgId,
+ planId: planId,
+ filesToUpdate: filesToUpdate,
+ descriptions: params.descriptions,
+ currentPlan: params.currentPlan,
+ })
if err != nil {
return fmt.Errorf("error invalidating conflicted results: %v", err)
}
@@ -157,6 +184,79 @@ func ContextRemove(orgId, planId string, contexts []*Context) error {
return nil
}
+type ClearContextParams struct {
+ OrgId string
+ PlanId string
+ SkipMaps bool
+ SkipPending bool
+}
+
+func ClearContext(params ClearContextParams) error {
+ orgId := params.OrgId
+ planId := params.PlanId
+ skipMaps := params.SkipMaps
+ skipPending := params.SkipPending
+
+ contexts, err := GetPlanContexts(orgId, planId, false, false)
+ if err != nil {
+ return fmt.Errorf("error getting plan contexts: %v", err)
+ }
+
+ var descriptions []*ConvoMessageDescription
+ var currentPlan *shared.CurrentPlanState
+
+ if skipPending {
+ var err error
+ descriptions, err = GetConvoMessageDescriptions(orgId, planId)
+ if err != nil {
+ return fmt.Errorf("error getting pending build descriptions: %v", err)
+ }
+
+ currentPlan, err = GetCurrentPlanState(CurrentPlanStateParams{
+ OrgId: orgId,
+ PlanId: planId,
+ ConvoMessageDescriptions: descriptions,
+ })
+
+ if err != nil {
+ return fmt.Errorf("error getting current plan state: %v", err)
+ }
+ }
+
+ toRemove := []*Context{}
+
+ for _, context := range contexts {
+ shouldSkip := false
+
+ if !(skipMaps && context.ContextType == shared.ContextMapType) {
+ shouldSkip = true
+ }
+
+ if skipPending && currentPlan.CurrentPlanFiles.Files[context.FilePath] != "" {
+ shouldSkip = true
+ }
+
+ if !shouldSkip {
+ toRemove = append(toRemove, context)
+ }
+ }
+
+ if len(toRemove) > 0 {
+ err := contextRemove(contextRemoveParams{
+ orgId: orgId,
+ planId: planId,
+ contexts: toRemove,
+ descriptions: descriptions,
+ currentPlan: currentPlan,
+ })
+ if err != nil {
+ return fmt.Errorf("error removing non-map contexts: %v", err)
+ }
+ }
+
+ return nil
+}
+
func StoreContext(context *Context, skipMapCache bool) error {
// log.Println("Storing context", context.Id)
// log.Println("Num tokens", context.NumTokens)
@@ -335,7 +435,11 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
}
if !params.SkipConflictInvalidation {
- err := invalidateConflictedResults(orgId, planId, filesToLoad)
+ err := invalidateConflictedResults(invalidateConflictedResultsParams{
+ orgId: orgId,
+ planId: planId,
+ filesToUpdate: filesToLoad,
+ })
if err != nil {
return nil, nil, fmt.Errorf("error invalidating conflicted results: %v", err)
}
@@ -418,19 +522,12 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
hash := sha256.Sum256([]byte(input))
mapShas[path] = hex.EncodeToString(hash[:])
mapBody := mappedFiles[path]
- mapTokens[path], err = shared.GetNumTokens(mapBody)
- if err != nil {
- return nil, nil, fmt.Errorf("error getting num tokens for %s: %v", path, err)
- }
+ mapTokens[path] = shared.GetNumTokensEstimate(mapBody)
}
}
combinedBody := mappedFiles.CombinedMap()
-
- numTokens, err = shared.GetNumTokens(combinedBody)
- if err != nil {
- return nil, nil, fmt.Errorf("error getting num tokens: %v", err)
- }
+ numTokens = shared.GetNumTokensEstimate(combinedBody)
newContext := Context{
// Id generated by db layer
@@ -453,12 +550,11 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
} else if context.ContextType == shared.ContextImageType {
numTokens, err = shared.GetImageTokens(context.Body, context.ImageDetail)
+ if err != nil {
+ return nil, nil, fmt.Errorf("error getting image num tokens: %v", err)
+ }
} else {
- numTokens, err = shared.GetNumTokens(context.Body)
- }
-
- if err != nil {
- return nil, nil, fmt.Errorf("error getting num tokens: %v", err)
+ numTokens = shared.GetNumTokensEstimate(context.Body)
}
paramsByTempId[tempId] = context
@@ -667,19 +763,17 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
if context.ContextType == shared.ContextImageType {
updateNumTokens, err = shared.GetImageTokens(params.Body, context.ImageDetail)
+ if err != nil {
+ errCh <- fmt.Errorf("error getting num tokens: %v", err)
+ return
+ }
} else {
- updateNumTokens, err = shared.GetNumTokens(params.Body)
-
+ updateNumTokens = shared.GetNumTokensEstimate(params.Body)
// log.Println("len(params.Body)", len(params.Body))
}
// log.Println("Updating context", id, "updateNumTokens", updateNumTokens)
- if err != nil {
- errCh <- fmt.Errorf("error getting num tokens: %v", err)
- return
- }
-
tokenDiff := updateNumTokens - context.NumTokens
tokenDiffsById[id] = tokenDiff
tokensDiff += tokenDiff
@@ -738,7 +832,11 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
}
if !params.SkipConflictInvalidation {
- err = invalidateConflictedResults(orgId, planId, filesToLoad)
+ err = invalidateConflictedResults(invalidateConflictedResultsParams{
+ orgId: orgId,
+ planId: planId,
+ filesToUpdate: filesToLoad,
+ })
if err != nil {
return nil, fmt.Errorf("error invalidating conflicted results: %v", err)
}
@@ -769,11 +867,7 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
context.MapParts[path] = part
context.MapShas[path] = params.InputShas[path]
- numTokens, err := shared.GetNumTokens(part)
- if err != nil {
- errCh <- fmt.Errorf("error getting num tokens for %s: %v", path, err)
- return
- }
+ numTokens := shared.GetNumTokensEstimate(part)
context.MapTokens[path] = numTokens
}
@@ -784,11 +878,7 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
}
context.Body = context.MapParts.CombinedMap()
- newNumTokens, err := shared.GetNumTokens(context.Body)
- if err != nil {
- errCh <- fmt.Errorf("error getting num tokens for %s: %v", context.Id, err)
- return
- }
+ newNumTokens := shared.GetNumTokensEstimate(context.Body)
// log.Println("Updated map context", id, "newNumTokens", newNumTokens)
@@ -854,20 +944,45 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
}, nil
}
-func invalidateConflictedResults(orgId, planId string, filesToUpdate map[string]string) error {
- descriptions, err := GetConvoMessageDescriptions(orgId, planId)
- if err != nil {
- return fmt.Errorf("error getting pending build descriptions: %v", err)
+type invalidateConflictedResultsParams struct {
+ orgId string
+ planId string
+ filesToUpdate map[string]string
+ descriptions []*ConvoMessageDescription
+ currentPlan *shared.CurrentPlanState
+}
+
+func invalidateConflictedResults(params invalidateConflictedResultsParams) error {
+ orgId := params.orgId
+ planId := params.planId
+ filesToUpdate := params.filesToUpdate
+
+ var descriptions []*ConvoMessageDescription
+
+ if params.descriptions == nil {
+ var err error
+ descriptions, err = GetConvoMessageDescriptions(orgId, planId)
+ if err != nil {
+ return fmt.Errorf("error getting pending build descriptions: %v", err)
+ }
+ } else {
+ descriptions = params.descriptions
}
- currentPlan, err := GetCurrentPlanState(CurrentPlanStateParams{
- OrgId: orgId,
- PlanId: planId,
- ConvoMessageDescriptions: descriptions,
- })
+ var currentPlan *shared.CurrentPlanState
- if err != nil {
- return fmt.Errorf("error getting current plan state: %v", err)
+ if params.currentPlan == nil {
+ var err error
+ currentPlan, err = GetCurrentPlanState(CurrentPlanStateParams{
+ OrgId: orgId,
+ PlanId: planId,
+ ConvoMessageDescriptions: descriptions,
+ })
+ if err != nil {
+ return fmt.Errorf("error getting current plan state: %v", err)
+ }
+ } else {
+ currentPlan = params.currentPlan
}
conflictPaths := currentPlan.PlanResult.FileResultsByPath.ConflictedPaths(filesToUpdate)
diff --git a/app/server/model/name.go b/app/server/model/name.go
index 2c3c2bf3..e6c18be9 100644
--- a/app/server/model/name.go
+++ b/app/server/model/name.go
@@ -25,14 +25,6 @@ func GenPlanName(
config := settings.ModelPack.Namer
content := prompts.GetPlanNamePrompt(planContent)
- contentTokens, err := shared.GetNumTokens(content)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
- }
-
- numTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + contentTokens
-
messages := []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
@@ -40,6 +32,8 @@ func GenPlanName(
},
}
+ numTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
+
var responseFormat *openai.ChatCompletionResponseFormat
if config.BaseModelConfig.HasJsonResponseMode {
responseFormat = &openai.ChatCompletionResponseFormat{Type: "json_object"}
@@ -55,7 +49,7 @@ func GenPlanName(
},
})
if apiErr != nil {
- return "", err
+ return "", fmt.Errorf("error executing hook: %v", apiErr)
}
resp, err := CreateChatCompletionWithRetries(
@@ -106,11 +100,7 @@ func GenPlanName(
outputTokens = resp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(res)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
- }
+ outputTokens = shared.GetNumTokensEstimate(res)
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
@@ -155,12 +145,6 @@ func GenPipedDataName(
content := prompts.GetPipedDataNamePrompt(pipedContent)
- contentTokens, err := shared.GetNumTokens(content)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
- }
-
messages := []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
@@ -168,7 +152,7 @@ func GenPipedDataName(
},
}
- numTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + contentTokens
+ numTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
var responseFormat *openai.ChatCompletionResponseFormat
if config.BaseModelConfig.HasJsonResponseMode {
@@ -185,7 +169,7 @@ func GenPipedDataName(
},
})
if apiErr != nil {
- return "", err
+ return "", fmt.Errorf("error executing hook: %v", apiErr)
}
log.Println("calling piped data name model")
@@ -244,11 +228,7 @@ func GenPipedDataName(
outputTokens = resp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(res)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
- }
+ outputTokens = shared.GetNumTokensEstimate(res)
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
@@ -297,14 +277,6 @@ func GenNoteName(
content := prompts.GetNoteNamePrompt(note)
- contentTokens, err := shared.GetNumTokens(content)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
- }
-
- numTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + contentTokens
-
messages := []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
@@ -312,6 +284,8 @@ func GenNoteName(
},
}
+ numTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
+
var responseFormat *openai.ChatCompletionResponseFormat
if config.BaseModelConfig.HasJsonResponseMode {
responseFormat = &openai.ChatCompletionResponseFormat{Type: "json_object"}
@@ -327,7 +301,7 @@ func GenNoteName(
},
})
if apiErr != nil {
- return "", err
+ return "", fmt.Errorf("error executing hook: %v", apiErr)
}
log.Println("calling piped data name model")
@@ -386,11 +360,7 @@ func GenNoteName(
outputTokens = resp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(res)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
- }
+ outputTokens = shared.GetNumTokensEstimate(res)
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.go
index 49551582..7c299c84 100644
--- a/app/server/model/plan/build_exec.go
+++ b/app/server/model/plan/build_exec.go
@@ -346,13 +346,7 @@ func (fileState *activeBuildStreamFileState) buildFile() {
fileState.onFinishBuildFile(planRes)
return
} else {
- currentNumTokens, err := shared.GetNumTokens(fileState.preBuildState)
-
- if err != nil {
- log.Printf("Error getting num tokens for current state: %v\n", err)
- fileState.onBuildFileError(fmt.Errorf("error getting num tokens for current state: %v", err))
- return
- }
+ currentNumTokens := shared.GetNumTokensEstimate(fileState.preBuildState)
log.Printf("Current state num tokens: %d\n", currentNumTokens)
diff --git a/app/server/model/plan/build_structured_edits.go b/app/server/model/plan/build_structured_edits.go
index 0f88fb6c..626a807c 100644
--- a/app/server/model/plan/build_structured_edits.go
+++ b/app/server/model/plan/build_structured_edits.go
@@ -166,15 +166,7 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
},
}
- promptTokens, err := shared.GetNumTokens(validateSysPrompt)
-
- if err != nil {
- log.Printf("buildStructuredEdits - error getting num tokens for prompt: %v\n", err)
- fileState.onBuildFileError(fmt.Errorf("error getting num tokens for prompt: %v", err))
- return
- }
-
- inputTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + promptTokens
+ inputTokens := shared.GetMessagesTokenEstimate(validateFileMessages...) + shared.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: auth,
diff --git a/app/server/model/plan/build_whole_file.go b/app/server/model/plan/build_whole_file.go
index fc000119..d04b5fde 100644
--- a/app/server/model/plan/build_whole_file.go
+++ b/app/server/model/plan/build_whole_file.go
@@ -43,15 +43,7 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(proposedCont
},
}
- promptTokens, err := shared.GetNumTokens(sysPrompt)
-
- if err != nil {
- log.Printf("buildWholeFile - error getting num tokens for prompt: %v\n", err)
- fileState.onBuildFileError(fmt.Errorf("error getting num tokens for prompt: %v", err))
- return
- }
-
- inputTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + promptTokens
+ inputTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: auth,
diff --git a/app/server/model/plan/commit_msg.go b/app/server/model/plan/commit_msg.go
index f1a5003a..bbc20363 100644
--- a/app/server/model/plan/commit_msg.go
+++ b/app/server/model/plan/commit_msg.go
@@ -37,7 +37,18 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
responseFormat = &openai.ChatCompletionResponseFormat{Type: "json_object"}
}
- numTokens := prompts.ExtraTokensPerRequest + (prompts.ExtraTokensPerMessage * 2) + prompts.SysDescribeNumTokens + activePlan.NumTokens
+ messages := []openai.ChatCompletionMessage{
+ {
+ Role: openai.ChatMessageRoleSystem,
+ Content: prompts.SysDescribe,
+ },
+ {
+ Role: openai.ChatMessageRoleAssistant,
+ Content: activePlan.CurrentReplyContent,
+ },
+ }
+
+ numTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: auth,
@@ -71,16 +82,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
Name: prompts.DescribePlanFn.Name,
},
},
- Messages: []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: prompts.SysDescribe,
- },
- {
- Role: openai.ChatMessageRoleAssistant,
- Content: activePlan.CurrentReplyContent,
- },
- },
+ Messages: messages,
Temperature: config.Temperature,
TopP: config.TopP,
ResponseFormat: responseFormat,
@@ -113,11 +115,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
outputTokens = descResp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(descStrRes)
-
- if err != nil {
- return nil, fmt.Errorf("error getting num tokens for content: %v", err)
- }
+ outputTokens = shared.GetNumTokensEstimate(descStrRes)
}
log.Println("Sending DidSendModelRequest hook")
@@ -180,13 +178,18 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
content := "Pending changes:\n\n" + s
- contentTokens, err := shared.GetNumTokens(content)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
+ messages := []openai.ChatCompletionMessage{
+ {
+ Role: openai.ChatMessageRoleSystem,
+ Content: prompts.SysPendingResults,
+ },
+ {
+ Role: openai.ChatMessageRoleUser,
+ Content: content,
+ },
}
- numTokens := prompts.ExtraTokensPerRequest + (prompts.ExtraTokensPerMessage * 2) + prompts.SysPendingResultsNumTokens + contentTokens
+ numTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: auth,
@@ -201,17 +204,6 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
return "", errors.New(apiErr.Msg)
}
- messages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: prompts.SysPendingResults,
- },
- {
- Role: openai.ChatMessageRoleUser,
- Content: content,
- },
- }
-
resp, err := model.CreateChatCompletionWithRetries(
client,
ctx,
@@ -242,11 +234,7 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
outputTokens = resp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(commitMsg)
-
- if err != nil {
- return "", fmt.Errorf("error getting num tokens for content: %v", err)
- }
+ outputTokens = shared.GetNumTokensEstimate(commitMsg)
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
diff --git a/app/server/model/plan/exec_status.go b/app/server/model/plan/exec_status.go
index 899bb623..a89ba2be 100644
--- a/app/server/model/plan/exec_status.go
+++ b/app/server/model/plan/exec_status.go
@@ -46,14 +46,14 @@ func (state *activeTellStreamState) execStatusShouldContinue(message string, ctx
content := prompts.GetExecStatusShouldContinue(state.userPrompt, message)
- contentTokens, err := shared.GetNumTokens(content)
-
- if err != nil {
- log.Printf("Error getting num tokens for content: %v\n", err)
- return false, false, fmt.Errorf("error getting num tokens for content: %v", err)
+ messages := []openai.ChatCompletionMessage{
+ {
+ Role: openai.ChatMessageRoleSystem,
+ Content: content,
+ },
}
- numTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + contentTokens
+ numTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: auth,
@@ -68,13 +68,6 @@ func (state *activeTellStreamState) execStatusShouldContinue(message string, ctx
return false, false, fmt.Errorf("error executing hook: %v", apiErr)
}
- messages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: content,
- },
- }
-
log.Println("Calling model to check if plan should continue")
// log.Println("messages:")
@@ -136,11 +129,7 @@ func (state *activeTellStreamState) execStatusShouldContinue(message string, ctx
outputTokens = resp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(strRes)
-
- if err != nil {
- return false, false, fmt.Errorf("error getting num tokens for res: %v", err)
- }
+ outputTokens = shared.GetNumTokensEstimate(strRes)
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
diff --git a/app/server/model/plan/tell_context.go b/app/server/model/plan/tell_context.go
index cfb07d94..f02dfdcc 100644
--- a/app/server/model/plan/tell_context.go
+++ b/app/server/model/plan/tell_context.go
@@ -11,13 +11,12 @@ import (
"github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees, isImplementationStage, smartContextEnabled, execEnabled bool) (string, int, error) {
+func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees, isImplementationStage, smartContextEnabled, execEnabled bool) (string, error) {
log.Println("Tell plan - formatModelContext")
var contextMessages []string = []string{
"### LATEST PLAN CONTEXT ###",
}
- var numTokens int
addedFilesSet := map[string]bool{}
uses := map[string]bool{}
@@ -77,16 +76,7 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
args = append(args, part.Name, part.Body)
}
- if part.ContextType == shared.ContextImageType {
- numTokens += part.NumTokens
- } else {
- numContextTokens, err := shared.GetNumTokens(fmt.Sprintf(fmtStr, ""))
- if err != nil {
- err = fmt.Errorf("failed to get the number of tokens in the context: %v", err)
- return "", 0, err
- }
-
- numTokens += part.NumTokens + numContextTokens
+ if part.ContextType != shared.ContextImageType {
message = fmt.Sprintf(fmtStr, args...)
contextMessages = append(contextMessages, message)
}
@@ -138,21 +128,14 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
contextMessages = append(contextMessages, fmt.Sprintf("\n\n- _apply.sh:\n\n```\n%s\n```", scriptContent))
}
- return strings.Join(contextMessages, "\n### END OF CONTEXT ###\n"), numTokens, nil
+ return strings.Join(contextMessages, "\n\n") + "\n\n### END OF CONTEXT ###\n\n", nil
}
var pathRegex = regexp.MustCompile("`(.+?)`")
func (state *activeTellStreamState) checkAutoLoadContext() []string {
req := state.req
-
- activePlan := GetActivePlan(state.plan.Id, state.branch)
-
- if activePlan == nil {
- log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", state.plan.Id, state.branch)
- return nil
- }
-
+ activePlan := state.activePlan
contextsByPath := activePlan.ContextsByPath
if !activePlan.AutoContext {
@@ -186,13 +169,10 @@ func (state *activeTellStreamState) checkAutoLoadContext() []string {
return files
}
-func (state *activeTellStreamState) addImageContext() bool {
- active := GetActivePlan(state.plan.Id, state.branch)
+func (state *activeTellStreamState) addImageContext() (int, bool) {
+ active := state.activePlan
- if active == nil {
- log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", state.plan.Id, state.branch)
- return false
- }
+ var imageContextTokens int
for _, context := range state.modelContext {
if context.ContextType == shared.ContextImageType {
@@ -204,9 +184,11 @@ func (state *activeTellStreamState) addImageContext() bool {
Status: http.StatusBadRequest,
Msg: "Model does not support images in context",
}
- return false
+ return 0, false
}
+ imageContextTokens += context.NumTokens
+
imageMessage := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
MultiContent: []openai.ChatMessagePart{
@@ -227,5 +209,5 @@ func (state *activeTellStreamState) addImageContext() bool {
}
}
- return true
+ return imageContextTokens, true
}
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index a12156b9..c7df5cd0 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -35,33 +35,49 @@ func Tell(clients map[string]*openai.Client, plan *db.Plan, branch string, auth
return err
}
- go execTellPlan(
- clients,
- plan,
- branch,
- auth,
- req,
- 0,
- "",
- !req.IsChatOnly && req.BuildMode == shared.BuildModeAuto,
- 0,
- )
+ go execTellPlan(execTellPlanParams{
+ clients: clients,
+ plan: plan,
+ branch: branch,
+ auth: auth,
+ req: req,
+ iteration: 0,
+ shouldBuildPending: !req.IsChatOnly && req.BuildMode == shared.BuildModeAuto,
+ })
log.Printf("Tell: Tell operation completed successfully for plan ID %s on branch %s\n", plan.Id, branch)
return nil
}
-func execTellPlan(
- clients map[string]*openai.Client,
- plan *db.Plan,
- branch string,
- auth *types.ServerAuth,
- req *shared.TellPlanRequest,
- iteration int,
- missingFileResponse shared.RespondMissingFileChoice,
- shouldBuildPending bool,
- numErrorRetry int,
-) {
+type execTellPlanParams struct {
+ clients map[string]*openai.Client
+ plan *db.Plan
+ branch string
+ auth *types.ServerAuth
+ req *shared.TellPlanRequest
+ iteration int
+ missingFileResponse shared.RespondMissingFileChoice
+ shouldBuildPending bool
+ numErrorRetry int
+ shouldLoadFollowUpContext bool
+ didLoadFollowUpContext bool
+ didMakeFollowUpPlan bool
+}
+
+func execTellPlan(params execTellPlanParams) {
+ clients := params.clients
+ plan := params.plan
+ branch := params.branch
+ auth := params.auth
+ req := params.req
+ iteration := params.iteration
+ missingFileResponse := params.missingFileResponse
+ shouldBuildPending := params.shouldBuildPending
+ numErrorRetry := params.numErrorRetry
+ shouldLoadFollowUpContext := params.shouldLoadFollowUpContext
+ didLoadFollowUpContext := params.didLoadFollowUpContext
+ didMakeFollowUpPlan := params.didMakeFollowUpPlan
+
log.Printf("execTellPlan: Called for plan ID %s on branch %s, iteration %d\n", plan.Id, branch, iteration)
currentUserId := auth.User.Id
currentOrgId := auth.OrgId
@@ -125,12 +141,26 @@ func execTellPlan(
autoContextEnabled := req.AutoContext && state.hasContextMap
smartContextEnabled := req.AutoContext
- isPlanningStage := req.IsChatOnly || (!req.IsUserContinue && (iteration == 0 || (autoContextEnabled && iteration == 1)))
+
+ isFollowUp := shouldLoadFollowUpContext || (iteration == 0 && (len(state.subtasks) > 0 || (req.IsChatOnly && state.hasAssistantReply)))
+
+ isPlanningStage := req.IsChatOnly ||
+ shouldLoadFollowUpContext ||
+ didLoadFollowUpContext ||
+ (!req.IsUserContinue &&
+ !didMakeFollowUpPlan &&
+ (iteration == 0 ||
+ (autoContextEnabled && iteration == 1)))
+
isImplementationStage := !isPlanningStage
- isContextStage := isPlanningStage && autoContextEnabled && !state.contextMapEmpty && iteration == 0
- log.Printf("isPlanningStage: %t, isImplementationStage: %t, isContextStage: %t\n", isPlanningStage, isImplementationStage, isContextStage)
+ isContextStage := isPlanningStage &&
+ (shouldLoadFollowUpContext ||
+ (!isFollowUp && autoContextEnabled && !state.contextMapEmpty && iteration == 0))
+
+ log.Printf("isPlanningStage: %t, isImplementationStage: %t, isContextStage: %t, isFollowUp: %t\n", isPlanningStage, isImplementationStage, isContextStage, isFollowUp)
+ state.isFollowUp = isFollowUp
state.isPlanningStage = isPlanningStage
state.isImplementationStage = isImplementationStage
state.isContextStage = isContextStage
@@ -143,7 +173,7 @@ func execTellPlan(
includeMaps = false
}
- modelContextText, modelContextTokens, err := state.formatModelContext(includeMaps, true, isImplementationStage, smartContextEnabled, req.ExecEnabled)
+ modelContextText, err := state.formatModelContext(includeMaps, true, isImplementationStage, smartContextEnabled, req.ExecEnabled)
if err != nil {
err = fmt.Errorf("error formatting model modelContext: %v", err)
log.Println(err)
@@ -156,8 +186,14 @@ func execTellPlan(
return
}
- ok, sysPrompt, sysPromptTokens := state.getTellSysPrompt(isPlanningStage, isContextStage, autoContextEnabled, smartContextEnabled, modelContextText)
- if !ok {
+ sysPrompt, err := state.getTellSysPrompt(autoContextEnabled, smartContextEnabled, modelContextText)
+ if err != nil {
+ log.Printf("Error getting tell sys prompt: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: err.Error(),
+ }
return
}
@@ -171,70 +207,30 @@ func execTellPlan(
}
// Add a separate message for image contexts
- if !state.addImageContext() {
- return
- }
-
- osDetailsTokens, err := shared.GetNumTokens(req.OsDetails)
- if err != nil {
- log.Printf("Error getting num tokens for os details: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for os details",
- }
+ imageContextTokens, ok := state.addImageContext()
+ if !ok {
return
}
- var (
- numPromptTokens int
- promptTokens int
- )
-
- var wrapperTokens int
- if isPlanningStage {
- wrapperTokens = prompts.PlanningPromptWrapperTokens
- } else {
- wrapperTokens = prompts.ImplementationPromptWrapperTokens
- }
-
- log.Printf("wrapperTokens: %d\n", wrapperTokens)
-
- if iteration == 0 && missingFileResponse == "" {
- numPromptTokens, err = shared.GetNumTokens(req.Prompt)
- if err != nil {
- err = fmt.Errorf("error getting number of tokens in prompt: %v", err)
- log.Println(err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting number of tokens in prompt",
- }
- return
- }
-
- promptTokens = wrapperTokens + numPromptTokens + osDetailsTokens
- } else if iteration > 0 && missingFileResponse == "" {
- numPromptTokens = prompts.AutoContinuePromptTokens
-
- log.Printf("numPromptTokens: %d\n", numPromptTokens)
- log.Printf("osDetailsTokens: %d\n", osDetailsTokens)
- log.Printf("wrapperTokens: %d\n", wrapperTokens)
-
- promptTokens = wrapperTokens + numPromptTokens + osDetailsTokens
+ var applyScriptSummary string
+ if req.ExecEnabled {
+ applyScriptSummary = prompts.ApplyScriptPromptSummary
}
- if req.ExecEnabled {
- log.Printf("Apply script summary num tokens: %d\n", prompts.ApplyScriptSummaryNumTokens)
- promptTokens += prompts.ApplyScriptSummaryNumTokens
+ promptMessage, ok := state.resolvePromptMessage(isPlanningStage, isContextStage, applyScriptSummary)
+ if !ok {
+ return
}
- state.tokensBeforeConvo = sysPromptTokens + modelContextTokens + state.latestSummaryTokens + promptTokens
+ state.tokensBeforeConvo =
+ shared.GetMessagesTokenEstimate(state.messages...) +
+ shared.GetMessagesTokenEstimate(*promptMessage) +
+ state.latestSummaryTokens +
+ imageContextTokens +
+ shared.TokensPerRequest
// print out breakdown of token usage
- log.Printf("System message tokens: %d\n", sysPromptTokens)
- log.Printf("Context tokens: %d\n", modelContextTokens)
- log.Printf("Prompt tokens: %d\n", promptTokens)
+ log.Printf("Image context tokens: %d\n", imageContextTokens)
log.Printf("Latest summary tokens: %d\n", state.latestSummaryTokens)
log.Printf("Total tokens before convo: %d\n", state.tokensBeforeConvo)
@@ -254,19 +250,12 @@ func execTellPlan(
return
}
- var applyScriptSummary string
- if req.ExecEnabled {
- applyScriptSummary = prompts.ApplyScriptPromptSummary
- }
-
state.replyId = uuid.New().String()
state.replyParser = types.NewReplyParser()
if missingFileResponse == "" {
- if !state.setPromptMessage(isPlanningStage, isContextStage, applyScriptSummary) {
- return
- }
- } else if !state.handleMissingFileResponse(isPlanningStage, applyScriptSummary) {
+ state.messages = append(state.messages, *promptMessage)
+ } else if !state.handleMissingFileResponse(applyScriptSummary) {
return
}
@@ -292,11 +281,14 @@ func execTellPlan(
var stop []string
if isPlanningStage {
stop = []string{"<EndPlandexTasks/>"}
+ if isFollowUp {
+ stop = append(stop, "<PlandexDecideContext/>")
+ }
} else if isImplementationStage {
stop = []string{"<PlandexSubtaskDone/>"}
}
- // log.Println("Stop:", stop)
+ log.Println("Stop:", stop)
// spew.Dump(state.messages)
modelReq := openai.ChatCompletionRequest{
diff --git a/app/server/model/plan/tell_load.go b/app/server/model/plan/tell_load.go
index af99710f..9b2506ed 100644
--- a/app/server/model/plan/tell_load.go
+++ b/app/server/model/plan/tell_load.go
@@ -24,11 +24,11 @@ func (state *activeTellStreamState) loadTellPlan() error {
iteration := state.iteration
missingFileResponse := state.missingFileResponse
- active := GetActivePlan(plan.Id, branch)
-
- if active == nil {
- return fmt.Errorf("no active plan with id %s", plan.Id)
+ err := state.setActivePlan()
+ if err != nil {
+ return err
}
+ active := state.activePlan
lockScope := db.LockScopeWrite
if iteration > 0 || missingFileResponse != "" {
@@ -167,13 +167,7 @@ func (state *activeTellStreamState) loadTellPlan() error {
ap.MessageNum = len(convo)
})
- promptTokens, err := shared.GetNumTokens(req.Prompt)
- if err != nil {
- log.Printf("Error getting prompt num tokens: %v\n", err)
- errCh <- fmt.Errorf("error getting prompt num tokens: %v", err)
- return
- }
-
+ promptTokens := shared.GetNumTokensEstimate(req.Prompt)
innerErrCh := make(chan error)
go func() {
@@ -229,13 +223,7 @@ func (state *activeTellStreamState) loadTellPlan() error {
log.Printf("got %d plan summaries", len(summaries))
if len(summaries) > 0 {
- var err error
- latestSummaryTokens, err = shared.GetNumTokens(summaries[len(summaries)-1].Summary)
- if err != nil {
- log.Printf("Error getting latest summary tokens: %v\n", err)
- innerErrCh <- fmt.Errorf("error getting latest summary tokens: %v", err)
- return
- }
+ latestSummaryTokens = shared.GetNumTokensEstimate(summaries[len(summaries)-1].Summary)
}
innerErrCh <- nil
@@ -352,6 +340,14 @@ func (state *activeTellStreamState) loadTellPlan() error {
}
}
+ state.hasAssistantReply = false
+ for _, convoMessage := range state.convo {
+ if convoMessage.Role == openai.ChatMessageRoleAssistant {
+ state.hasAssistantReply = true
+ break
+ }
+ }
+
if iteration == 0 && missingFileResponse == "" {
UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
ap.Contexts = state.modelContext
@@ -389,3 +385,18 @@ func (state *activeTellStreamState) loadTellPlan() error {
return nil
}
+
+func (state *activeTellStreamState) setActivePlan() error {
+ plan := state.plan
+ branch := state.branch
+
+ active := GetActivePlan(plan.Id, branch)
+
+ if active == nil {
+ return fmt.Errorf("no active plan with id %s", plan.Id)
+ }
+
+ state.activePlan = active
+
+ return nil
+}
diff --git a/app/server/model/plan/tell_missing_file.go b/app/server/model/plan/tell_missing_file.go
index 4648b76b..776508d3 100644
--- a/app/server/model/plan/tell_missing_file.go
+++ b/app/server/model/plan/tell_missing_file.go
@@ -2,7 +2,6 @@ package plan
import (
"log"
- "net/http"
"plandex-server/model/prompts"
"plandex-server/types"
@@ -10,11 +9,13 @@ import (
"github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) handleMissingFileResponse(isPlanningStage bool, applyScriptSummary string) bool {
+func (state *activeTellStreamState) handleMissingFileResponse(applyScriptSummary string) bool {
missingFileResponse := state.missingFileResponse
planId := state.plan.Id
branch := state.branch
req := state.req
+ isFollowUp := state.isFollowUp
+ isPlanningStage := state.isPlanningStage
active := GetActivePlan(planId, branch)
@@ -35,20 +36,10 @@ func (state *activeTellStreamState) handleMissingFileResponse(isPlanningStage bo
replyContent := active.CurrentReplyContent
numTokens := active.NumTokens
- var err error
if missingFileResponse == shared.RespondMissingFileChoiceSkip {
replyBeforeCurrentFile := state.replyParser.GetReplyBeforeCurrentPath()
- numTokens, err = shared.GetNumTokens(replyBeforeCurrentFile)
- if err != nil {
- log.Printf("Error getting num tokens for reply before current file: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for reply before current file",
- }
- return false
- }
+ numTokens = shared.GetNumTokensEstimate(replyBeforeCurrentFile)
replyContent = replyBeforeCurrentFile
state.replyParser = types.NewReplyParser()
@@ -76,19 +67,9 @@ func (state *activeTellStreamState) handleMissingFileResponse(isPlanningStage bo
if missingFileResponse == shared.RespondMissingFileChoiceSkip {
res := state.replyParser.FinishAndRead()
skipPrompt := prompts.GetSkipMissingFilePrompt(res.CurrentFilePath)
- prompt := prompts.GetWrappedPrompt(skipPrompt, req.OsDetails, applyScriptSummary, isPlanningStage) + "\n\n" + skipPrompt // repetition of skip prompt to improve instruction following
-
- skipPromptTokens, err := shared.GetNumTokens(skipPrompt)
- if err != nil {
- log.Printf("Error getting num tokens for skip prompt: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for skip prompt",
- }
- return false
- }
+ prompt := prompts.GetWrappedPrompt(skipPrompt, req.OsDetails, applyScriptSummary, isPlanningStage, isFollowUp) + "\n\n" + skipPrompt // repetition of skip prompt to improve instruction following
+ skipPromptTokens := shared.GetNumTokensEstimate(skipPrompt)
state.totalRequestTokens += skipPromptTokens
state.messages = append(state.messages, openai.ChatCompletionMessage{
@@ -98,19 +79,9 @@ func (state *activeTellStreamState) handleMissingFileResponse(isPlanningStage bo
} else {
missingPrompt := prompts.GetMissingFileContinueGeneratingPrompt(res.CurrentFilePath)
- prompt := prompts.GetWrappedPrompt(missingPrompt, req.OsDetails, applyScriptSummary, isPlanningStage) + "\n\n" + missingPrompt // repetition of missing prompt to improve instruction following
-
- promptTokens, err := shared.GetNumTokens(prompt)
- if err != nil {
- log.Printf("Error getting num tokens for missing file continue prompt: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for missing file continue prompt",
- }
- return false
- }
+ prompt := prompts.GetWrappedPrompt(missingPrompt, req.OsDetails, applyScriptSummary, isPlanningStage, isFollowUp) + "\n\n" + missingPrompt // repetition of missing prompt to improve instruction following
+ promptTokens := shared.GetNumTokensEstimate(prompt)
state.totalRequestTokens += promptTokens
state.messages = append(state.messages, openai.ChatCompletionMessage{
diff --git a/app/server/model/plan/tell_prompt_message.go b/app/server/model/plan/tell_prompt_message.go
index 2bf35b86..5a9bf006 100644
--- a/app/server/model/plan/tell_prompt_message.go
+++ b/app/server/model/plan/tell_prompt_message.go
@@ -9,20 +9,14 @@ import (
"github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextStage bool, applyScriptSummary string) bool {
- planId := state.plan.Id
- branch := state.branch
+func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isContextStage bool, applyScriptSummary string) (*openai.ChatCompletionMessage, bool) {
req := state.req
iteration := state.iteration
-
- active := GetActivePlan(planId, branch)
-
- if active == nil {
- log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return false
- }
+ active := state.activePlan
+ isFollowUp := state.isFollowUp
var promptMessage *openai.ChatCompletionMessage
+
if req.IsUserContinue {
if len(state.messages) == 0 {
active.StreamDoneCh <- &shared.ApiError{
@@ -30,7 +24,7 @@ func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextS
Status: http.StatusBadRequest,
Msg: "No messages yet. Can't continue plan.",
}
- return false
+ return nil, false
}
// if the user is continuing the plan, we need to check whether the previous message was a user message or assistant message
@@ -47,7 +41,7 @@ func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextS
state.messages = state.messages[:len(state.messages)-1]
promptMessage = &openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
- Content: prompts.GetWrappedPrompt(lastMessage.Content, req.OsDetails, applyScriptSummary, isPlanningStage),
+ Content: prompts.GetWrappedPrompt(lastMessage.Content, req.OsDetails, applyScriptSummary, isPlanningStage, isFollowUp),
}
state.userPrompt = lastMessage.Content
@@ -59,7 +53,7 @@ func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextS
// otherwise we'll use the continue prompt
promptMessage = &openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
- Content: prompts.GetWrappedPrompt(prompts.UserContinuePrompt, req.OsDetails, applyScriptSummary, isPlanningStage),
+ Content: prompts.GetWrappedPrompt(prompts.UserContinuePrompt, req.OsDetails, applyScriptSummary, isPlanningStage, isFollowUp),
}
}
@@ -69,10 +63,8 @@ func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextS
if iteration == 0 {
if req.IsChatOnly {
prompt = req.Prompt + prompts.ChatOnlyPrompt
- state.totalRequestTokens += prompts.ChatOnlyPromptTokens
} else if req.IsUserDebug {
prompt = req.Prompt + prompts.DebugPrompt
- state.totalRequestTokens += prompts.DebugPromptTokens
} else if req.IsApplyDebug {
prompt = req.Prompt + prompts.ApplyDebugPrompt
state.totalRequestTokens += prompts.ApplyDebugPromptTokens
@@ -89,7 +81,7 @@ func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextS
if isContextStage {
finalPrompt = prompt
} else {
- finalPrompt = prompts.GetWrappedPrompt(prompt, req.OsDetails, applyScriptSummary, isPlanningStage)
+ finalPrompt = prompts.GetWrappedPrompt(prompt, req.OsDetails, applyScriptSummary, isPlanningStage, isFollowUp)
}
// log.Println("Final prompt:", finalPrompt)
@@ -102,8 +94,5 @@ func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextS
// log.Println("Prompt message:", promptMessage.Content)
- state.promptMessage = promptMessage
- state.messages = append(state.messages, *promptMessage)
-
- return true
+ return promptMessage, true
}
diff --git a/app/server/model/plan/tell_state.go b/app/server/model/plan/tell_state.go
index 38a0083a..aa70b23b 100644
--- a/app/server/model/plan/tell_state.go
+++ b/app/server/model/plan/tell_state.go
@@ -3,13 +3,13 @@ package plan
import (
"plandex-server/db"
"plandex-server/types"
- "strings"
"github.com/plandex/plandex/shared"
"github.com/sashabaranov/go-openai"
)
type activeTellStreamState struct {
+ activePlan *types.ActivePlan
clients map[string]*openai.Client
req *shared.TellPlanRequest
auth *types.ServerAuth
@@ -40,11 +40,14 @@ type activeTellStreamState struct {
currentReplyNumRetries int
subtasks []*db.Subtask
currentSubtask *db.Subtask
+ hasAssistantReply bool
isContextStage bool
isPlanningStage bool
isImplementationStage bool
+ isFollowUp bool
+
chunkProcessor *chunkProcessor
}
@@ -53,7 +56,7 @@ type chunkProcessor struct {
chunksReceived int
maybeRedundantOpeningTagContent string
fileOpen bool
- contentBuffer *strings.Builder
+ contentBuffer string
awaitingBlockOpeningTag bool
awaitingBlockClosingTag bool
awaitingOpClosingTag bool
diff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.go
index 7e858155..2bace61a 100644
--- a/app/server/model/plan/tell_stream_finish.go
+++ b/app/server/model/plan/tell_stream_finish.go
@@ -6,6 +6,7 @@ import (
"net/http"
"plandex-server/db"
"plandex-server/types"
+ "strings"
"time"
"github.com/plandex/plandex/shared"
@@ -33,9 +34,8 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
iteration := state.iteration
replyOperations := state.chunkProcessor.replyOperations
- active := GetActivePlan(planId, branch)
-
- if active == nil {
+ err := state.setActivePlan()
+ if err != nil {
state.onActivePlanMissingError()
return handleStreamFinishedResult{
shouldContinueMainLoop: true,
@@ -43,6 +43,8 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
}
}
+ active := state.activePlan
+
time.Sleep(30 * time.Millisecond)
active.FlushStreamBuffer()
time.Sleep(100 * time.Millisecond)
@@ -52,7 +54,7 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
})
active.FlushStreamBuffer()
- err := db.SetPlanStatus(planId, branch, shared.PlanStatusDescribing, "")
+ err = db.SetPlanStatus(planId, branch, shared.PlanStatusDescribing, "")
if err != nil {
state.onError(fmt.Errorf("failed to set plan status to describing: %v", err), true, "", "")
return handleStreamFinishedResult{
@@ -63,6 +65,7 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
autoLoadContextFiles := state.checkAutoLoadContext()
hasNewSubtasks := state.checkNewSubtasks()
+ followUpNeedsContextStage := state.followUpNeedsContextStage()
handleDescAndExecStatusRes := state.handleDescAndExecStatus(autoLoadContextFiles, hasNewSubtasks)
if handleDescAndExecStatusRes.shouldContinueMainLoop || handleDescAndExecStatusRes.shouldReturn {
@@ -72,7 +75,13 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
shouldContinue := handleDescAndExecStatusRes.shouldContinue
subtaskFinished := handleDescAndExecStatusRes.subtaskFinished
- storeOnFinishedResult := state.storeOnFinished(replyOperations, generatedDescription, subtaskFinished, hasNewSubtasks)
+ storeOnFinishedResult := state.storeOnFinished(storeOnFinishedParams{
+ replyOperations: replyOperations,
+ generatedDescription: generatedDescription,
+ subtaskFinished: subtaskFinished,
+ hasNewSubtasks: hasNewSubtasks,
+ followUpNeedsContextStage: followUpNeedsContextStage,
+ })
if storeOnFinishedResult.shouldContinueMainLoop || storeOnFinishedResult.shouldReturn {
return storeOnFinishedResult.handleStreamFinishedResult
}
@@ -153,6 +162,11 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
}
}
+ if followUpNeedsContextStage {
+ log.Println("Clearing context before follow up context stage")
+
+ }
+
// if we're auto-loading context files, we always want to continue for at least another iteration with the loaded context
log.Printf("req.AutoContinue: %v\n", req.AutoContinue)
log.Printf("shouldContinue: %v\n", shouldContinue)
@@ -161,13 +175,24 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
log.Printf("hasNewSubtasks: %v\n", hasNewSubtasks)
log.Printf("len(state.subtasks): %d\n", len(state.subtasks))
log.Printf("allSubtasksFinished: %v\n", allSubtasksFinished)
+ log.Printf("followUpNeedsContextStage: %v\n", followUpNeedsContextStage)
- if (len(autoLoadContextFiles) > 0 && !hasNewSubtasks) ||
+ if followUpNeedsContextStage ||
+ (len(autoLoadContextFiles) > 0 && !hasNewSubtasks) ||
(req.AutoContinue && shouldContinue && iteration < MaxAutoContinueIterations &&
!(len(state.subtasks) > 0 && allSubtasksFinished)) {
log.Println("Auto continue plan")
// continue plan
- execTellPlan(clients, plan, branch, auth, req, iteration+1, "", false, 0)
+ execTellPlan(execTellPlanParams{
+ clients: clients,
+ plan: plan,
+ branch: branch,
+ auth: auth,
+ req: req,
+ iteration: iteration + 1,
+ shouldLoadFollowUpContext: followUpNeedsContextStage,
+ didMakeFollowUpPlan: state.isFollowUp && !followUpNeedsContextStage && hasNewSubtasks,
+ })
} else {
var buildFinished bool
UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
@@ -328,31 +353,33 @@ func (state *activeTellStreamState) handleDescAndExecStatus(autoLoadContextFiles
}
}
+type storeOnFinishedParams struct {
+ replyOperations []*shared.Operation
+ generatedDescription *db.ConvoMessageDescription
+ subtaskFinished bool
+ hasNewSubtasks bool
+ followUpNeedsContextStage bool
+}
+
type storeOnFinishedResult struct {
handleStreamFinishedResult
allSubtasksFinished bool
}
-func (state *activeTellStreamState) storeOnFinished(replyOperations []*shared.Operation, generatedDescription *db.ConvoMessageDescription, subtaskFinished, hasNewSubtasks bool) storeOnFinishedResult {
+func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams) storeOnFinishedResult {
+ replyOperations := params.replyOperations
+ generatedDescription := params.generatedDescription
+ subtaskFinished := params.subtaskFinished
+ hasNewSubtasks := params.hasNewSubtasks
+ followUpNeedsContextStage := params.followUpNeedsContextStage
+
currentOrgId := state.currentOrgId
currentUserId := state.currentUserId
planId := state.plan.Id
branch := state.branch
auth := state.auth
summarizedToMessageId := state.summarizedToMessageId
-
- active := GetActivePlan(planId, branch)
-
- if active == nil {
- state.onActivePlanMissingError()
- return storeOnFinishedResult{
- handleStreamFinishedResult: handleStreamFinishedResult{
- shouldContinueMainLoop: true,
- shouldReturn: false,
- },
- allSubtasksFinished: false,
- }
- }
+ active := state.activePlan
var allSubtasksFinished bool
@@ -479,11 +506,23 @@ func (state *activeTellStreamState) storeOnFinished(replyOperations []*shared.Op
// log.Println("Update state of subtasks")
// spew.Dump(state.subtasks)
+
}
- // spew.Dump(description)
+ if followUpNeedsContextStage {
+ log.Println("Clearing non-map/non-pending context before follow up context stage")
+ err := db.ClearContext(db.ClearContextParams{
+ OrgId: currentOrgId,
+ PlanId: planId,
+ SkipMaps: true,
+ SkipPending: true,
+ })
+ if err != nil {
+ log.Printf("Error clearing context: %v\n", err)
+ }
+ }
- log.Println("Comitting reply message, description, and subtasks")
+ log.Println("Comitting after store on finished")
err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)
if err != nil {
@@ -525,11 +564,7 @@ func (state *activeTellStreamState) storeAssistantReply() (*db.ConvoMessage, str
log.Printf("storing assistant reply | len(convo) %d | num %d\n", len(convo), num)
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- return nil, "", fmt.Errorf("active plan not found")
- }
+ activePlan := state.activePlan
assistantMsg := db.ConvoMessage{
Id: replyId,
@@ -559,3 +594,14 @@ func (state *activeTellStreamState) storeAssistantReply() (*db.ConvoMessage, str
return &assistantMsg, commitMsg, err
}
+
+func (state *activeTellStreamState) followUpNeedsContextStage() bool {
+ if !(state.isPlanningStage && state.isFollowUp && state.iteration == 0) {
+ return false
+ }
+
+ active := state.activePlan
+
+ return strings.Contains(active.CurrentReplyContent, "clear all context") ||
+ strings.Contains(active.CurrentReplyContent, "decide what context I need")
+}
diff --git a/app/server/model/plan/tell_stream_main.go b/app/server/model/plan/tell_stream_main.go
index 75fcf82c..41ac54ed 100644
--- a/app/server/model/plan/tell_stream_main.go
+++ b/app/server/model/plan/tell_stream_main.go
@@ -4,7 +4,6 @@ import (
"fmt"
"log"
"plandex-server/model"
- "strings"
"time"
"github.com/plandex/plandex/shared"
@@ -30,7 +29,7 @@ func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionSt
chunksReceived: 0,
maybeRedundantOpeningTagContent: "",
fileOpen: false,
- contentBuffer: &strings.Builder{},
+ contentBuffer: "",
awaitingBlockOpeningTag: false,
awaitingBlockClosingTag: false,
awaitingBackticks: false,
diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.go
index 223ac4c1..f492cc6e 100644
--- a/app/server/model/plan/tell_stream_processor.go
+++ b/app/server/model/plan/tell_stream_processor.go
@@ -10,10 +10,13 @@ import (
"strings"
"time"
+ "github.com/davecgh/go-spew/spew"
"github.com/plandex/plandex/shared"
"github.com/sashabaranov/go-openai"
)
+const verboseLogging = false
+
var openingTagRegex = regexp.MustCompile(`<PlandexBlock\s+lang="(.+?)".*?>`)
type processChunkResult struct {
@@ -44,51 +47,33 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStr
processor.chunksReceived++
- // log.Printf("content: %s\n", content)
-
- // Below needs reworking to correctly integrate with the rest of the processor
- // Maybe isn't necessary anymore
- // buffer if we're continuing after a missing file response to avoid sending redundant opening tags
- // if missingFileResponse != "" {
- // if processor.maybeRedundantOpeningTagContent != "" {
- // if strings.Contains(content, "\n") {
- // processor.maybeRedundantOpeningTagContent = ""
- // } else {
- // processor.maybeRedundantOpeningTagContent += content
- // }
-
- // // skip processing this chunk
- // return processChunkResult{}
- // } else if processor.chunksReceived < 3 && strings.Contains(content, "<PlandexBlock") {
- // // received <PlandexBlock in first 3 chunks after missing file response
- // // means this is a redundant start of a new file block, so just ignore it
-
- // processor.maybeRedundantOpeningTagContent += content
-
- // // skip processing this chunk
- // return processChunkResult{}
- // }
- // }
-
- // log.Printf("Adding chunk to parser: %s\n", content)
- // log.Printf("fileOpen: %v\n", processor.fileOpen)
+ if verboseLogging {
+ log.Printf("Adding chunk to parser: %s\n", content)
+ log.Printf("fileOpen: %v\n", processor.fileOpen)
+ }
replyParser.AddChunk(content, true)
parserRes := replyParser.Read()
if !processor.fileOpen && parserRes.CurrentFilePath != "" {
- log.Printf("File open: %s\n", parserRes.CurrentFilePath)
+ if verboseLogging {
+ log.Printf("File open: %s\n", parserRes.CurrentFilePath)
+ }
processor.fileOpen = true
}
if processor.fileOpen && strings.HasSuffix(active.CurrentReplyContent+content, "</PlandexBlock>") {
- log.Println("FinishAndRead because of closing tag")
+ if verboseLogging {
+ log.Println("FinishAndRead because of closing tag")
+ }
parserRes = replyParser.FinishAndRead()
processor.fileOpen = false
}
if processor.fileOpen && parserRes.CurrentFilePath == "" {
- log.Println("File open but current file path is empty, closing file")
+ if verboseLogging {
+ log.Println("File open but current file path is empty, closing file")
+ }
processor.fileOpen = false
}
@@ -116,13 +101,14 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStr
ap.NumTokens++
})
- // log.Println("processor before bufferOrStream")
- // spew.Dump(processor)
- // log.Println("maybeFilePath", parserRes.MaybeFilePath)
- // log.Println("currentFilePath", parserRes.CurrentFilePath)
-
- // log.Println("res")
- // spew.Dump(res)
+ if verboseLogging {
+ log.Println("processor before bufferOrStream")
+ spew.Dump(processor)
+ log.Println("maybeFilePath", parserRes.MaybeFilePath)
+ log.Println("currentFilePath", parserRes.CurrentFilePath)
+ log.Println("bufferOrStreamRes")
+ spew.Dump(bufferOrStreamRes)
+ }
if bufferOrStreamRes.shouldStream {
active.Stream(shared.StreamMessage{
@@ -131,8 +117,10 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStr
})
}
- // log.Println("processor after bufferOrStream")
- // spew.Dump(processor)
+ if verboseLogging {
+ log.Println("processor after bufferOrStream")
+ spew.Dump(processor)
+ }
if !req.IsChatOnly && len(operations) > len(processor.replyOperations) {
state.handleNewOperations(&parserRes)
@@ -159,51 +147,51 @@ func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types
var shouldStream bool
var blockLang string
- if processor.awaitingBlockOpeningTag || processor.awaitingBlockClosingTag || processor.awaitingBackticks || processor.awaitingOpClosingTag {
- processor.contentBuffer.WriteString(content)
- s := processor.contentBuffer.String()
-
- // log.Printf("awaitingBlockOpeningTag: %v\n", processor.awaitingBlockOpeningTag)
- // log.Printf("awaitingBlockClosingTag: %v\n", processor.awaitingBlockClosingTag)
- // log.Printf("awaitingBackticks: %v\n", processor.awaitingBackticks)
- // log.Printf("awaitingOpClosingTag: %v\n", processor.awaitingOpClosingTag)
- // log.Printf("s: %q\n", s)
-
- if processor.awaitingBackticks {
- if strings.Contains(s, "```") {
- processor.awaitingBackticks = false
- s = strings.ReplaceAll(s, "```", "\\`\\`\\`")
-
- if processor.awaitingBlockOpeningTag || processor.awaitingBlockClosingTag {
- // update buffer with escaped backticks
- processor.contentBuffer.Reset()
- processor.contentBuffer.WriteString(s)
- } else {
- content = s
- processor.contentBuffer.Reset()
- shouldStream = true
- }
- } else if !strings.HasSuffix(s, "`") {
- // fewer than 3 backticks, no need to escape
- processor.awaitingBackticks = false
+ awaitingTag := processor.awaitingBlockOpeningTag || processor.awaitingBlockClosingTag || processor.awaitingOpClosingTag
+ awaitingAny := awaitingTag || processor.awaitingBackticks
- if !(processor.awaitingBlockOpeningTag || processor.awaitingBlockClosingTag) {
- content = s
- processor.contentBuffer.Reset()
- shouldStream = true
- }
+ if awaitingAny {
+ if verboseLogging {
+ log.Println("awaitingAny")
+ }
+ processor.contentBuffer += content
+ content = processor.contentBuffer
+
+ if verboseLogging {
+ log.Printf("awaitingBlockOpeningTag: %v\n", processor.awaitingBlockOpeningTag)
+ log.Printf("awaitingBlockClosingTag: %v\n", processor.awaitingBlockClosingTag)
+ log.Printf("awaitingBackticks: %v\n", processor.awaitingBackticks)
+ log.Printf("awaitingOpClosingTag: %v\n", processor.awaitingOpClosingTag)
+ log.Printf("content: %q\n", content)
+ }
+ }
+
+ if processor.awaitingBackticks {
+ if strings.Contains(content, "```") {
+ processor.awaitingBackticks = false
+ content = strings.ReplaceAll(content, "```", "\\`\\`\\`")
+
+ if !(processor.awaitingBlockOpeningTag || processor.awaitingBlockClosingTag) {
+ shouldStream = true
+ }
+ } else if !strings.HasSuffix(content, "`") {
+ // fewer than 3 backticks, no need to escape
+ processor.awaitingBackticks = false
+
+ if !(processor.awaitingBlockOpeningTag || processor.awaitingBlockClosingTag) {
+ shouldStream = true
}
}
+ }
+ if awaitingTag {
if processor.awaitingBlockOpeningTag {
if parserRes.MaybeFilePath == "" && parserRes.CurrentFilePath == "" {
// wasn't really a file path / code block
processor.awaitingBlockOpeningTag = false
- content = s
- processor.contentBuffer.Reset()
shouldStream = true
} else if parserRes.CurrentFilePath != "" {
- matched, replaced := replaceCodeBlockOpeningTag(s, func(lang string) string {
+ matched, replaced := replaceCodeBlockOpeningTag(content, func(lang string) string {
blockLang = lang
return "```" + lang
})
@@ -213,99 +201,148 @@ func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types
processor.awaitingBlockOpeningTag = false
processor.fileOpen = true
content = replaced
- processor.contentBuffer.Reset()
} else {
// tag is missing - something is wrong - we shouldn't be here but let's try to recover anyway
- log.Printf("Opening <PlandexBlock> tag is missing even though parserRes.CurrentFile is set - something is wrong: %s\n", s)
+ if verboseLogging {
+ log.Printf("Opening <PlandexBlock> tag is missing even though parserRes.CurrentFile is set - something is wrong: %s\n", content)
+ }
processor.awaitingBlockOpeningTag = false
processor.fileOpen = false
- s += "\n```" // add ``` to the end of the line to close the markdown code block
- content = s
- processor.contentBuffer.Reset()
+ content += "\n```" // add ``` to the end of the line to close the markdown code block
shouldStream = true
}
}
} else if processor.awaitingBlockClosingTag {
if parserRes.CurrentFilePath == "" {
- if strings.Contains(s, "</PlandexBlock>") {
+ if strings.Contains(content, "</PlandexBlock>") {
shouldStream = true
processor.awaitingBlockClosingTag = false
processor.fileOpen = false
// replace </PlandexBlock> with ``` to close the markdown code block
- s = strings.ReplaceAll(s, "</PlandexBlock>", "```")
- content = s
- processor.contentBuffer.Reset()
+ content = strings.ReplaceAll(content, "</PlandexBlock>", "```")
} else {
- log.Printf("Closing </PlandexBlock> tag is missing even though parserRes.CurrentOperation is nil - something is wrong: %s\n", s)
+ log.Printf("Closing </PlandexBlock> tag is missing even though parserRes.CurrentOperation is nil - something is wrong: %s\n", content)
processor.awaitingBlockClosingTag = false
- content = s
- processor.contentBuffer.Reset()
shouldStream = true
}
}
} else if processor.awaitingOpClosingTag {
- // log.Printf("awaitingOpClosingTag: %v\n", processor.awaitingOpClosingTag)
- if strings.Contains(s, "<EndPlandexFileOps/>") {
- log.Printf("Found <EndPlandexFileOps/>\n")
+ if verboseLogging {
+ log.Printf("awaitingOpClosingTag: %v\n", processor.awaitingOpClosingTag)
+ }
+ if strings.Contains(content, "<EndPlandexFileOps/>") {
+ if verboseLogging {
+ log.Printf("Found <EndPlandexFileOps/>\n")
+ }
processor.awaitingOpClosingTag = false
- s = strings.Replace(s, "\n<EndPlandexFileOps/>", "", 1)
- s = strings.Replace(s, "<EndPlandexFileOps/>", "", 1)
- content = s
- processor.contentBuffer.Reset()
+ content = strings.Replace(content, "\n<EndPlandexFileOps/>", "", 1)
+ content = strings.Replace(content, "<EndPlandexFileOps/>", "", 1)
shouldStream = true
}
}
} else {
+ if verboseLogging {
+ log.Println("not awaiting tag")
+ }
+
if parserRes.MaybeFilePath != "" && parserRes.CurrentFilePath == "" {
processor.awaitingBlockOpeningTag = true
}
if parserRes.CurrentFilePath != "" {
+ if verboseLogging {
+ log.Println("parserRes.CurrentFilePath != \"\"")
+ }
if strings.Contains(content, "</PlandexBlock>") {
+ if verboseLogging {
+ log.Println("strings.Contains(content, \"</PlandexBlock>\")")
+ }
processor.awaitingBlockClosingTag = true
} else {
+ if verboseLogging {
+ log.Println("not strings.Contains(content, \"</PlandexBlock>\")")
+ }
split := strings.Split(content, "<")
// log.Printf("split: %v\n", split)
if len(split) > 1 {
+ if verboseLogging {
+ log.Println("len(split) > 1")
+ }
last := split[len(split)-1]
// log.Printf("last: %s\n", last)
if strings.HasPrefix("/PlandexBlock>", last) {
+ if verboseLogging {
+ log.Println("strings.HasPrefix(\"/PlandexBlock>\", last)")
+ }
processor.awaitingBlockClosingTag = true
}
}
}
} else if parserRes.FileOperationBlockOpen() {
+ if verboseLogging {
+ log.Println("parserRes.FileOperationBlockOpen()")
+ }
if strings.Contains(content, "<EndPlandexFileOps/>") {
+ if verboseLogging {
+ log.Println("strings.Contains(content, \"<EndPlandexFileOps/>\")")
+ }
processor.awaitingOpClosingTag = true
} else {
+ if verboseLogging {
+ log.Println("not strings.Contains(content, \"<EndPlandexFileOps/>\")")
+ }
split := strings.Split(content, "<")
if len(split) > 1 {
+ if verboseLogging {
+ log.Println("len(split) > 1")
+ }
last := split[len(split)-1]
if strings.HasPrefix("EndPlandexFileOps/>", last) {
+ if verboseLogging {
+ log.Println("strings.HasPrefix(\"EndPlandexFileOps/>\", last)")
+ }
processor.awaitingOpClosingTag = true
}
}
}
} else if strings.Contains(content, "</PlandexBlock>") {
+ if verboseLogging {
+ log.Println("strings.Contains(content, \"</PlandexBlock>\")")
+ }
content = strings.Replace(content, "</PlandexBlock>", "```", 1)
} else if strings.Contains(content, "<EndPlandexFileOps/>") {
+ if verboseLogging {
+ log.Println("strings.Contains(content, \"<EndPlandexFileOps/>\")")
+ }
content = strings.Replace(content, "\n<EndPlandexFileOps/>", "", 1)
content = strings.Replace(content, "<EndPlandexFileOps/>", "", 1)
}
if processor.fileOpen && (strings.Contains(content, "```") || strings.HasSuffix(content, "`")) {
+ if verboseLogging {
+ log.Println("processor.fileOpen && (strings.Contains(content, \"```\") || strings.HasSuffix(content, \"`\"))")
+ }
processor.awaitingBackticks = true
}
var matchedOpeningTag bool
if processor.fileOpen {
+ if verboseLogging {
+ log.Println("processor.fileOpen")
+ }
var replaced string
matchedOpeningTag, replaced = replaceCodeBlockOpeningTag(content, func(lang string) string {
blockLang = lang
return "```" + lang
})
+
+ if verboseLogging {
+ log.Println("matchedOpeningTag", matchedOpeningTag)
+ log.Println("replaced", replaced)
+ }
+
if matchedOpeningTag {
content = replaced
}
@@ -313,11 +350,29 @@ func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types
shouldStream = !processor.awaitingBlockOpeningTag && !processor.awaitingBlockClosingTag && !processor.awaitingOpClosingTag && !processor.awaitingBackticks
- if !shouldStream {
- processor.contentBuffer.WriteString(content)
+ if verboseLogging {
+ log.Println("processor.awaitingBlockOpeningTag", processor.awaitingBlockOpeningTag)
+ log.Println("processor.awaitingBlockClosingTag", processor.awaitingBlockClosingTag)
+ log.Println("processor.awaitingOpClosingTag", processor.awaitingOpClosingTag)
+ log.Println("processor.awaitingBackticks", processor.awaitingBackticks)
+
+ log.Println("shouldStream", shouldStream)
}
}
+ if verboseLogging {
+ log.Println("returning bufferOrStreamResult")
+ log.Println("shouldStream", shouldStream)
+ log.Println("content", content)
+ log.Println("blockLang", blockLang)
+ }
+
+ if shouldStream {
+ processor.contentBuffer = ""
+ } else {
+ processor.contentBuffer = content
+ }
+
return bufferOrStreamResult{
shouldStream: shouldStream,
content: content,
@@ -369,18 +424,12 @@ func (state *activeTellStreamState) handleNewOperations(parserRes *types.ReplyPa
var opContentTokens int
if op.Type == shared.OperationTypeFile {
- var err error
- opContentTokens, err = shared.GetNumTokens(op.Content)
- if err != nil {
- log.Printf("Error getting num tokens for operation %s: %v\n", op.Name(), err)
- state.onError(fmt.Errorf("error getting num tokens for operation %s: %v", op.Name(), err), true, "", "")
- return
- }
+ opContentTokens = shared.GetNumTokensEstimate(op.Content)
} else {
opContentTokens = op.NumTokens
}
- log.Printf("buildState.queueBuilds - op.Description:\n%s\n", op.Description)
+ // log.Printf("buildState.queueBuilds - op.Description:\n%s\n", op.Description)
buildState.queueBuilds([]*types.ActiveBuild{{
ReplyId: replyId,
@@ -513,17 +562,15 @@ func (state *activeTellStreamState) handleMissingFile(content, currentFile, bloc
log.Println("Continuing stream")
// continue plan
- execTellPlan(
- clients,
- plan,
- branch,
- auth,
- req,
- iteration, // keep the same iteration
- userChoice,
- false,
- 0,
- )
+ execTellPlan(execTellPlanParams{
+ clients: clients,
+ plan: plan,
+ branch: branch,
+ auth: auth,
+ req: req,
+ iteration: iteration, // keep the same iteration
+ missingFileResponse: userChoice,
+ })
return processChunkResult{shouldReturn: true}
}
diff --git a/app/server/model/plan/tell_stream_processor_test.go b/app/server/model/plan/tell_stream_processor_test.go
index 758cb362..ba272162 100644
--- a/app/server/model/plan/tell_stream_processor_test.go
+++ b/app/server/model/plan/tell_stream_processor_test.go
@@ -2,7 +2,6 @@ package plan
import (
"plandex-server/types"
- "strings"
"testing"
)
@@ -22,7 +21,7 @@ func TestBufferOrStream(t *testing.T) {
{
name: "streams regular content",
initialState: &chunkProcessor{
- contentBuffer: &strings.Builder{},
+ contentBuffer: "",
},
chunk: "some regular text",
want: bufferOrStreamResult{
@@ -41,7 +40,7 @@ func TestBufferOrStream(t *testing.T) {
initialState: &chunkProcessor{
awaitingBlockOpeningTag: true,
fileOpen: false,
- contentBuffer: &strings.Builder{},
+ contentBuffer: "",
},
chunk: `<Pland`,
maybeFilePath: "main.go",
@@ -54,22 +53,14 @@ func TestBufferOrStream(t *testing.T) {
awaitingBlockClosingTag: false,
awaitingBackticks: false,
fileOpen: false,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString(`<Pland`)
- return b
- }(),
+ contentBuffer: "<Pland",
},
},
{
name: "converts opening tag",
initialState: &chunkProcessor{
- fileOpen: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString(`<PlandexBlock lang="go">` + "\n")
- return b
- }(),
+ fileOpen: true,
+ contentBuffer: `<PlandexBlock lang="go">` + "\n",
awaitingBlockOpeningTag: true,
},
chunk: `package`,
@@ -91,7 +82,7 @@ func TestBufferOrStream(t *testing.T) {
name: "converts opening tag without awaitingOpeningTag",
initialState: &chunkProcessor{
fileOpen: true,
- contentBuffer: &strings.Builder{},
+ contentBuffer: "",
awaitingBlockOpeningTag: false,
},
chunk: `<PlandexBlock lang="go">` + "\npackage",
@@ -111,12 +102,8 @@ func TestBufferOrStream(t *testing.T) {
{
name: "buffers partial backticks",
initialState: &chunkProcessor{
- fileOpen: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("here's some co")
- return b
- }(),
+ fileOpen: true,
+ contentBuffer: "here's some co",
},
chunk: "de:`",
currentFilePath: "main.go",
@@ -133,11 +120,7 @@ func TestBufferOrStream(t *testing.T) {
initialState: &chunkProcessor{
fileOpen: true,
awaitingBackticks: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("here's some code:\n`")
- return b
- }(),
+ contentBuffer: "here's some code:\n`",
},
chunk: "``\npackage",
currentFilePath: "main.go",
@@ -157,7 +140,7 @@ func TestBufferOrStream(t *testing.T) {
initialState: &chunkProcessor{
fileOpen: true,
awaitingBlockClosingTag: false,
- contentBuffer: &strings.Builder{},
+ contentBuffer: "",
},
currentFilePath: "main.go",
chunk: "\n}</Plan",
@@ -167,11 +150,7 @@ func TestBufferOrStream(t *testing.T) {
wantState: &chunkProcessor{
awaitingBlockClosingTag: true,
fileOpen: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("\n}</Plan")
- return b
- }(),
+ contentBuffer: "\n}</Plan",
},
},
{
@@ -179,7 +158,7 @@ func TestBufferOrStream(t *testing.T) {
initialState: &chunkProcessor{
fileOpen: true,
awaitingBlockClosingTag: false,
- contentBuffer: &strings.Builder{},
+ contentBuffer: "",
},
currentFilePath: "main.go",
chunk: "\n}</PlandexBlock>",
@@ -189,11 +168,7 @@ func TestBufferOrStream(t *testing.T) {
wantState: &chunkProcessor{
awaitingBlockClosingTag: true,
fileOpen: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("\n}</PlandexBlock>")
- return b
- }(),
+ contentBuffer: "\n}</PlandexBlock>",
},
},
{
@@ -201,7 +176,7 @@ func TestBufferOrStream(t *testing.T) {
initialState: &chunkProcessor{
fileOpen: false,
awaitingBlockClosingTag: false,
- contentBuffer: &strings.Builder{},
+ contentBuffer: "",
},
currentFilePath: "",
chunk: "\n}</PlandexBlock>",
@@ -214,16 +189,31 @@ func TestBufferOrStream(t *testing.T) {
fileOpen: false,
},
},
+ {
+ name: "replaces full closing tag with file closed and awaiting backticks",
+ initialState: &chunkProcessor{
+ fileOpen: false,
+ awaitingBlockClosingTag: false,
+ awaitingBackticks: true,
+ contentBuffer: "",
+ },
+ currentFilePath: "",
+ chunk: " ONLY this one-line title and nothing else.`\n</PlandexBlock>\n\nNow let",
+ want: bufferOrStreamResult{
+ shouldStream: true,
+ content: " ONLY this one-line title and nothing else.`\n```\n\nNow let",
+ },
+ wantState: &chunkProcessor{
+ awaitingBlockClosingTag: false,
+ fileOpen: false,
+ },
+ },
{
name: "handles single backticks",
initialState: &chunkProcessor{
fileOpen: true,
awaitingBackticks: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("`file.go`")
- return b
- }(),
+ contentBuffer: "`file.go`",
},
chunk: "\nsomething",
currentFilePath: "main.go",
@@ -243,11 +233,7 @@ func TestBufferOrStream(t *testing.T) {
initialState: &chunkProcessor{
fileOpen: true,
awaitingBackticks: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("`file.go`")
- return b
- }(),
+ contentBuffer: "`file.go`",
},
chunk: "\n`file2.go`",
currentFilePath: "main.go",
@@ -259,11 +245,7 @@ func TestBufferOrStream(t *testing.T) {
awaitingBlockClosingTag: false,
awaitingBackticks: true,
fileOpen: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("`file.go`\n`file2.go`")
- return b
- }(),
+ contentBuffer: "`file.go`\n`file2.go`",
},
},
{
@@ -276,22 +258,14 @@ func TestBufferOrStream(t *testing.T) {
},
wantState: &chunkProcessor{
awaitingOpClosingTag: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("\n<EndPlandexFileOps/>\nmore")
- return b
- }(),
+ contentBuffer: "\n<EndPlandexFileOps/>\nmore",
},
},
{
name: "replaces full end of file operations tag",
initialState: &chunkProcessor{
awaitingOpClosingTag: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("\n<EndPlandexFileOps/>\nmore")
- return b
- }(),
+ contentBuffer: "\n<EndPlandexFileOps/>\nmore",
},
chunk: " stuff",
want: bufferOrStreamResult{
@@ -313,22 +287,14 @@ func TestBufferOrStream(t *testing.T) {
},
wantState: &chunkProcessor{
awaitingOpClosingTag: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("\n<EndPlandex")
- return b
- }(),
+ contentBuffer: "\n<EndPlandex",
},
},
{
name: "replaces end of file operation closing partial tag",
initialState: &chunkProcessor{
awaitingOpClosingTag: true,
- contentBuffer: func() *strings.Builder {
- b := &strings.Builder{}
- b.WriteString("\n<EndPlandex")
- return b
- }(),
+ contentBuffer: "\n<EndPlandex",
},
chunk: "FileOps/>\nmore",
want: bufferOrStreamResult{
@@ -345,11 +311,6 @@ func TestBufferOrStream(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
processor := tt.initialState
- // Initialize content buffer if needed
- if processor.contentBuffer == nil {
- processor.contentBuffer = &strings.Builder{}
- }
-
got := processor.bufferOrStream(tt.chunk, &types.ReplyParserRes{
MaybeFilePath: tt.maybeFilePath,
CurrentFilePath: tt.currentFilePath,
@@ -379,14 +340,14 @@ func TestBufferOrStream(t *testing.T) {
t.Errorf("awaitingBackticks = %v, want %v", processor.awaitingBackticks, tt.wantState.awaitingBackticks)
}
- if tt.wantState.contentBuffer != nil {
- if processor.contentBuffer.String() != tt.wantState.contentBuffer.String() {
- t.Errorf("content buffer = %q, want %q", processor.contentBuffer.String(), tt.wantState.contentBuffer.String())
+ if tt.wantState.contentBuffer != "" {
+ if processor.contentBuffer != tt.wantState.contentBuffer {
+ t.Errorf("content buffer = %q, want %q", processor.contentBuffer, tt.wantState.contentBuffer)
}
}
// Check buffer is reset when it should be
- if tt.want.shouldStream && processor.contentBuffer.Len() > 0 {
+ if tt.want.shouldStream && processor.contentBuffer != "" {
t.Error("content buffer should be reset after streaming")
}
})
diff --git a/app/server/model/plan/tell_subtasks.go b/app/server/model/plan/tell_subtasks.go
index 3ab2a945..403b63fd 100644
--- a/app/server/model/plan/tell_subtasks.go
+++ b/app/server/model/plan/tell_subtasks.go
@@ -8,14 +8,11 @@ import (
"strings"
"github.com/davecgh/go-spew/spew"
- "github.com/plandex/plandex/shared"
)
-func (state *activeTellStreamState) formatSubtasks() (string, int, error) {
+func (state *activeTellStreamState) formatSubtasks() string {
subtasksText := "### LATEST PLAN TASKS ###\n\n"
- var numTokens int
-
var current *db.Subtask
for idx, subtask := range state.subtasks {
@@ -62,12 +59,7 @@ func (state *activeTellStreamState) formatSubtasks() (string, int, error) {
}
}
- numTokens, err := shared.GetNumTokens(subtasksText)
- if err != nil {
- return "", 0, fmt.Errorf("error getting num tokens for subtasks: %v", err)
- }
-
- return subtasksText, numTokens, nil
+ return subtasksText
}
func (state *activeTellStreamState) checkNewSubtasks() bool {
@@ -90,18 +82,23 @@ func (state *activeTellStreamState) checkNewSubtasks() bool {
subtasksByName := map[string]*db.Subtask{}
+ // Only index unfinished subtasks by name
for _, subtask := range state.subtasks {
- subtasksByName[subtask.Title] = subtask
+ if !subtask.IsFinished {
+ subtasksByName[subtask.Title] = subtask
+ }
}
var newSubtasks []*db.Subtask
+ // Keep finished subtasks
for _, subtask := range state.subtasks {
if subtask.IsFinished {
newSubtasks = append(newSubtasks, subtask)
}
}
+ // Add new subtasks if they don't exist or if existing one was finished
for _, subtask := range subtasks {
if subtasksByName[subtask.Title] == nil {
newSubtasks = append(newSubtasks, subtask)
@@ -136,5 +133,8 @@ func (state *activeTellStreamState) checkNewSubtasks() bool {
}
}
+ // log.Println("state.subtasks:\n", spew.Sdump(state.subtasks))
+ // log.Println("state.currentSubtask:\n", spew.Sdump(state.currentSubtask))
+
return true
}
diff --git a/app/server/model/plan/tell_summary.go b/app/server/model/plan/tell_summary.go
index 712de6ac..fb02b603 100644
--- a/app/server/model/plan/tell_summary.go
+++ b/app/server/model/plan/tell_summary.go
@@ -29,10 +29,10 @@ func (state *activeTellStreamState) addConversationMessages() bool {
return false
}
- conversationTokens := prompts.ExtraTokensPerRequest
+ conversationTokens := 0
tokensUpToTimestamp := make(map[int64]int)
for _, convoMessage := range convo {
- conversationTokens += convoMessage.Tokens + prompts.ExtraTokensPerMessage
+ conversationTokens += convoMessage.Tokens + shared.TokensPerMessage + shared.TokensPerName
timestamp := convoMessage.CreatedAt.UnixNano() / int64(time.Millisecond)
tokensUpToTimestamp[timestamp] = conversationTokens
// log.Printf("Timestamp: %s | Tokens: %d | Total: %d | conversationTokens\n", convoMessage.Timestamp, convoMessage.Tokens, conversationTokens)
@@ -242,7 +242,7 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
// log.Println("Generating plan summary - convo:")
// spew.Dump(convo)
- numTokens := prompts.ExtraTokensPerRequest
+ numTokens := 0
if latestSummary == nil {
for _, convoMessage := range convo {
@@ -253,7 +253,7 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
latestMessageId = convoMessage.Id
latestMessageSummarizedAt = convoMessage.CreatedAt
numMessagesSummarized++
- numTokens += convoMessage.Tokens + prompts.ExtraTokensPerMessage
+ numTokens += convoMessage.Tokens + shared.TokensPerMessage + shared.TokensPerName
}
} else {
summaryMessages = append(summaryMessages, &openai.ChatCompletionMessage{
@@ -261,7 +261,7 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
Content: latestSummary.Summary,
})
- numTokens += latestSummary.Tokens + prompts.ExtraTokensPerMessage
+ numTokens += latestSummary.Tokens + shared.TokensPerMessage + shared.TokensPerName
var found bool
for _, convoMessage := range convo {
@@ -275,7 +275,7 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
Content: convoMessage.Message,
})
numMessagesSummarized++
- numTokens += convoMessage.Tokens + prompts.ExtraTokensPerMessage
+ numTokens += convoMessage.Tokens + shared.TokensPerMessage + shared.TokensPerName
}
}
@@ -294,13 +294,8 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
Content: userPrompt,
})
- tokens, err := shared.GetNumTokens(userPrompt)
- if err != nil {
- log.Printf("Error getting num tokens for user prompt: %v\n", err)
- return err
- }
-
- numTokens += tokens + prompts.ExtraTokensPerMessage
+ tokens := shared.GetNumTokensEstimate(userPrompt)
+ numTokens += tokens + shared.TokensPerMessage + shared.TokensPerName
}
}
@@ -310,7 +305,7 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
Content: currentReply,
})
- numTokens += params.currentReplyNumTokens + prompts.ExtraTokensPerMessage
+ numTokens += params.currentReplyNumTokens + shared.TokensPerMessage + shared.TokensPerName
}
log.Printf("Calling model for plan summary. Summarizing %d messages\n", len(summaryMessages))
diff --git a/app/server/model/plan/tell_sys_prompt.go b/app/server/model/plan/tell_sys_prompt.go
index a4e39e6c..056dd45f 100644
--- a/app/server/model/plan/tell_sys_prompt.go
+++ b/app/server/model/plan/tell_sys_prompt.go
@@ -3,75 +3,48 @@ package plan
import (
"fmt"
"log"
- "net/http"
"plandex-server/model/prompts"
-
- "github.com/plandex/plandex/shared"
)
-func (state *activeTellStreamState) getTellSysPrompt(isPlanningStage, isContextStage, autoContextEnabled, smartContextEnabled bool, modelContextText string) (bool, string, int) {
+func (state *activeTellStreamState) getTellSysPrompt(autoContextEnabled, smartContextEnabled bool, modelContextText string) (string, error) {
req := state.req
-
- active := GetActivePlan(state.plan.Id, state.branch)
-
- if active == nil {
- log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", state.plan.Id, state.branch)
- return false, "", 0
- }
+ isPlanningStage := state.isPlanningStage
+ isContextStage := state.isContextStage
+ isFollowUp := state.isFollowUp
+ active := state.activePlan
var sysCreate string
- var sysCreateTokens int
if isPlanningStage {
log.Println("isPlanningStage")
if autoContextEnabled && isContextStage {
sysCreate = prompts.AutoContextPreamble
- sysCreateTokens = prompts.AutoContextPreambleNumTokens
} else if autoContextEnabled || smartContextEnabled {
sysCreate = prompts.SysPlanningAutoContext
- sysCreateTokens = prompts.SysPlanningAutoContextTokens
+
+ if isFollowUp {
+ sysCreate = prompts.FollowUpPlanClassifierPrompt + "\n\n" + sysCreate
+ }
} else {
sysCreate = prompts.SysPlanningBasic
- sysCreateTokens = prompts.SysPlanningBasicTokens
}
} else {
log.Println("isImplementationStage")
if state.currentSubtask == nil {
- err := fmt.Errorf("no current subtask")
- log.Println(err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "No current subtask",
- }
- return false, "", 0
+ return "", fmt.Errorf("no current subtask during implementation stage")
}
sysCreate = prompts.GetImplementationPrompt(state.currentSubtask.Title)
- var err error
- sysCreateTokens, err = shared.GetNumTokens(sysCreate)
- if err != nil {
- log.Printf("Error getting num tokens for implementation prompt: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for implementation prompt",
- }
- return false, "", 0
- }
}
if !isContextStage {
if req.ExecEnabled {
if isPlanningStage {
sysCreate += prompts.ApplyScriptPlanningPrompt
- sysCreateTokens += prompts.ApplyScriptPlanningPromptNumTokens
} else {
sysCreate += prompts.ApplyScriptImplementationPrompt
- sysCreateTokens += prompts.ApplyScriptImplementationPromptNumTokens
}
} else {
sysCreate += prompts.NoApplyScriptPrompt
- sysCreateTokens += prompts.NoApplyScriptPromptNumTokens
}
}
@@ -84,40 +57,15 @@ func (state *activeTellStreamState) getTellSysPrompt(isPlanningStage, isContextS
for skippedPath := range active.SkippedPaths {
skippedPrompt += fmt.Sprintf("- %s\n", skippedPath)
}
-
- numTokens, err := shared.GetNumTokens(skippedPrompt)
- if err != nil {
- log.Printf("Error getting num tokens for skipped paths: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for skipped paths",
- }
- return false, "", 0
- }
-
- sysCreateTokens += numTokens
}
if len(state.subtasks) > 0 {
- subtasksPrompt, subtaskTokens, err := state.formatSubtasks()
-
- if err != nil {
- err = fmt.Errorf("error formatting subtasks: %v", err)
- log.Println(err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error formatting subtasks",
- }
- return false, "", 0
- }
+ subtasksPrompt := state.formatSubtasks()
// log.Println("subtasksPrompt:\n", subtasksPrompt)
sysCreate += subtasksPrompt
- sysCreateTokens += subtaskTokens
}
- return true, sysCreate, sysCreateTokens
+ return sysCreate, nil
}
diff --git a/app/server/model/prompts/apply_exec.go b/app/server/model/prompts/apply_exec.go
index 99c0a24f..ed58bc3c 100644
--- a/app/server/model/prompts/apply_exec.go
+++ b/app/server/model/prompts/apply_exec.go
@@ -9,8 +9,6 @@ The command will be run again *automatically* on the user's machine once the cha
Command details:
`
-var DebugPromptTokens int
-
const ApplyDebugPrompt = `The _apply.sh script failed and you must debug. Focus only on fixing this issue so that the command runs successfully; don't make other changes.
Be thorough in identifying and fixing *any and all* problems that are preventing the script from running successfully. If there are multiple problems, identify and fix all of them.
@@ -68,8 +66,6 @@ You MUST NOT tell the user to do anything themselves that's included in the _app
If the plan includes other script files, apart from _apply.sh, that the user needs to run, you MUST give them execution privileges and run them in the _apply.sh script. Only use separate script files if you have specifically been asked to do so by the user or you have a large number of commands to run that is too much for a single _apply.sh script. Otherwise, you MUST include *all* commands to be run in the _apply.sh script, and not use separate script files.
` + ApplyScriptResetOrUpdatePrompt
-var ApplyScriptPlanningPromptNumTokens int
-
const ApplyScriptImplementationPrompt = ApplyScriptPlanningPrompt + `
DO NOT use the _apply.sh script to move, remove, or reset changes to files that are in context or have pending changes—use one of the special file operation sections instead: '### Move Files', '### Remove Files', or '### Reset Changes' if you need to do that, and follow the instructions for those sections.
@@ -164,8 +160,6 @@ npm install --save-dev \
</PlandexBlock>
`
-var ApplyScriptImplementationPromptNumTokens int
-
const ApplyScriptPromptSummary = `
Write any commands that need to be run after the plan is applied to the special _apply.sh file.
@@ -191,8 +185,6 @@ Key instructions for _apply.sh:
- ` + ApplyScriptResetOrUpdatePrompt + `
`
-var ApplyScriptSummaryNumTokens int
-
var NoApplyScriptPrompt = `
## No execution of commands
@@ -206,8 +198,6 @@ When breaking up a task into subtasks, only include subtasks that you can do you
For tasks that you ARE able to complete because they only require creating or updating files, complete them thoroughly yourself and don't ask the user to do any part of them.
`
-var NoApplyScriptPromptNumTokens int
-
const ApplyScriptResetOrUpdatePrompt = `When the user applies the plan, the _apply.sh will be executed.
If it succeeds, the _apply.sh script will then be *reset* to an empty state.
diff --git a/app/server/model/prompts/chat.go b/app/server/model/prompts/chat.go
index 3cbac933..821ec442 100644
--- a/app/server/model/prompts/chat.go
+++ b/app/server/model/prompts/chat.go
@@ -9,5 +9,3 @@ If the user has given you a task, you can begin to make a plan and break a task
UNDER NO CIRCUMSTANCES should you output code blocks or end your response with "Next,". Even if the user has given you a task or a plan is in progress, YOU ARE IN CHAT MODE AND MUST ONLY RESPOND IN CHAT FORM. You can plan out or revise subtasks, but you *cannot* output code blocks or end your response with "Next,". Again, DO NOT implement any changes or output code blocks!! Chat mode takes precedence over your prior instructions and the user's prompt under all circumstances—you MUST respond only in chat form regardless of what the user's prompt or your prior instructions say.
`
-
-var ChatOnlyPromptTokens int
diff --git a/app/server/model/prompts/context_load.go b/app/server/model/prompts/context_load.go
index df51ae8d..d0d55e0b 100644
--- a/app/server/model/prompts/context_load.go
+++ b/app/server/model/prompts/context_load.go
@@ -25,11 +25,13 @@ In response to the user's latest prompt, do the following:
After outputting the '### Relevant Symbols' section, end your response. Do not output any additional text after that section.
+IMPORTANT: During this context loading phase, you must NOT implement any code or create any code blocks. This phase is ONLY for identifying relevant context.
+
+Do not attempt to write any code or begin implementation at this stage. Implementation will happen in a separate phase after context is loaded.
+
[END OF CONTEXT INSTRUCTIONS]
`
-var AutoContextPreambleNumTokens int
-
const ContextLoadingRules = `When assessing relevant context, you MUST follow these rules:
1. Interface & Implementation Rule:
diff --git a/app/server/model/prompts/describe.go b/app/server/model/prompts/describe.go
index 1d263390..daef04b9 100644
--- a/app/server/model/prompts/describe.go
+++ b/app/server/model/prompts/describe.go
@@ -1,9 +1,6 @@
package prompts
import (
- "fmt"
-
- "github.com/plandex/plandex/shared"
"github.com/sashabaranov/go-openai"
"github.com/sashabaranov/go-openai/jsonschema"
)
@@ -23,24 +20,4 @@ var DescribePlanFn = openai.FunctionDefinition{
},
}
-var SysDescribeNumTokens int
-
const SysPendingResults = "You are an AI commit message summarizer. You take a list of descriptions of pending changes and turn them into a succinct one-line summary of all the pending changes that makes for a good commit message title. Output ONLY this one-line title and nothing else."
-
-var SysPendingResultsNumTokens int
-
-func init() {
- var err error
- SysDescribeNumTokens, err = shared.GetNumTokens(SysDescribe)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting num tokens for describe plan prompt: %v\n", err))
- }
-
- SysPendingResultsNumTokens, err = shared.GetNumTokens(SysPendingResults)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting num tokens for pending results prompt: %v\n", err))
- }
-
-}
diff --git a/app/server/model/prompts/init.go b/app/server/model/prompts/init.go
deleted file mode 100644
index fa86e6f3..00000000
--- a/app/server/model/prompts/init.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package prompts
-
-import (
- "fmt"
-
- "github.com/plandex/plandex/shared"
-)
-
-func init() {
- var err error
-
- AutoContextPreambleNumTokens, err = shared.GetNumTokens(AutoContextPreamble)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for context preamble: %v", err))
- }
-
- SysPlanningBasicTokens, err = shared.GetNumTokens(SysPlanningBasic)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for sys msg: %v", err))
- }
-
- SysPlanningAutoContextTokens, err = shared.GetNumTokens(SysPlanningAutoContext)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for sys msg: %v", err))
- }
-
- PlanningPromptWrapperTokens, err = shared.GetNumTokens(fmt.Sprintf(planningPromptWrapperFormatStr, "", "", "", ""))
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for prompt wrapper: %v", err))
- }
-
- ImplementationPromptWrapperTokens, err = shared.GetNumTokens(fmt.Sprintf(implementationPromptWrapperFormatStr, "", "", "", ""))
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for prompt wrapper: %v", err))
- }
-
- // log.Printf("ImplementationPromptWrapperTokens: %d\n", ImplementationPromptWrapperTokens)
-
- // log.Println("implementationPromptWrapperFormatStr:\n", implementationPromptWrapperFormatStr)
-
- AutoContinuePromptTokens, err = shared.GetNumTokens(AutoContinuePrompt)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for auto continue prompt: %v", err))
- }
-
- DebugPromptTokens, err = shared.GetNumTokens(DebugPrompt)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for debug prompt: %v", err))
- }
-
- ChatOnlyPromptTokens, err = shared.GetNumTokens(ChatOnlyPrompt)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for chat only prompt: %v", err))
- }
-
- ApplyScriptPlanningPromptNumTokens, err = shared.GetNumTokens(ApplyScriptPlanningPrompt)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for apply script planning prompt: %v", err))
- }
-
- ApplyScriptImplementationPromptNumTokens, err = shared.GetNumTokens(ApplyScriptImplementationPrompt)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for apply script prompt: %v", err))
- }
-
- ApplyScriptSummaryNumTokens, err = shared.GetNumTokens(ApplyScriptPromptSummary)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for apply script prompt summary: %v", err))
- }
-
- NoApplyScriptPromptNumTokens, err = shared.GetNumTokens(NoApplyScriptPrompt)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting number of tokens for no execute script prompt: %v", err))
- }
-}
diff --git a/app/server/model/prompts/planning.go b/app/server/model/prompts/planning.go
index c2001abe..06c13b1a 100644
--- a/app/server/model/prompts/planning.go
+++ b/app/server/model/prompts/planning.go
@@ -7,12 +7,10 @@ type createPromptParams struct {
var SysPlanningBasic = GetPlanningPrompt(createPromptParams{
autoContext: false,
})
-var SysPlanningBasicTokens int
var SysPlanningAutoContext = GetPlanningPrompt(createPromptParams{
autoContext: true,
})
-var SysPlanningAutoContextTokens int
func GetPlanningPrompt(params createPromptParams) string {
prompt := Identity + ` A plan is a set of files with an attached context.
@@ -73,7 +71,9 @@ func GetPlanningPrompt(params createPromptParams) string {
- After you have broken a task up in to multiple subtasks and output a '### Tasks' section, you *ABSOLUTELY MUST* output a <EndPlandexTasks/> tag and then end the response. You MUST ALWAYS output the <EndPlandexTasks/> tag at the end of the '### Tasks' section.
- - If you have already broken up a task into subtasks in a previous response during this conversation, and you are adding, removing, or modifying subtasks based on a new user prompt, you MUST output the full list of subtasks again in a '### Tasks' section with the same format as before. You ABSOLUTELY MUST NEVER output only a partial list of subtasks. Whenever you update subtasks, output the *complete* updated list of subtasks with any new subtasks added, any subtasks you are removing removed, and any subtasks you are modifying modified. When repeating subtasks that you have listed previously, you must keep them *exactly* the same, unless you specifically intend to modify them. No not make minor changes or add additional text to the subtask. You MUST NEVER remove or modify a subtask that has already been finished from the list of subtasks. DO NOT include the 'Done:' line in subtasks in this list. If an existing subtask has a 'Uses: ' line, you MUST include it.
+ ` + ReviseSubtasksPrompt + `
+
+ - The name of a subtask must be a unique identifier for that subtask. Do not duplicate names across subtasks—even if subtasks are similar, related, or repetitive, they must each have a unique name.
- Be thorough and exhaustive in your list of subtasks. Ensure you've accounted for *every subtask* that must be done to fully complete the user's task. Ensure that you list *every* file that needs to be created or updated. Be specific and detailed in your list of subtasks. Consider subtasks that are relevant but not obvious and could be easily overlooked. Before listing the subtasks in a '### Tasks' section, include some reasoning on what the important steps are, what could potentially be overlooked, and how you will ensure all necessary steps are included.
@@ -117,6 +117,10 @@ If a plan is in progress and the user asks you a question, don't respond by cont
prompt += SharedPlanningImplementationPrompt
prompt += `
+IMPORTANT: During this planning phase, you must NOT implement any code or create any code blocks. Your only task is to break down the work into subtasks. Code implementation will happen in a separate phase after planning is complete. The planning phase is ONLY for breaking the work into subtasks.
+
+Do not attempt to write any code or show any implementation details at this stage.
+
[END OF YOUR INSTRUCTIONS]
`
@@ -195,3 +199,76 @@ Always work from the LATEST state of the user-provided context. If the user has
Similarly, if you have made updates to any files, you MUST always work from the *latest version* of the files when continuing the plan.
`
+
+const FollowUpPlanClassifierPrompt = `
+Since this prompt is a follow up to a plan that has already been started, you must assess the following:
+
+- Whether the prompt is:
+ A. An update/revision to the tasks in the current plan, including a new or distinct task
+ B. A conversation prompt like a question or comment that does not indicate a an update to the plan or a new task
+
+- If the prompt is A, you must then assess whether the prompt is:
+ A1. A small/minor update to or revision of the current plan
+ A2. A significant update to or revision of the current plan
+ A3. A new task that is distinct from the current plan
+
+ A task is likely to be:
+
+ - A1 (small update) if it involves:
+ * Minor changes to existing functionality
+ * Changes contained within files already in context
+ * Simple additions or modifications
+ * Refinements to existing subtasks
+
+ - A2 (significant update) if it involves:
+ * Major changes to existing functionality
+ * Changes spanning multiple components
+ * New features that build on current work
+ * Substantial restructuring of existing subtasks
+
+ - A3 (new task) if it:
+ * Addresses a different concern/feature
+ * Has little overlap with current work
+ * Would make more sense as a separate plan
+ * Requires a fresh context evaluation
+
+- If the prompt is A2 or A3, either a significant update to or revision of the current plan, or a new task that is distinct from the current plan, you must explicitly state either:
+ - For A2: "This is a significant update to the plan. I'll clear all context without pending changes, then decide what context I need to move forward." - then output <PlandexDecideContext/> and end the response.
+ - For A3: "This is a new task that is distinct from the plan. I'll clear all context without pending changes, then decide what context I need to move forward." - then output <PlandexDecideContext/> and end the response.
+ - You MUST ouput one of the above statements *exactly* as shown, and you MUST output a <PlandexDecideContext/> tag immediately after the statement and end the response.
+
+- If the prompt is A1, a small/minor update to or revision of the plan, you must explicitly state:
+ - "This is a small update to the plan."
+ - Then you must move on to the [Context Assessment Instructions] below.
+
+- If the prompt is B, you must move on to the [Context Assessment Instructions] below.
+
+[Context Assessment Instructions]
+
+You must now assess whether you have sufficient context loaded to either continue with the plan and make the small/minor update to the plan that the user has requested (A1), or respond effectively in chat form to the user's prompt (B).
+
+For chat responses (B), you have "sufficient context" if you have enough information to provide accurate, informed answers about the specific code or concepts the user is asking about.
+
+For small updates (A1), you have "sufficient context" if you have:
+* All files that will be modified
+* Any dependent files needed to understand the changes
+* Any similar implementations that would be helpful as reference
+
+- If you have sufficient context loaded, you must explicitly state "I have the context I need to continue." and then move on to the [YOUR INSTRUCTIONS] section below.
+
+- If you do not have sufficient context loaded, you must explicitly state "I need more context to continue." - then output <PlandexDecideContext/> and end the response.
+
+[Handling Multi-part Prompts]
+
+If the user's prompt contains multiple parts (e.g. both questions and updates):
+1. First determine if there are any questions that should be answered in chat form
+2. Answer those questions first
+3. Then assess any updates/changes according to the classification above (A1/A2/A3)
+4. Only after answering questions should you output any of the classification statements or tags
+
+Before beginning on the assessment above and outputting one of the listed statements, you can output a few sentences responding to the user's prompt and/or reasoning about the assessment.
+` + FollowUpRequiredPrompt
+
+const ReviseSubtasksPrompt = `
+- If you have already broken up a task into subtasks in a previous response during this conversation, and you are adding, removing, or modifying subtasks based on a new user prompt, you MUST output the full list of subtasks again in a '### Tasks' section with the same format as before. You ABSOLUTELY MUST NEVER output only a partial list of subtasks. Whenever you update subtasks, output the *complete* updated list of *all* unfinished subtasks with any new subtasks added, any subtasks you are removing removed, and any subtasks you are modifying modified. You don't need to reproduce *finished* subtasks, but any unfinished subtasks that you have listed previously *must without exception* be included in the list. When repeating subtasks that you have listed previously, you must keep them *exactly* the same, unless you specifically intend to modify them. No not make minor changes or add additional text to the subtask. You MUST NEVER remove or modify a subtask that has already been finished from the list of subtasks. DO NOT include the 'Done:' line in subtasks in this list. If an existing subtask has a 'Uses: ' line, you MUST include it.
+`
diff --git a/app/server/model/prompts/shared.go b/app/server/model/prompts/shared.go
index aff37859..12bb9a65 100644
--- a/app/server/model/prompts/shared.go
+++ b/app/server/model/prompts/shared.go
@@ -1,24 +1,3 @@
package prompts
-import (
- "fmt"
-
- "github.com/plandex/plandex/shared"
-)
-
const Identity = "You are Plandex, an AI programming and system administration assistant. You and the programmer collaborate to create a 'plan' for the task at hand."
-
-var IdentityNumTokens int
-
-func init() {
- var err error
- IdentityNumTokens, err = shared.GetNumTokens(Identity)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting num tokens for identity prompt: %v\n", err))
- }
-}
-
-// these account for control tokens like %system%, %user%, %assistant%, etc. and add more tokens to the request
-const ExtraTokensPerRequest = 3
-const ExtraTokensPerMessage = 4
diff --git a/app/server/model/prompts/summary.go b/app/server/model/prompts/summary.go
index 4abe4e09..1198b36b 100644
--- a/app/server/model/prompts/summary.go
+++ b/app/server/model/prompts/summary.go
@@ -1,11 +1,5 @@
package prompts
-import (
- "fmt"
-
- "github.com/plandex/plandex/shared"
-)
-
const PlanSummary = `
You are an AI summarizer that summarizes the conversation so far. The conversation so far is a plan to complete one or more programming tasks for a user. This conversation may begin with an existing summary of the plan.
@@ -31,14 +25,3 @@ Do not include any heading or title for the summary. Just start with the summary
Output only the summary of the current state of the plan and nothing else.
`
-
-var PlanSummaryNumTokens int
-
-func init() {
- var err error
- PlanSummaryNumTokens, err = shared.GetNumTokens(PlanSummary)
-
- if err != nil {
- panic(fmt.Sprintf("Error getting num tokens for plan summary prompt: %v\n", err))
- }
-}
diff --git a/app/server/model/prompts/user_prompt.go b/app/server/model/prompts/user_prompt.go
index 0969f1e6..197205f2 100644
--- a/app/server/model/prompts/user_prompt.go
+++ b/app/server/model/prompts/user_prompt.go
@@ -5,7 +5,7 @@ import (
"time"
)
-const sharedPromptWrapperFormatStr = "# The user's latest prompt:\n```\n%s\n```\n\n" + `Please respond according to the 'Your instructions' section above.
+const SharedPromptWrapperFormatStr = "# The user's latest prompt:\n```\n%s\n```\n\n" + `Please respond according to the 'Your instructions' section above.
Do not ask the user to do anything that you can do yourself. Do not say a task is too large or complex for you to complete--do your best to break down the task and complete it even if it's very large or complex.
@@ -21,10 +21,12 @@ User's operating system details:
---
`
-const planningPromptWrapperFormatStr = sharedPromptWrapperFormatStr + `
+const PlanningPromptWrapperFormatStr = SharedPromptWrapperFormatStr + `
Do NOT include tests or documentation in the subtasks unless the user has specifically asked for them. Do not include extra code or features beyond what the user has asked for. Focus on the user's request and implement only what is necessary to fulfill it.
+` + ReviseSubtasksPrompt + `
+
` + CombineSubtasksPrompt + `
At the end of the '### Tasks' section, you ABSOLUTELY MUST ALWAYS include a <EndPlandexTasks/> tag, then end the response.
@@ -38,11 +40,13 @@ Example:
2. Write a basic test for the 'main' function
<EndPlandexTasks/>
-`
-var PlanningPromptWrapperTokens int
+IMPORTANT: During this planning phase, you must NOT implement any code or create any code blocks. Your only task is to break down the work into subtasks. Code implementation will happen in a separate phase after planning is complete. The planning phase is ONLY for breaking the work into subtasks.
+
+Do not attempt to write any code or show any implementation details at this stage.
+`
-const implementationPromptWrapperFormatStr = sharedPromptWrapperFormatStr + `
+const ImplementationPromptWrapperFormatStr = SharedPromptWrapperFormatStr + `
If you're making a plan, remember to label code blocks with the file path *exactly* as described in point 2, and do not use any other formatting for file paths. **Do not include explanations or any other text apart from the file path in code block labels.**
@@ -98,19 +102,42 @@ If you break up a task into subtasks, only include subtasks that can be implemen
` + FileOpsImplementationPromptSummary
-var ImplementationPromptWrapperTokens int
+const FollowUpRequiredPrompt = `
+[CLASSIFICATION REQUIRED]
+
+YOU MUST COMPLETE THE CLASSIFICATION STEP BEFORE PROCEEDING TO ANY OTHER STEPS.
+
+DO NOT proceed to planning or implementation without first:
+1. Classifying the prompt according to the rules below
+2. Outputting the required classification statement
+3. Assessing context needs
+4. Outputting the required context statement
-func GetWrappedPrompt(prompt, osDetails, applyScriptSummary string, isPlanningStage bool) string {
+You MUST output one of these exact statements before proceeding:
+- "This is a small update to the plan."
+- "This is a significant update to the plan. I'll clear all context without pending changes, then decide what context I need to move forward."
+- "This is a new task that is distinct from the plan. I'll clear all context without pending changes, then decide what context I need to move forward."
+
+AND then one of these for small updates (A1) or chat responses (B):
+- "I have the context I need to continue."
+- "I need more context to continue."
+`
+
+func GetWrappedPrompt(prompt, osDetails, applyScriptSummary string, isPlanningStage, isFollowUp bool) string {
var promptWrapperFormatStr string
if isPlanningStage {
- promptWrapperFormatStr = planningPromptWrapperFormatStr
+ promptWrapperFormatStr = PlanningPromptWrapperFormatStr
} else {
- promptWrapperFormatStr = implementationPromptWrapperFormatStr
+ promptWrapperFormatStr = ImplementationPromptWrapperFormatStr
}
// If we're in the planning stage, we don't need to include the apply script summary
if isPlanningStage {
applyScriptSummary = ""
+
+ if isFollowUp {
+ promptWrapperFormatStr += "\n\n" + FollowUpRequiredPrompt
+ }
}
ts := time.Now().Format(time.RFC3339)
@@ -135,8 +162,6 @@ If you break up a task into subtasks, only include subtasks that can be implemen
Do NOT include tests or documentation in the subtasks unless the user has specifically asked for them. Do not include extra code or features beyond what the user has asked for. Focus on the user's request and implement only what is necessary to fulfill it.`
-var AutoContinuePromptTokens int
-
const SkippedPathsPrompt = "\n\nSome files have been skipped by the user and *must not* be generated. The user will handle any updates to these files themselves. Skip any parts of the plan that require generating these files. You *must not* generate a file block for any of these files.\nSkipped files:\n"
const CombineSubtasksPrompt = `
diff --git a/app/server/model/summarize.go b/app/server/model/summarize.go
index 62fc2381..f8fb5423 100644
--- a/app/server/model/summarize.go
+++ b/app/server/model/summarize.go
@@ -35,8 +35,6 @@ func PlanSummary(client *openai.Client, config shared.ModelRoleConfig, params Pl
},
}
- numTokens := params.ConversationNumTokens + prompts.IdentityNumTokens
-
for _, message := range params.Conversation {
messages = append(messages, *message)
}
@@ -46,7 +44,7 @@ func PlanSummary(client *openai.Client, config shared.ModelRoleConfig, params Pl
Content: prompts.PlanSummary,
})
- numTokens += prompts.PlanSummaryNumTokens
+ numTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: params.Auth,
@@ -94,11 +92,7 @@ func PlanSummary(client *openai.Client, config shared.ModelRoleConfig, params Pl
outputTokens = resp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(content)
-
- if err != nil {
- return nil, err
- }
+ outputTokens = shared.GetNumTokensEstimate(content)
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
diff --git a/app/server/types/active_plan_pending_builds.go b/app/server/types/active_plan_pending_builds.go
index 46b44fe7..fced3df6 100644
--- a/app/server/types/active_plan_pending_builds.go
+++ b/app/server/types/active_plan_pending_builds.go
@@ -66,12 +66,7 @@ func (ap *ActivePlan) PendingBuildsByPath(orgId, userId string, convoMessagesArg
activeBuildsByPath[op.Path] = []*ActiveBuild{}
}
- numTokens, err := shared.GetNumTokens(op.Content)
-
- if err != nil {
- log.Printf("Error getting num tokens for file content: %v\n", err)
- return nil, fmt.Errorf("error getting num tokens for file content: %v", err)
- }
+ numTokens := shared.GetNumTokensEstimate(op.Content)
activeBuildsByPath[op.Path] = append(activeBuildsByPath[op.Path], &ActiveBuild{
ReplyId: desc.ConvoMessageId,
diff --git a/app/server/types/reply_test_examples/10.md b/app/server/types/reply_test_examples/10.md
index b1abcd15..b18c1ccf 100644
--- a/app/server/types/reply_test_examples/10.md
+++ b/app/server/types/reply_test_examples/10.md
@@ -31,13 +31,13 @@ var SysPendingResultsNumTokens int
func init() {
var err error
- SysDescribeNumTokens, err = shared.GetNumTokens(SysDescribe)
+ SysDescribeNumTokens, err = shared.GetNumTokensEstimate(SysDescribe)
if err != nil {
panic(fmt.Sprintf("Error getting num tokens for describe plan prompt: %v\n", err))
}
- SysPendingResultsNumTokens, err = shared.GetNumTokens(SysPendingResults)
+ SysPendingResultsNumTokens, err = shared.GetNumTokensEstimate(SysPendingResults)
if err != nil {
panic(fmt.Sprintf("Error getting num tokens for pending results prompt: %v\n", err))
@@ -131,7 +131,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
outputTokens = descResp.Usage.CompletionTokens
} else {
inputTokens = numTokens
- outputTokens, err = shared.GetNumTokens(content)
+ outputTokens, err = shared.GetNumTokensEstimate(content)
if err != nil {
return nil, fmt.Errorf("error getting num tokens for content: %v", err)
diff --git a/app/shared/tokens.go b/app/shared/tokens.go
index 24799b94..dfa4b28d 100644
--- a/app/shared/tokens.go
+++ b/app/shared/tokens.go
@@ -4,13 +4,44 @@ import (
"fmt"
"github.com/pkoukk/tiktoken-go"
+ "github.com/sashabaranov/go-openai"
)
-func GetNumTokens(text string) (int, error) {
- tkm, err := tiktoken.EncodingForModel("gpt-4")
+var tkm *tiktoken.Tiktoken
+
+func init() {
+ var err error
+ tkm, err = tiktoken.EncodingForModel("gpt-4o")
if err != nil {
- err = fmt.Errorf("error getting encoding for model: %v", err)
- return 0, err
+ panic(fmt.Sprintf("error getting encoding for model: %v", err))
+ }
+}
+
+func GetNumTokensEstimate(text string) int {
+ return len(tkm.Encode(text, nil, nil))
+}
+
+const (
+ // Per OpenAI's documentation:
+ // Every message follows this format: {"role": "role_name", "content": "content"}
+ // which has a 4-token overhead per message
+ TokensPerMessage = 4
+
+ // System, user, or assistant - each role name costs 1 token
+ TokensPerName = 1
+
+ // Tokens per request
+ TokensPerRequest = 3
+)
+
+func GetMessagesTokenEstimate(messages ...openai.ChatCompletionMessage) int {
+ tokens := 0
+
+ for _, msg := range messages {
+ tokens += TokensPerMessage
+ tokens += TokensPerName
+ tokens += GetNumTokensEstimate(msg.Content)
}
- return len(tkm.Encode(text, nil, nil)), nil
+
+ return tokens
}