Skip to content

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

many fixes and prompt improvements, upgrade to 'Tools' api for OpenAI, move to latest OpenAI models by default. getting fairly consistent results now

Dane Schneider38e084b35d62
diff --git a/app/cli/changes_tui/main_viewport.go b/app/cli/changes_tui/main_viewport.go
index 7a19eef8..e4490d7b 100644
--- a/app/cli/changes_tui/main_viewport.go
+++ b/app/cli/changes_tui/main_viewport.go
@@ -113,7 +113,10 @@ func (m changesUIModel) renderMainViewFooter() string {
}
sidebarWidth := lipgloss.Width(m.renderSidebar())
- style := lipgloss.NewStyle().Width(m.width - sidebarWidth).Inherit(topBorderStyle).Foreground(lipgloss.Color(helpTextColor))
+ style := lipgloss.NewStyle().
+ Width(m.width - sidebarWidth).
+ Inherit(topBorderStyle).
+ Foreground(lipgloss.Color(helpTextColor))
footer := ` (r)eject change • (c)opy to clipboard`
return style.Render(footer)
}
@@ -132,7 +135,7 @@ func (m changesUIModel) renderScrollFooter() string {
var footer string
if m.selectedNewFile() || m.selectedFullFile() {
- footer = `(j/k) scroll • (d/u) page • (g/G) start/end`
+ footer = ` (j/k) scroll • (d/u) page • (g/G) start/end`
} else {
footer = ` (j/k) scroll`
if m.oldScrollable() && m.newScrollable() {
@@ -140,7 +143,10 @@ func (m changesUIModel) renderScrollFooter() string {
}
}
- style := lipgloss.NewStyle().Width(width).Inherit(topBorderStyle).Foreground(lipgloss.Color(helpTextColor))
+ style := lipgloss.NewStyle().
+ Width(width).
+ Inherit(topBorderStyle).
+ Foreground(lipgloss.Color(helpTextColor))
return style.Render(footer)
}
diff --git a/app/cli/changes_tui/path_tabs.go b/app/cli/changes_tui/path_tabs.go
index 7d0d457d..ef4dde64 100644
--- a/app/cli/changes_tui/path_tabs.go
+++ b/app/cli/changes_tui/path_tabs.go
@@ -22,8 +22,8 @@ func (m changesUIModel) renderPathTabs() string {
for i, path := range paths {
selected := i == m.selectedFileIndex
- if len(path) > 20 {
- path = path[:10] + "⋯" + path[len(path)-10:]
+ if len(path) > 40 {
+ path = path[:20] + "⋯" + path[len(path)-20:]
}
tab := " 📄 " + path + " "
diff --git a/app/cli/cmd/checkout.go b/app/cli/cmd/checkout.go
index 78a51597..b5fb0874 100644
--- a/app/cli/cmd/checkout.go
+++ b/app/cli/cmd/checkout.go
@@ -55,39 +55,14 @@ func checkout(cmd *cobra.Command, args []string) {
return
}
- if nameOrIdx == "" {
- opts := make([]string, len(branches))
- for i, branch := range branches {
- opts[i] = branch.Name
- }
- opts = append(opts, OptCreateNewBranch)
-
- selected, err := term.SelectFromList("Select a branch", opts)
-
- if err != nil {
- fmt.Println("Error selecting branch:", err)
- return
- }
-
- if selected == OptCreateNewBranch {
- branchName, err = term.GetUserStringInput("Branch name")
- if err != nil {
- fmt.Println("Error getting branch name:", err)
- return
- }
- willCreate = true
- } else {
- branchName = selected
- }
- } else {
- // see if it's an index
+ if nameOrIdx != "" {
idx, err := strconv.Atoi(nameOrIdx)
if err == nil {
if idx > 0 && idx <= len(branches) {
branchName = branches[idx-1].Name
} else {
- fmt.Fprintln(os.Stderr, "Error: index out of range")
+ fmt.Fprintf(os.Stderr, "🚨 Branch %d not found\n", idx)
os.Exit(1)
}
} else {
@@ -98,24 +73,9 @@ func checkout(cmd *cobra.Command, args []string) {
}
}
}
- }
-
- if branchName == "" {
- fmt.Fprintln(os.Stderr, "🚨 Branch not found")
- os.Exit(1)
- }
-
- if !willCreate {
- found := false
- for _, branch := range branches {
- if branch.Name == branchName {
- found = true
- break
- }
- }
- if !found {
- fmt.Printf("🤷‍♂️ Branch '%s' not found\n", branchName)
+ if branchName == "" {
+ fmt.Printf("🤷‍♂️ Branch %s not found\n", color.New(color.Bold, color.FgHiCyan).Sprint(nameOrIdx))
res, err := term.ConfirmYesNo("Create it now?")
if err != nil {
@@ -123,11 +83,44 @@ func checkout(cmd *cobra.Command, args []string) {
}
if res {
+ branchName = nameOrIdx
willCreate = true
} else {
return
}
}
+
+ }
+
+ if nameOrIdx == "" {
+ opts := make([]string, len(branches))
+ for i, branch := range branches {
+ opts[i] = branch.Name
+ }
+ opts = append(opts, OptCreateNewBranch)
+
+ selected, err := term.SelectFromList("Select a branch", opts)
+
+ if err != nil {
+ fmt.Println("Error selecting branch:", err)
+ return
+ }
+
+ if selected == OptCreateNewBranch {
+ branchName, err = term.GetUserStringInput("Branch name")
+ if err != nil {
+ fmt.Println("Error getting branch name:", err)
+ return
+ }
+ willCreate = true
+ } else {
+ branchName = selected
+ }
+ }
+
+ if branchName == "" {
+ fmt.Fprintln(os.Stderr, "🚨 Branch not found")
+ os.Exit(1)
}
if willCreate {
@@ -141,7 +134,7 @@ func checkout(cmd *cobra.Command, args []string) {
}
term.StopSpinner()
- fmt.Printf("✅ Created branch %s\n", color.New(color.Bold, color.FgHiGreen).Sprint(branchName))
+ // fmt.Printf("✅ Created branch %s\n", color.New(color.Bold, color.FgHiGreen).Sprint(branchName))
}
err := lib.WriteCurrentBranch(branchName)
diff --git a/app/cli/stream/stream.go b/app/cli/stream/stream.go
index 6461659c..98046e7e 100644
--- a/app/cli/stream/stream.go
+++ b/app/cli/stream/stream.go
@@ -4,6 +4,8 @@ import (
"log"
streamtui "plandex/stream_tui"
"plandex/types"
+
+ "github.com/plandex/plandex/shared"
)
var OnStreamPlan types.OnStreamPlan = func(params types.OnStreamPlanParams) {
@@ -12,6 +14,11 @@ var OnStreamPlan types.OnStreamPlan = func(params types.OnStreamPlanParams) {
return
}
+ if params.Msg.Type == shared.StreamMessageStart {
+ log.Println("Stream started")
+ return
+ }
+
// log.Println("Stream message:")
// log.Println(spew.Sdump(*params.Msg))
diff --git a/app/cli/stream_tui/run.go b/app/cli/stream_tui/run.go
index 0fb06d40..df79d9e1 100644
--- a/app/cli/stream_tui/run.go
+++ b/app/cli/stream_tui/run.go
@@ -38,7 +38,10 @@ func StartStreamUI(prompt string, buildOnly bool) error {
if !mod.buildOnly {
fmt.Println(mod.mainDisplay)
}
- fmt.Println(mod.renderStaticBuild())
+
+ if len(mod.finishedByPath) > 0 || len(mod.tokensByPath) > 0 {
+ fmt.Println(mod.renderStaticBuild())
+ }
if mod.err != nil {
fmt.Println()
@@ -53,6 +56,7 @@ func StartStreamUI(prompt string, buildOnly bool) error {
}
if mod.stopped {
+ fmt.Println()
color.New(color.BgBlack, color.Bold, color.FgHiRed).Print(" 🛑 stopped early by user ")
fmt.Println()
}
diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.go
index 212c75c6..a51d45c0 100644
--- a/app/cli/stream_tui/update.go
+++ b/app/cli/stream_tui/update.go
@@ -81,7 +81,7 @@ func (m streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case bubbleKey.Matches(msg, m.keymap.end) && !m.promptingMissingFile:
m.scrollEnd()
case m.promptingMissingFile && bubbleKey.Matches(msg, m.keymap.enter):
- m.selectedMissingFileOpt()
+ return m.selectedMissingFileOpt()
default:
m.resolveEscapeSequence(msg.String())
@@ -119,8 +119,8 @@ func (m *streamUIModel) updateReplyDisplay() {
if m.reply != "" {
replyMd, _ := term.GetMarkdown(m.reply)
- s += "\n\n" + color.New(color.BgBlue, color.Bold, color.FgHiWhite).Sprintf(" 🤖 Plandex reply 👇 ")
- s += "\n\n" + strings.TrimSpace(replyMd) + "\n"
+ s += "\n" + color.New(color.BgBlue, color.Bold, color.FgHiWhite).Sprintf(" 🤖 Plandex reply 👇 ")
+ s += "\n\n" + strings.TrimSpace(replyMd)
} else {
s += "\n"
}
@@ -367,11 +367,11 @@ func (m *streamUIModel) down() {
}
-func (m *streamUIModel) selectedMissingFileOpt() {
+func (m *streamUIModel) selectedMissingFileOpt() (tea.Model, tea.Cmd) {
choice := promptChoices[m.missingFileSelectedIdx]
if choice == "" {
- return
+ return m, nil
}
apiErr := api.Client.RespondMissingFile(lib.CurrentPlanId, lib.CurrentBranch, shared.RespondMissingFileRequest{
@@ -383,7 +383,7 @@ func (m *streamUIModel) selectedMissingFileOpt() {
if apiErr != nil {
log.Println("missing file prompt api error:", apiErr)
m.apiErr = apiErr
- return
+ return m, nil
}
if choice == shared.RespondMissingFileChoiceSkip {
@@ -399,4 +399,6 @@ func (m *streamUIModel) selectedMissingFileOpt() {
m.missingFileTokens = 0
m.promptedMissingFile = true
m.processing = true
+
+ return m, m.spinner.Tick
}
diff --git a/app/cli/stream_tui/view.go b/app/cli/stream_tui/view.go
index 69e5fef8..cd72e597 100644
--- a/app/cli/stream_tui/view.go
+++ b/app/cli/stream_tui/view.go
@@ -99,6 +99,7 @@ func (m streamUIModel) doRenderBuild(outputStatic bool) string {
var rows [][]string
lineWidth := 0
lineNum := 0
+ rowIdx := 0
for _, filePath := range filePaths {
tokens := m.tokensByPath[filePath]
@@ -111,13 +112,23 @@ func (m streamUIModel) doRenderBuild(outputStatic bool) string {
block += fmt.Sprintf(" %d 🪙", tokens)
}
- blockWidth := lipgloss.Width(block)
+ maybePrefix := ""
+ if rowIdx > 0 {
+ maybePrefix = " | "
+ }
+
+ maybeBlockWidth := lipgloss.Width(maybePrefix + block)
- if lineWidth+blockWidth > m.width {
+ if lineWidth+maybeBlockWidth > m.width {
lineWidth = 0
lineNum++
+ rowIdx = 0
+ } else {
+ block = maybePrefix + block
}
+ defBlockWidth := lipgloss.Width(block)
+
if len(rows) <= lineNum {
rows = append(rows, []string{})
}
@@ -126,14 +137,15 @@ func (m streamUIModel) doRenderBuild(outputStatic bool) string {
row = append(row, block)
rows[lineNum] = row
- lineWidth += blockWidth
+ lineWidth += defBlockWidth
+ rowIdx++
}
resRows := make([]string, len(rows)+1)
resRows[0] = head
for i, row := range rows {
- resRows[i+1] = strings.Join(row, " | ")
+ resRows[i+1] = strings.Join(row, "")
}
return style.Render(strings.Join(resRows, "\n"))
diff --git a/app/cli/tell/tell.go b/app/cli/tell/tell.go
index 063c8f77..f54e3757 100644
--- a/app/cli/tell/tell.go
+++ b/app/cli/tell/tell.go
@@ -23,8 +23,6 @@ func TellPlan(prompt string, tellBg, tellStop, tellNoBuild bool) {
return
}
- log.Println("tellNoBuild:", tellNoBuild)
-
var fn func() bool
fn = func() bool {
@@ -35,6 +33,8 @@ func TellPlan(prompt string, tellBg, tellStop, tellNoBuild bool) {
buildMode = shared.BuildModeAuto
}
+ term.StartSpinner("💬 Sending prompt...")
+
apiErr := api.Client.TellPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.TellPlanRequest{
Prompt: prompt,
ConnectStream: !tellBg,
@@ -43,6 +43,9 @@ func TellPlan(prompt string, tellBg, tellStop, tellNoBuild bool) {
BuildMode: buildMode,
ApiKey: os.Getenv("OPENAI_API_KEY"),
}, stream.OnStreamPlan)
+
+ term.StopSpinner()
+
if apiErr != nil {
if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
streamtui.Quit()
diff --git a/app/server/db/context_helpers.go b/app/server/db/context_helpers.go
index 60fd61ad..18e3a104 100644
--- a/app/server/db/context_helpers.go
+++ b/app/server/db/context_helpers.go
@@ -136,6 +136,8 @@ func StoreContext(context *Context) error {
metaFilename := context.Id + ".meta"
metaPath := filepath.Join(contextDir, metaFilename)
+ originalBody := context.Body
+
bodyFilename := context.Id + ".body"
bodyPath := filepath.Join(contextDir, bodyFilename)
body := []byte(context.Body)
@@ -157,5 +159,7 @@ func StoreContext(context *Context) error {
return fmt.Errorf("failed to write context meta to file %s: %v", metaPath, err)
}
+ context.Body = originalBody
+
return nil
}
diff --git a/app/server/go.mod b/app/server/go.mod
index 799471fb..a2f128f1 100644
--- a/app/server/go.mod
+++ b/app/server/go.mod
@@ -4,11 +4,11 @@ go 1.21.3
require (
github.com/davecgh/go-spew v1.1.1
- github.com/google/uuid v1.4.0
+ github.com/google/uuid v1.6.0
github.com/gorilla/mux v1.8.1
github.com/pkg/errors v0.9.1
github.com/plandex/plandex/shared v0.0.0-00010101000000-000000000000
- github.com/sashabaranov/go-openai v1.19.2
+ github.com/sashabaranov/go-openai v1.19.3
)
require (
diff --git a/app/server/go.sum b/app/server/go.sum
index c080b60a..eb9b7d80 100644
--- a/app/server/go.sum
+++ b/app/server/go.sum
@@ -35,8 +35,8 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-migrate/migrate/v4 v4.16.2 h1:8coYbMKUyInrFk1lfGfRovTLAW7PhWp8qQDT2iKfuoA=
github.com/golang-migrate/migrate/v4 v4.16.2/go.mod h1:pfcJX4nPHaVdc5nmdCikFBWtm+UBpiZjRNNsyBbp0/o=
-github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
-github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -81,8 +81,8 @@ github.com/pkoukk/tiktoken-go v0.1.6 h1:JF0TlJzhTbrI30wCvFuiw6FzP2+/bR+FIxUdgEAc
github.com/pkoukk/tiktoken-go v0.1.6/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/sashabaranov/go-openai v1.19.2 h1:+dkuCADSnwXV02YVJkdphY8XD9AyHLUWwk6V7LB6EL8=
-github.com/sashabaranov/go-openai v1.19.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
+github.com/sashabaranov/go-openai v1.19.3 h1:xJvkU8Tye6MOKLaoqjh7qXYwKiEYGtlmp06cb8179yo=
+github.com/sashabaranov/go-openai v1.19.3/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
github.com/sirupsen/logrus v1.9.2 h1:oxx1eChJGI6Uks2ZC4W1zpLlVgqB8ner4EuQwV4Ik1Y=
github.com/sirupsen/logrus v1.9.2/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
diff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.go
index cae7618e..b0b7ec73 100644
--- a/app/server/handlers/plans_exec.go
+++ b/app/server/handlers/plans_exec.go
@@ -101,6 +101,8 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
modelPlan.UnsubscribePlan(planId, branch, subscriptionId)
})
}
+
+ log.Println("Successfully processed request for TellPlanHandler")
}
func BuildPlanHandler(w http.ResponseWriter, r *http.Request) {
@@ -289,6 +291,9 @@ func RespondMissingFileHandler(w http.ResponseWriter, r *http.Request) {
}
dbContext := dbContexts[0]
+
+ log.Println("loaded missing file:", dbContext.FilePath)
+
modelPlan.UpdateActivePlan(planId, branch, func(activePlan *types.ActivePlan) {
activePlan.Contexts = append(activePlan.Contexts, dbContext)
activePlan.ContextsByPath[dbContext.FilePath] = dbContext
diff --git a/app/server/handlers/stream_helper.go b/app/server/handlers/stream_helper.go
index 2de24f56..b3a23d24 100644
--- a/app/server/handlers/stream_helper.go
+++ b/app/server/handlers/stream_helper.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "encoding/json"
"log"
"net/http"
"plandex-server/types"
@@ -19,6 +20,22 @@ func startResponseStream(w http.ResponseWriter, ch chan string, active *types.Ac
closeFn()
}()
+ // send initial message to client
+ msg := shared.StreamMessage{
+ Type: shared.StreamMessageStart,
+ }
+ bytes, err := json.Marshal(msg)
+
+ if err != nil {
+ log.Printf("Response stream manager: error marshalling message: %v\n", err)
+ return
+ }
+
+ err = sendStreamMessage(w, active, string(bytes))
+ if err != nil {
+ return
+ }
+
for {
select {
case <-active.Ctx.Done():
@@ -26,20 +43,27 @@ func startResponseStream(w http.ResponseWriter, ch chan string, active *types.Ac
return
case msg := <-ch:
// log.Println("Response stream manager: sending message:", msg)
-
- bytes := []byte(msg + shared.STREAM_MESSAGE_SEPARATOR)
- _, err := w.Write(bytes)
+ err = sendStreamMessage(w, active, msg)
if err != nil {
- log.Printf("Response stream mananger: error writing to client: %v\n", err)
- if !active.IsBackground && active.NumSubscribers() == 1 {
- active.CancelFn()
- }
return
}
- if flusher, ok := w.(http.Flusher); ok {
- flusher.Flush()
- }
}
}
}
+
+func sendStreamMessage(w http.ResponseWriter, active *types.ActivePlan, msg string) error {
+ bytes := []byte(msg + shared.STREAM_MESSAGE_SEPARATOR)
+ _, err := w.Write(bytes)
+ if err != nil {
+ log.Printf("Response stream mananger: error writing to client: %v\n", err)
+ if !active.IsBackground && active.NumSubscribers() == 1 {
+ active.CancelFn()
+ }
+ return err
+ }
+ if flusher, ok := w.(http.Flusher); ok {
+ flusher.Flush()
+ }
+ return nil
+}
diff --git a/app/server/model/name.go b/app/server/model/name.go
index 60cd7c48..1502b269 100644
--- a/app/server/model/name.go
+++ b/app/server/model/name.go
@@ -25,8 +25,20 @@ func GenPlanName(client *openai.Client, planContent string) (string, error) {
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
- Model: NameModel,
- Functions: []openai.FunctionDefinition{prompts.PlanNameFn},
+ Model: NameModel,
+ Tools: []openai.Tool{
+ {
+ Type: "function",
+ Function: prompts.PlanNameFn,
+ },
+ },
+ ToolChoice: openai.ToolChoice{
+ Type: "function",
+ Function: openai.ToolFunction{
+ Name: prompts.PlanNameFn.Name,
+ },
+ },
+
Messages: messages,
ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
},
@@ -41,11 +53,11 @@ func GenPlanName(client *openai.Client, planContent string) (string, error) {
}
for _, choice := range resp.Choices {
- if choice.FinishReason == "function_call" &&
- choice.Message.FunctionCall != nil &&
- choice.Message.FunctionCall.Name == "namePlan" {
- fnCall := choice.Message.FunctionCall
+ if len(choice.Message.ToolCalls) == 1 &&
+ choice.Message.ToolCalls[0].Function.Name == prompts.PlanNameFn.Name {
+ fnCall := choice.Message.ToolCalls[0].Function
res = fnCall.Arguments
+ break
}
}
diff --git a/app/server/model/openai_models.go b/app/server/model/openai_models.go
index 290e8917..829447c0 100644
--- a/app/server/model/openai_models.go
+++ b/app/server/model/openai_models.go
@@ -6,9 +6,9 @@ import (
"github.com/sashabaranov/go-openai"
)
-const strongModel = openai.GPT4Turbo1106
-const mediumModel = openai.GPT4Turbo1106
-const weakModel = openai.GPT3Dot5Turbo1106
+const strongModel = openai.GPT4Turbo0125
+const mediumModel = openai.GPT4Turbo0125
+const weakModel = openai.GPT3Dot5Turbo0125
var PlannerModel = strongModel
var PlanSummaryModel = mediumModel
diff --git a/app/server/model/plan/build.go b/app/server/model/plan/build.go
index 45208654..a6bb4e6b 100644
--- a/app/server/model/plan/build.go
+++ b/app/server/model/plan/build.go
@@ -144,18 +144,19 @@ func queueBuilds(client *openai.Client, currentOrgId, currentUserId, planId, bra
activePlan := GetActivePlan(planId, branch)
filePath := activeBuilds[0].Path
+ // log.Printf("Queue:")
+ // spew.Dump(activePlan.BuildQueuesByPath[filePath])
+
UpdateActivePlan(planId, branch, func(active *types.ActivePlan) {
active.BuildQueuesByPath[filePath] = append(active.BuildQueuesByPath[filePath], activeBuilds...)
})
log.Printf("Queued %d build(s) for file %s\n", len(activeBuilds), filePath)
- // log.Printf("Queue:")
- // spew.Dump(activePlan.BuildQueuesByPath[filePath])
if activePlan.IsBuildingByPath[filePath] {
log.Printf("Already building file %s\n", filePath)
return
} else {
- log.Printf("Will process build queue for file %s\n", filePath)
+ log.Printf("Not building file %s, will execute now\n", filePath)
go execPlanBuild(client, currentOrgId, currentUserId, branch, activePlan, activeBuilds)
}
}
@@ -181,9 +182,11 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
}
}
- UpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {
- ap.IsBuildingByPath[filePath] = true
- })
+ if !activePlan.IsBuildingByPath[filePath] {
+ UpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {
+ ap.IsBuildingByPath[filePath] = true
+ })
+ }
buildInfo := &shared.BuildInfo{
Path: filePath,
@@ -270,7 +273,7 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
currentPlan = res
log.Println("Got current plan state")
- spew.Dump(currentPlan)
+ // spew.Dump(currentPlan)
}()
errCh := make(chan error)
@@ -281,8 +284,8 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
// first check if any of the messages we're building hasen't finished streaming yet
stillStreaming := false
var doneCh chan bool
+ ap := GetActivePlan(planId, branch)
for _, convoMessageId := range convoMessageIds {
- ap := GetActivePlan(planId, branch)
if ap.CurrentStreamingReplyId == convoMessageId {
stillStreaming = true
doneCh = ap.CurrentReplyDoneCh
@@ -294,6 +297,14 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
<-doneCh
}
+ // Check again if build is finished
+ // (more builds could have been queued while we were waiting for the reply to finish streaming)
+ ap = GetActivePlan(planId, branch)
+ if !ap.BuildFinished() {
+ log.Println("Build not finished after waiting for reply to finish streaming")
+ return
+ }
+
repoLockId, err := db.LockRepo(
db.LockRepoParams{
OrgId: currentOrgId,
@@ -407,7 +418,7 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
active := GetActivePlan(planId, branch)
- if active.RepliesFinished || active.BuildOnly {
+ if active != nil && (active.RepliesFinished || active.BuildOnly) {
activePlan.Stream(shared.StreamMessage{
Type: shared.StreamMessageFinished,
})
@@ -480,8 +491,6 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
ap.BuiltFiles[filePath] = true
- ap.IsBuildingByPath[filePath] = false
-
if ap.BuildFinished() {
finished = true
}
@@ -490,10 +499,18 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
log.Printf("Finished building file %s\n", filePath)
if finished {
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.IsBuildingByPath[filePath] = false
+ })
log.Println("Finished building plan, calling onFinishBuild")
onFinishBuild()
} else {
- if !activePlan.PathFinished(filePath) {
+ if activePlan.PathFinished(filePath) {
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.IsBuildingByPath[filePath] = false
+ })
+ log.Printf("File %s finished, but not all builds finished\n", filePath)
+ } else {
log.Printf("Processing next build for file %s\n", filePath)
var nextBuilds []*types.ActiveBuild
for _, build := range activePlan.BuildQueuesByPath[filePath] {
@@ -502,16 +519,15 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
}
}
- log.Println("Next builds:")
- spew.Dump(nextBuilds)
+ // log.Println("Next builds:")
+ // spew.Dump(nextBuilds)
+ log.Printf("%d builds left for file %s\n", len(nextBuilds), filePath)
if len(nextBuilds) > 0 {
log.Println("Calling execPlanBuild for next build in queue")
go execPlanBuild(client, currentOrgId, currentUserId, branch, activePlan, nextBuilds)
}
return
- } else {
- log.Printf("File %s finished, but not all builds finished\n", filePath)
}
}
}
@@ -550,6 +566,11 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
buildFile = func(filePath string, numRetry int, numReplacementsRetry int, res *db.PlanFileResult) {
log.Printf("Building file %s, numRetry: %d\n", filePath, numRetry)
+ log.Println("activePlan.ContextsByPath files:")
+ for k := range activePlan.ContextsByPath {
+ log.Println(k)
+ }
+
// get relevant file context (if any)
contextPart := activePlan.ContextsByPath[filePath]
@@ -563,7 +584,13 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
// log.Println("Current state:")
// log.Println(currentState)
} else if contextPart != nil {
+ log.Printf("File %s found in model context. Using context state.\n", filePath)
+
currentState = contextPart.Body
+
+ if currentState == "" {
+ log.Println("Context state is empty. That's bad.")
+ }
}
if currentState == "" {
@@ -606,8 +633,8 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
}
log.Println("Num active builds: " + fmt.Sprintf("%d", len(activeBuilds)))
- log.Println("Merged reply:")
- log.Println(mergedReply)
+ // log.Println("Merged reply:")
+ // log.Println(mergedReply)
fileMessages := []openai.ChatCompletionMessage{
{
@@ -660,8 +687,19 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
// }
modelReq := openai.ChatCompletionRequest{
- Model: model.BuilderModel,
- Functions: []openai.FunctionDefinition{prompts.ReplaceFn},
+ Model: model.BuilderModel,
+ Tools: []openai.Tool{
+ {
+ Type: "function",
+ Function: prompts.ReplaceFn,
+ },
+ },
+ ToolChoice: openai.ToolChoice{
+ Type: "function",
+ Function: openai.ToolFunction{
+ Name: prompts.ReplaceFn.Name,
+ },
+ },
Messages: fileMessages,
Temperature: 0.2,
TopP: 0.1,
@@ -765,48 +803,30 @@ func execPlanBuild(client *openai.Client, currentOrgId, currentUserId, branch st
}
choice := response.Choices[0]
+ var content string
+ delta := response.Choices[0].Delta
- if choice.FinishReason != "" {
- if choice.FinishReason != openai.FinishReasonFunctionCall {
- handleErrorRetry(
- fmt.Errorf("stream finished without a function call. Reason: %s, File: %s", choice.FinishReason, filePath),
- false,
- false,
- res,
- )
- return
- }
+ if len(delta.ToolCalls) == 0 {
+ log.Println("Stream chunk missing function call. Response:")
+ spew.Dump(response)
- log.Printf("File %s: Stream finished with non-function call\n", filePath)
- log.Println("finish reason: " + choice.FinishReason)
-
- active := GetActivePlan(planId, branch)
- if !active.BuiltFiles[filePath] {
- log.Printf("Stream finished before replacements parsed. File: %s\n", filePath)
- log.Println("Buffer:")
- log.Println(buffer)
-
- handleErrorRetry(
- fmt.Errorf("stream finished before replacements parsed. File: %s", filePath),
- true,
- false,
- res,
- )
- return
- }
- }
+ log.Println("Messages:")
+ spew.Dump(fileMessages)
- var content string
- delta := response.Choices[0].Delta
+ log.Println("Buffer:")
+ log.Println(buffer)
+
+ handleErrorRetry(
+ fmt.Errorf("stream chunk missing function call. Reason: %s, File: %s", choice.FinishReason, filePath),
+ false,
+ false,
+ res,
+ )
+ return
- if delta.FunctionCall == nil {
- log.Println("No function call in delta. File:", filePath)
- spew.Dump(delta)
- continue
- } else {
- content = delta.FunctionCall.Arguments
}
+ content = delta.ToolCalls[0].Function.Arguments
buildInfo := &shared.BuildInfo{
Path: filePath,
NumTokens: 1,
@@ -911,8 +931,10 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {
_, allSucceeded := shared.ApplyReplacements(currentState, replacements, true)
var contextSha string
+ var contextBody string
if contextPart != nil {
contextSha = contextPart.Sha
+ contextBody = contextPart.Body
}
for _, replacement := range replacements {
@@ -929,7 +951,7 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {
Path: filePath,
Replacements: replacements,
ContextSha: contextSha,
- ContextBody: contextPart.Body,
+ ContextBody: contextBody,
AnyFailed: !allSucceeded,
}, allSucceeded
}
diff --git a/app/server/model/plan/describe.go b/app/server/model/plan/describe.go
index 28854dfd..fbdcf59a 100644
--- a/app/server/model/plan/describe.go
+++ b/app/server/model/plan/describe.go
@@ -17,8 +17,19 @@ func genPlanDescription(client *openai.Client, planId, branch string, ctx contex
descResp, err := client.CreateChatCompletion(
ctx,
openai.ChatCompletionRequest{
- Model: model.CommitMsgModel,
- Functions: []openai.FunctionDefinition{prompts.DescribePlanFn},
+ Model: model.CommitMsgModel,
+ Tools: []openai.Tool{
+ {
+ Type: "function",
+ Function: prompts.DescribePlanFn,
+ },
+ },
+ ToolChoice: openai.ToolChoice{
+ Type: "function",
+ Function: openai.ToolFunction{
+ Name: prompts.DescribePlanFn.Name,
+ },
+ },
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
@@ -42,17 +53,17 @@ func genPlanDescription(client *openai.Client, planId, branch string, ctx contex
var desc shared.ConvoMessageDescription
for _, choice := range descResp.Choices {
- if choice.FinishReason == "function_call" &&
- choice.Message.FunctionCall != nil &&
- choice.Message.FunctionCall.Name == "describePlan" {
- fnCall := choice.Message.FunctionCall
+ if len(choice.Message.ToolCalls) == 1 &&
+ choice.Message.ToolCalls[0].Function.Name == prompts.DescribePlanFn.Name {
+ fnCall := choice.Message.ToolCalls[0].Function
descStrRes = fnCall.Arguments
+ break
}
}
if descStrRes == "" {
fmt.Println("no describePlan function call found in response")
- return nil, err
+ return nil, fmt.Errorf("no describePlan function call found in response")
}
descByteRes := []byte(descStrRes)
diff --git a/app/server/model/plan/exec_status.go b/app/server/model/plan/exec_status.go
index 88ea5e6f..4a25c0b1 100644
--- a/app/server/model/plan/exec_status.go
+++ b/app/server/model/plan/exec_status.go
@@ -17,21 +17,20 @@ func ExecStatusShouldContinue(client *openai.Client, message string, ctx context
// First try to determine if the plan should continue based on the last paragraph without calling the model
paragraphs := strings.Split(message, "\n\n")
- lastParagraph := paragraphs[len(paragraphs)-1]
+ lastParagraphLower := strings.ToLower(paragraphs[len(paragraphs)-1])
- log.Printf("Last paragraph: %s\n", lastParagraph)
+ // log.Printf("Last paragraph: %s\n", lastParagraphLower)
- if lastParagraph != "" {
- if strings.Contains(lastParagraph, "All tasks have been completed") ||
- strings.Contains(lastParagraph, "all tasks have been completed") ||
- strings.Contains(lastParagraph, "plan cannot be continued") {
+ if lastParagraphLower != "" {
+ if strings.Contains(lastParagraphLower, "all tasks have been completed") ||
+ strings.Contains(lastParagraphLower, "plan cannot be continued") {
log.Println("Plan cannot be continued based on last paragraph")
return false, nil
}
- if strings.Index(lastParagraph, "Next, ") < 3 {
+ if strings.Index(lastParagraphLower, "next,") < 3 {
log.Println("Plan can be continued based on last paragraph")
@@ -51,8 +50,19 @@ func ExecStatusShouldContinue(client *openai.Client, message string, ctx context
resp, err := client.CreateChatCompletion(
ctx,
openai.ChatCompletionRequest{
- Model: model.PlanExecStatusModel,
- Functions: []openai.FunctionDefinition{prompts.ShouldAutoContinueFn},
+ Model: model.PlanExecStatusModel,
+ Tools: []openai.Tool{
+ {
+ Type: "function",
+ Function: prompts.ShouldAutoContinueFn,
+ },
+ },
+ ToolChoice: openai.ToolChoice{
+ Type: "function",
+ Function: openai.ToolFunction{
+ Name: prompts.ShouldAutoContinueFn.Name,
+ },
+ },
Messages: messages,
ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
},
@@ -72,11 +82,11 @@ func ExecStatusShouldContinue(client *openai.Client, message string, ctx context
}
for _, choice := range resp.Choices {
- if choice.FinishReason == "function_call" &&
- choice.Message.FunctionCall != nil &&
- choice.Message.FunctionCall.Name == "shouldAutoContinue" {
- fnCall := choice.Message.FunctionCall
+ if len(choice.Message.ToolCalls) == 1 &&
+ choice.Message.ToolCalls[0].Function.Name == prompts.ShouldAutoContinueFn.Name {
+ fnCall := choice.Message.ToolCalls[0].Function
strRes = fnCall.Arguments
+ break
}
}
diff --git a/app/server/model/plan/stop.go b/app/server/model/plan/stop.go
index 2be341f2..abfcccc0 100644
--- a/app/server/model/plan/stop.go
+++ b/app/server/model/plan/stop.go
@@ -26,13 +26,15 @@ func Stop(planId, branch, currentUserId, currentOrgId string) error {
active.CancelFn()
if !active.BuildOnly {
+ num := active.MessageNum + 1
+
userMsg := db.ConvoMessage{
OrgId: currentOrgId,
PlanId: planId,
UserId: currentUserId,
Role: openai.ChatMessageRoleAssistant,
Tokens: active.NumTokens,
- Num: active.PromptMessageNum + 1,
+ Num: num,
Stopped: true,
Message: active.CurrentReplyContent,
}
diff --git a/app/server/model/plan/tell.go b/app/server/model/plan/tell.go
index 57507934..0fcfc76f 100644
--- a/app/server/model/plan/tell.go
+++ b/app/server/model/plan/tell.go
@@ -24,7 +24,7 @@ import (
func Tell(client *openai.Client, plan *db.Plan, branch string, auth *types.ServerAuth, req *shared.TellPlanRequest) error {
log.Printf("Tell: Called with plan ID %s on branch %s\n", plan.Id, branch)
- active, err := activatePlan(client, plan, branch, auth, req.Prompt, false)
+ _, err := activatePlan(client, plan, branch, auth, req.Prompt, false)
if err != nil {
log.Printf("Error activating plan: %v\n", err)
@@ -37,7 +37,6 @@ func Tell(client *openai.Client, plan *db.Plan, branch string, auth *types.Serve
branch,
auth,
req,
- active,
0,
"",
req.BuildMode == shared.BuildModeAuto,
@@ -47,11 +46,22 @@ func Tell(client *openai.Client, plan *db.Plan, branch string, auth *types.Serve
return nil
}
-func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *types.ServerAuth, req *shared.TellPlanRequest, active *types.ActivePlan, iteration int, missingFileResponse shared.RespondMissingFileChoice, shouldBuildPending bool) {
+func execTellPlan(
+ client *openai.Client,
+ plan *db.Plan,
+ branch string,
+ auth *types.ServerAuth,
+ req *shared.TellPlanRequest,
+ iteration int,
+ missingFileResponse shared.RespondMissingFileChoice,
+ shouldBuildPending bool,
+) {
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
+ active := GetActivePlan(plan.Id, branch)
+
if os.Getenv("IS_CLOUD") != "" &&
missingFileResponse == "" {
log.Println("execTellPlan: IS_CLOUD environment variable is set")
@@ -205,13 +215,15 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
go func() {
if iteration == 0 && missingFileResponse == "" {
+ num := len(convo) + 1
+
userMsg := db.ConvoMessage{
OrgId: currentOrgId,
PlanId: planId,
UserId: currentUserId,
Role: openai.ChatMessageRoleUser,
Tokens: promptTokens,
- Num: len(convo) + 1,
+ Num: num,
Message: req.Prompt,
}
@@ -222,6 +234,10 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
innerErrCh <- fmt.Errorf("error storing user message: %v", err)
return
}
+
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.MessageNum = num
+ })
}
innerErrCh <- nil
@@ -301,7 +317,6 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
if iteration == 0 && missingFileResponse == "" {
UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
ap.Contexts = modelContext
- ap.PromptMessageNum = len(convo) + 1
for _, context := range modelContext {
if context.FilePath != "" {
@@ -524,6 +539,8 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
replyParser := types.NewReplyParser()
replyFiles := []string{}
replyNumTokens := 0
+ chunksReceived := 0
+ maybeRedundantBacktickContent := ""
var promptMessage *openai.ChatCompletionMessage
var prompt string
@@ -540,11 +557,18 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
if missingFileResponse == "" {
messages = append(messages, *promptMessage)
- } else {
+ }
+
+ if missingFileResponse != "" {
+ log.Println("Missing file response:", missingFileResponse, "setting replyParser")
+
replyParser.AddChunk(active.CurrentReplyContent, true)
res := replyParser.Read()
currentFile := res.CurrentFilePath
+ log.Printf("Current file: %s\n", currentFile)
+ // log.Println("Current reply content:\n", active.CurrentReplyContent)
+
replyContent := active.CurrentReplyContent
numTokens := active.NumTokens
@@ -602,9 +626,6 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
}
}
- replyNumTokens = active.NumTokens
- replyFiles = active.Files
-
// log.Println("\n\nMessages:")
// for _, message := range messages {
// log.Printf("%s: %s\n", message.Role, message.Content)
@@ -664,7 +685,7 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
ap.CurrentStreamingReplyId = replyId
- ap.CurrentReplyDoneCh = make(chan bool)
+ ap.CurrentReplyDoneCh = make(chan bool, 1)
})
storeAssistantReply := func() (*db.ConvoMessage, []string, string, error) {
@@ -673,6 +694,8 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
num++
}
+ log.Printf("Storing assistant reply num %d\n", num)
+
assistantMsg := db.ConvoMessage{
Id: replyId,
OrgId: currentOrgId,
@@ -691,6 +714,10 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
return nil, replyFiles, "", err
}
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.MessageNum = num
+ })
+
return &assistantMsg, replyFiles, commitMsg, err
}
@@ -817,6 +844,8 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
})
}
+ log.Println("Locking repo for assistant reply and description")
+
repoLockId, err := db.LockRepo(
db.LockRepoParams{
OrgId: currentOrgId,
@@ -839,6 +868,8 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
return
}
+ log.Println("Locked repo for assistant reply and description")
+
var shouldContinue bool
err = func() error {
defer func() {
@@ -850,6 +881,8 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
}
}
+ log.Println("Unlocking repo for assistant reply and description")
+
err = db.UnlockRepo(repoLockId)
if err != nil {
log.Printf("Error unlocking repo: %v\n", err)
@@ -914,6 +947,8 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
return
}
+ log.Printf("Should continue: %v\n", shouldContinue)
+
errCh <- nil
}()
@@ -924,7 +959,7 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
}
}
- log.Println("Comitting assistant message and description")
+ log.Println("Comitting reply message and description")
err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)
if err != nil {
@@ -932,6 +967,8 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
return err
}
+ log.Println("Assistant reply and description committed")
+
return nil
}()
@@ -939,22 +976,26 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
return
}
+ log.Println("Sending active.CurrentReplyDoneCh <- true")
+
active.CurrentReplyDoneCh <- true
- UpdateActivePlan(planId, branch, func(active *types.ActivePlan) {
- active.CurrentStreamingReplyId = ""
- active.CurrentReplyDoneCh = nil
+ log.Println("Resetting active.CurrentReplyDoneCh")
+
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.CurrentStreamingReplyId = ""
+ ap.CurrentReplyDoneCh = nil
})
if req.AutoContinue && shouldContinue {
log.Println("Auto continue plan")
// continue plan
- execTellPlan(client, plan, branch, auth, req, active, iteration+1, "", false)
+ execTellPlan(client, plan, branch, auth, req, iteration+1, "", false)
} else {
var buildFinished bool
- UpdateActivePlan(planId, branch, func(active *types.ActivePlan) {
- buildFinished = active.BuildFinished()
- active.RepliesFinished = true
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ buildFinished = ap.BuildFinished()
+ ap.RepliesFinished = true
})
log.Printf("Won't continue plan. Build finished: %v\n", buildFinished)
@@ -974,11 +1015,30 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
return
}
+ chunksReceived++
delta := choice.Delta
content := delta.Content
- UpdateActivePlan(planId, branch, func(active *types.ActivePlan) {
- active.CurrentReplyContent += content
- active.NumTokens++
+
+ if missingFileResponse != "" {
+ if chunksReceived < 3 && strings.Contains(content, "```") {
+ // received closing triple backticks in first 3 chunks after missing file response
+ // means this is a redundant start of a new file block, so just ignore it
+
+ maybeRedundantBacktickContent += content
+ continue
+ } else if maybeRedundantBacktickContent != "" {
+ if strings.Contains(content, "\n") {
+ maybeRedundantBacktickContent = ""
+ } else {
+ maybeRedundantBacktickContent += content
+ continue
+ }
+ }
+ }
+
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.CurrentReplyContent += content
+ ap.NumTokens++
})
// log.Printf("Sending stream msg: %s", content)
@@ -986,15 +1046,20 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
Type: shared.StreamMessageReply,
ReplyChunk: content,
})
- replyParser.AddChunk(content, true)
- res := replyParser.Read()
+ // log.Printf("content: %s\n", content)
+ replyParser.AddChunk(content, true)
+ res := replyParser.Read()
files := res.Files
fileContents := res.FileContents
replyNumTokens = res.TotalTokens
currentFile := res.CurrentFilePath
+ // log.Printf("currentFile: %s\n", currentFile)
+ // log.Println("files:")
+ // spew.Dump(files)
+
// Handle file that is present in project paths but not in context
// Prompt user for what to do on the client side, stop the stream, and wait for user response before proceeding
if currentFile != "" &&
@@ -1025,7 +1090,7 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
log.Printf("Stopping stream for missing file: %s\n", currentFile)
- log.Printf("Current reply content: %s\n", active.CurrentReplyContent)
+ // log.Printf("Current reply content: %s\n", active.CurrentReplyContent)
// stop stream for now
active.CancelModelStreamFn()
@@ -1048,7 +1113,6 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
branch,
auth,
req,
- active,
iteration, // keep the same iteration
userChoice,
false,
@@ -1056,10 +1120,23 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
return
}
+ // log.Println("Content:", content)
+ // log.Println("Current reply content:", active.CurrentReplyContent)
+ // log.Println("Current file:", currentFile)
+ // log.Println("files:")
+ // spew.Dump(files)
+ // log.Println("replyFiles:")
+ // spew.Dump(replyFiles)
+
if len(files) > len(replyFiles) {
- log.Printf("Files: %v\n", files)
- for i := len(files) - 1; i > len(replyFiles)-1; i-- {
- file := files[i]
+ log.Printf("%d new files\n", len(files)-len(replyFiles))
+
+ for i, file := range files {
+ if i < len(replyFiles) {
+ continue
+ }
+
+ log.Printf("New file: %s\n", file)
if req.BuildMode == shared.BuildModeAuto {
log.Printf("Queuing build for %s\n", file)
queueBuilds(client, currentOrgId, currentUserId, planId, branch, []*types.ActiveBuild{{
@@ -1070,12 +1147,11 @@ func execTellPlan(client *openai.Client, plan *db.Plan, branch string, auth *typ
}})
}
replyFiles = append(replyFiles, file)
- UpdateActivePlan(planId, branch, func(active *types.ActivePlan) {
- active.Files = append(active.Files, file)
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.Files = append(ap.Files, file)
})
}
}
-
}
}
}()
diff --git a/app/server/model/prompts/create.go b/app/server/model/prompts/create.go
index 7bd47b39..8ec73a3e 100644
--- a/app/server/model/prompts/create.go
+++ b/app/server/model/prompts/create.go
@@ -12,11 +12,11 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
`First, decide if the user has a task for you.
- If the user doesn't have a task and is just asking a question or chatting, ignore the rest of the instructions below, and respond to the user in chat form. You can make reference to the context to inform your response, and you can include code in your response, but don't include labelled code blocks as described below, since that indicates that a plan is being created.
+ *If the user doesn't have a task and is just asking a question or chatting*, ignore the rest of the instructions below, and respond to the user in chat form. You can make reference to the context to inform your response, and you can include code in your response, but don't include labelled code blocks as described below, since that indicates that a plan is being created. If a plan is in progress, follow the instructions below.
- If the user does have a task, create a plan for the task based on user-provided context using the following steps:
+ *If the user does have a task*, create a plan for the task based on user-provided context using the following steps:
- 1. Decide whether you've been given enough information and context to make a good plan.
+ 1. Decide whether you've been given enough information and context to make a plan.
- Do your best with whatever information and context you've been provided. Choose sensible values and defaults where appropriate. Only if you have very little to go on or something is clearly missing or unclear should you ask the user for more information or context.
a. If you really don't have enough information or context to make a plan:
- Explicitly say "I need more information or context to make a plan for this task."
@@ -27,8 +27,9 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
- src/main.rs:
- lib/term.go:
- main.py:
- File paths should always come *before* the opening triple backticks of a code block. They should *not* be included in the code block itself.
- File paths should appear *immediately* before the opening triple backticks of a code block. There should be *no other lines* between the file path and the code block. Any explanations should come either *before the file path or after the code block.*
+ ***File paths should always come *before* the opening triple backticks of a code block. They should *not* be included in the code block itself.
+ ***File paths should appear *immediately* before the opening triple backticks of a code block. There should be *no other lines* between the file path and the code block. Any explanations should come either *before the file path or after the code block.*
+ ***You *must not* include any other text in a code block label apart from the initial '- ' and the file path. DO NOT use a label like 'File path: src/main.rs' or 'src/main.rs: (Create this file)'. Instead use 'src/main.rs:'. DO NOT include any explanatory text in the code block label like 'src/main.rs: (Add a new function)'. Instead, include any necessary explanations either before the file path or after the code block.
b. If not:
- Explicitly say "Let's break up this task."
- Divide the task into smaller subtasks and list them in a numbered list. Stop there.
@@ -39,6 +40,8 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
Every file you reference in a plan should either exist in the context directly or be a new file that will be created in the same base directory a file in the context. For example, if there is a file in context at path 'lib/term.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/term.go'. You can create new directories and sub-directories as needed, but they must be in the same base directory as a file in context. Don't ask the user to create new files or directories--you must do that yourself.
+ **You must not include anything except code in labelled file blocks for code files.** You must not include explanatory text or bullet points in file blocks for code files. Only code. Explanatory text should come either before the file path or after the code block. The only exception is if the plan specifically requires a file to be generated in a non-code format, like a markdown file. In that case, you can include the non-code content in the file block. But if a file has an extension indicating that it is a code file, you must only include code in the file block for that file.
+
For code in markdown blocks, always include the language name after the opening triple backticks.
Don't include unnecessary comments in code. Lean towards no comments as much as you can. If you must include a comment to make the code understandable, be sure it is concise. Don't use comments to communicate with the user.
@@ -53,32 +56,73 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
For changes that are larger or more complex, only include one change per response.
+ As much as possible, do not include placeholders in code blocks. Unless you absolutely cannot implement the full code block, do not include a placeholder denoted with comments. Do your best to implement the functionality rather than inserting a placeholder. You **MUST NOT** include placeholders just to shorten the code block. If the task is too large to implement in a single code block, you should break the task down into smaller steps and **FULLY** implement each step.
+
**Don't ask the user to take an action that you are able to do.** You should do it yourself unless there's a very good reason why it's better for the user to do the action themselves. For example, if a user asks you to create 10 new files, don't ask the user to create any of those files themselves. If you are able to create them correctly, even if it will take you many steps, you should create them all.
- At the end of your response, you can suggest additional iterations to make the plan better. You can also ask the user to load more files into context or give you more information if it would help you make a better plan.
+ At the end of each response, you can suggest additional iterations to make the plan better. You can also ask the user to load more files into context or give you more information if it would help you make a better plan.
At the *very* end of your response, in a final, separate paragraph, you *must* decide whether the plan is completed and if not, whether it should be automatically continued.
-
- - If all the subtasks in a plan are completed (including if there is a single task and no subtasks), you must explictly say "All tasks have been completed."
+ - If all the subtasks in a plan have been completed you must explictly say "All tasks have been completed."
Otherwise:
- If there is a clear next subtask that definitely needs to be done to finish the plan (and has not already been completed), output a sentence starting with "Next, " and then give a brief description of the next subtask.
- If there is no clear next subtask, or the user needs to take some action before you can continue, explicitly say "The plan cannot be continued." Then finish with a brief description of what the user needs to do for the plan to proceed.
- - You must not output any other text after this final paragraph. It *must* be the last thing in your response, and it *must* begin with one of the three options above ("All tasks have been completed.", "Next, ", or "The plan cannot be continued.").
+ - You must not output any other text after this final paragraph. It *must* be the last thing in your response, and it *must* begin with one of the options above ("All tasks have been completed.", "Next, ", or "The plan cannot be continued.").
- You should consider the plan complete if all the subtasks are completed to a decent standard. Even if there are additional steps that *could* be taken, if you have completed all the subtasks, you should consider the plan complete.
- Don't consider the user verifying or testing the code as a next step. If all that's left is for the user to verify or test the code, consider the plan complete.
- Remember not to ask the user to do anything that you can do yourself, or anything that isn't strictly necessary for completing the plan to a decent standard.
+ You *must never respond with just a single paragraph.* Every response should include at least a few paragraphs that try to move a plan forward. You *especially must never* reply with just a single paragraph that begins with "Next," or "The plan cannot be continued.". You must also **never reply with just a single paragraph that contains only "All tasks have been completed."**.
+
+ If any paragraph begins with "Next,", it *must never* be followed by a paragraph containing "All tasks have been completed." or "The plan cannot be continued." *Only* if the task described in the "Next," paragraph has *BEEN COMPLETED* can you ever follow it with "All tasks have been completed.".
+
+ If you working on a subtask, it should be implemented with code blocks unless it is impossible to do so. Apart from when you are following instruction 2b above to create the intial subtasks, you must not list, describe, or explain the subtask you are working on without an accompanying implementation in one or more code blocks.
+
+ If you are working on a subtask and it is too large to be implemented in a single response, it should be broken down into smaller steps. Each step should then be implemented with code blocks.
+
+ Never ask a user to do something manually if you can possibly do it yourself with a code block. Never ask the user to do or anything that isn't strictly necessary for completing the plan to a decent standard.
+
+ If the last paragraph (p) of your previous response in the conversation began with "Next," and you are continuing the plan:
+ - Continue from where your previous response left off.
+ - **Do not repeat any part of your previous response**
+ - **Do not begin your response with "Next,"**
+ - Continue seamlessly from where your previous response left off.
+ - Always continue with the task described in paragraph p unless the user has given you new instructions or context that make it clear that you should do something else.
+ - **Never begin your response with "The plan cannot be continued." or "All tasks have been completed."**
- Be aware that since the plan started, the context may have been updated. It may have been updated by the user implementing your suggestions, by the user implementing their own work, or by the user adding more files or information to context. Be sure to consider the current state of the context when continuing with the plan, and whether the plan needs to be updated to reflect the latest context. For example, if you are working on a plan that has been broken up into subtasks, and you've reached the point of implementing a particular subtask, first consider whether the subtask is still necessary looking at the files in context. If it has already been implemented or is no longer necessary, say so, revise the plan if needed, and move on. Otherwise, implement the subtask.
- ` +
+ Be aware that since the plan started, the context may have been updated. It may have been updated by the user implementing your suggestions, by the user implementing their own work, or by the user adding more files or information to context. Be sure to consider the current state of the context when continuing with the plan, and whether the plan needs to be updated to reflect the latest context. For example, if you are working on a plan that has been broken up into subtasks, and you've reached the point of implementing a particular subtask, first consider whether the subtask is still necessary looking at the files in context. If it has already been implemented or is no longer necessary, say so, revise the plan as needed, and move on. Otherwise, implement the subtask.
+
+ If a plan is in progress and the user asks you a question, don't respond by continuing with the plan unless that is the clear intention of the question. Instead, respond in chat form and answer the question, then stop there.
+ ` +
"\n```\n\n" +
"User-provided context:"
var CreateSysMsgNumTokens, _ = shared.GetNumTokens(SysCreate)
-const PromptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\n Please respond according to the 'Your instructions' section above. If you're making a plan, remember to precede code blocks with the file path *exactly* as described in 2a, and do not use any other formatting for file paths. If you're making a plan, also remember to end every response with either " + `"All tasks have been completed.", "Next, " (plus a brief descripton of the next step), or "The plan cannot be continued." according to your instructions for ending a response.`
+const PromptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\n Please respond according to the 'Your instructions' section above. If you're making a plan, remember to precede code blocks with the file path *exactly* as described in 2a, 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.** Always use triple backticks to start and end code blocks. Only list out subtasks once for the plan--after that, do not list or describe a subtask that can be implemented in code without including a code block that implements the subtask. Do not ask the user to do anything that you can do yourself with a code block. If you're making a plan, also remember to end every response with either " + `"All tasks have been completed.", "Next, " (plus a brief descripton of the next step), or "The plan cannot be continued." according to your instructions for ending a response.`
var PromptWrapperTokens, _ = shared.GetNumTokens(fmt.Sprintf(PromptWrapperFormatStr, ""))
+
+// --
+// For each task or subtask identified:
+
+// 1. Directly Implement in Code: Instead of describing what needs to be done,
+// directly implement the solution in code. This includes writing functions,
+// handlers, and any other necessary logic in the appropriate programming
+// language.
+// 2. Code Snippets: Provide complete code snippets that can be directly used
+// or easily adapted for use. Ensure these snippets are ready to be integrated
+// into the project.
+// 3. Detailed Instructions with Code: If a task requires explanation or
+// context, accompany these explanations with corresponding code snippets that
+// demonstrate or complete the task.
+// 4. No Placeholder Tasks: Avoid leaving tasks as placeholders or to-be-done
+// items. If a task is mentioned, it must be accompanied by its implementation
+// in code within the same response.
+// 5. Executable Plan: Ensure the plan culminates in a fully executable
+// implementation. By the end of your response, the user should have a clear,
+// actionable codebase that addresses the initial request without needing
+// further modifications or clarifications.
+// --
diff --git a/app/server/model/prompts/exec_status.go b/app/server/model/prompts/exec_status.go
index 1ca4587a..c19a6167 100644
--- a/app/server/model/prompts/exec_status.go
+++ b/app/server/model/prompts/exec_status.go
@@ -9,11 +9,11 @@ const SysExecStatusShouldContinue = `You are tasked with evaluating a response g
Your goal is to determine whether the plan created by AI 1 should automatically continue or if it is considered complete. To do this, you need to analyze the latest message of the plan from AI 1 carefully and decide based on the following criteria:
-Assess whether AI 1 has indicated that all tasks and subtasks within the plan have been completed. AI 1 should explicitly state "All tasks have been completed" if this is the case. If such a statement is present, the plan is considered complete and should not continue.
+Assess whether AI 1 has indicated that all tasks and subtasks within the plan have been completed.
-If AI 1 has concluded with a statement that indicates either the user needs to take specific actions before the plan can proceed, or that the plan can't automatically continue for any other reason. Look for the sentence "The plan isn't complete, but it can't be continued." followed by a description of what the user needs to or the reason why the plan cannot continue. In this case, the plan should not contineu.
+Assess whether AI 1 has concluded with a statement that indicates either the user needs to take specific actions before the plan can proceed, or that the plan can't automatically continue for any other reason. If so, the plan should not continue.
-If AI 1 has outlined a clear next step necessary to finish the plan but has not executed it, the plan should continue. Look for a sentence at the end of the response starting with "Next, " followed by a brief description of what should be done. In this place, the plan should continue.
+If AI 1 has outlined a clear next step necessary to finish the plan but has not executed it, the plan should continue.
You *must* call the shouldAutoContinue function with a JSON object containing the key 'shouldContinue'.
diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.go
index 051a61fc..88ea75ff 100644
--- a/app/server/types/active_plan.go
+++ b/app/server/types/active_plan.go
@@ -41,7 +41,7 @@ type ActivePlan struct {
IsBuildingByPath map[string]bool
CurrentReplyContent string
NumTokens int
- PromptMessageNum int
+ MessageNum int
BuildQueuesByPath map[string][]*ActiveBuild
RepliesFinished bool
StreamDoneCh chan *shared.ApiError
diff --git a/app/server/types/reply.go b/app/server/types/reply.go
index bbe99176..14269472 100644
--- a/app/server/types/reply.go
+++ b/app/server/types/reply.go
@@ -1,7 +1,11 @@
package types
import (
+ "log"
+ "strconv"
"strings"
+
+ "github.com/davecgh/go-spew/spew"
)
type parserRes struct {
@@ -92,19 +96,21 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {
}
prevFullLine := r.lines[r.lineIndex-1]
- // log.Println("Previous full line:", strconv.Quote(prevFullLine)) // Logging the full line that's being checked
+ log.Println("Previous full line:", strconv.Quote(prevFullLine)) // Logging the full line that's being checked
prevFullLineTrimmed := strings.TrimSpace(prevFullLine)
if r.maybeFilePath != "" {
- // log.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePath
+ log.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePath
if strings.HasPrefix(prevFullLineTrimmed, "```") {
+ log.Println("Found opening ticks--confirming file path...") // Logging the confirmed file path
+
r.currentFilePath = r.maybeFilePath
r.currentFileIdx = len(r.files)
r.fileContents = append(r.fileContents, "")
r.maybeFilePath = ""
r.currentFileLines = []string{}
- // log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path
+ log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path
return
} else if prevFullLineTrimmed != "" {
@@ -114,17 +120,17 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {
}
if r.currentFilePath == "" {
- // log.Println("Current file path is empty--checking for possible file path...")
+ log.Println("Current file path is empty--checking for possible file path...")
var gotPath string
if lineHasFilePath(prevFullLineTrimmed) {
gotPath = extractFilePath(prevFullLineTrimmed)
} else {
- // log.Println("No possible file path detected.", strconv.Quote(prevFullLineTrimmed))
+ log.Println("No possible file path detected.", strconv.Quote(prevFullLineTrimmed))
}
if gotPath != "" {
- // log.Println("Detected possible file path:", gotPath) // Logging the possible file path
+ log.Println("Detected possible file path:", gotPath) // Logging the possible file path
if r.maybeFilePath == "" {
r.maybeFilePath = gotPath
} else {
@@ -132,13 +138,15 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {
}
}
} else {
- // log.Println("Current file path is not empty--adding to current file...")
+ log.Println("Current file path is not empty--adding to current file...")
if strings.HasPrefix(prevFullLineTrimmed, "```") {
- // log.Println("Found closing ticks--adding file to files and resetting current file...")
+ log.Println("Found closing ticks--adding file to files and resetting current file...")
r.files = append(r.files, r.currentFilePath)
r.currentFilePath = ""
+
+ spew.Dump(r.files)
} else {
- // log.Println("Adding tokens to current file...") // Logging token addition
+ log.Println("Adding tokens to current file...") // Logging token addition
r.fileContents[r.currentFileIdx] += prevFullLine + "\n"
r.currentFileLines = append(r.currentFileLines, prevFullLine)
@@ -184,12 +192,17 @@ func lineHasFilePath(line string) bool {
}
func extractFilePath(line string) string {
- p := strings.TrimPrefix(line, "**")
+ p := strings.ReplaceAll(line, "**", "")
p = strings.TrimPrefix(p, "-")
p = strings.TrimSpace(p)
- p = strings.TrimSuffix(p, "**")
p = strings.TrimPrefix(p, "file:")
p = strings.TrimSuffix(p, ":")
p = strings.TrimSpace(p)
+
+ split := strings.Split(p, " ")
+ if len(split) > 1 {
+ p = split[0]
+ }
+
return p
}
diff --git a/app/shared/stream.go b/app/shared/stream.go
index 50e670ce..dd5efa5a 100644
--- a/app/shared/stream.go
+++ b/app/shared/stream.go
@@ -11,6 +11,7 @@ type BuildInfo struct {
type StreamMessageType string
const (
+ StreamMessageStart StreamMessageType = "start"
StreamMessageReply StreamMessageType = "reply"
StreamMessageDescribing StreamMessageType = "describing"
StreamMessageRepliesFinished StreamMessageType = "repliesFinished"