Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
reply parsing fix, sectionize fix
Dane Schneider24d198311960
diff --git a/cli/cmd/apply.go b/cli/cmd/apply.goindex a555bdd4..0099249b 100644--- a/cli/cmd/apply.go+++ b/cli/cmd/apply.go@@ -5,7 +5,6 @@ import ("io""log""os"- "os/exec""path/filepath""plandex/lib""strings"@@ -86,25 +85,8 @@ func apply(cmd *cobra.Command, args []string) error {return fmt.Errorf("Error processing files: %v", err)}- didExec := false- // If it exists, run [planDir]/exec.sh with cwd set to current process cwd- execPath := filepath.Join(rootDir, "exec.sh")- if _, err := os.Stat(execPath); err == nil {- // exec.sh exists, run it- cmd := exec.Command(execPath)- cmd.Stdout = os.Stdout- cmd.Stderr = os.Stderr- cmd.Dir = "." // Current process CWD-- err = cmd.Run()- if err != nil {- return fmt.Errorf("Error executing plan: %v", err)- }- didExec = true- }-- if copiedAny || didExec {- fmt.Println("Plan applied successfully!")+ if copiedAny {+ fmt.Println("✅ Applied changes")} else {return fmt.Errorf("This plan has no changes to apply.")}diff --git a/cli/cmd/preview.go b/cli/cmd/preview.goindex 0a617e14..e847c526 100644--- a/cli/cmd/preview.go+++ b/cli/cmd/preview.go@@ -79,5 +79,5 @@ func checkout(cmd *cobra.Command, args []string) {fmt.Fprintln(os.Stderr, "Error committing plan: ", err)return}- fmt.Println("✅ Applied changes")+}diff --git a/server/handlers/sectionize.go b/server/handlers/sectionize.gonew file mode 100644index 00000000..7e8a55d1--- /dev/null+++ b/server/handlers/sectionize.go@@ -0,0 +1,50 @@+package handlers++import (+ "encoding/json"+ "io"+ "log"+ "net/http"++ "plandex-server/model"+ "github.com/plandex/plandex/shared"+)++func SectionizeHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for SectionizeHandler")++ // Read the request body+ body, err := io.ReadAll(r.Body)+ if err != nil {+ log.Printf("Error reading request body: %v\n", err)+ http.Error(w, "Error reading request body", http.StatusInternalServerError)+ return+ }+ defer r.Body.Close()++ // Unmarshal the request body to obtain the 'text' that needs sectionizing+ var requestBody shared.SectionizeRequest+ if err := json.Unmarshal(body, &requestBody); err != nil {+ log.Printf("Error parsing request body: %v\n", err)+ http.Error(w, "Error parsing request body", http.StatusBadRequest)+ return+ }++ if requestBody.Text == "" {+ log.Println("Received an empty text field")+ http.Error(w, "text field is required", http.StatusBadRequest)+ return+ }++ // Call the model's Sectionize function and handle any returned errors+ modelRes, err := model.Sectionize(requestBody.Text)+ if err != nil {+ log.Printf("Error in sectionizing text: %v\n", err)+ http.Error(w, "Error in sectionizing text: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully processed sectionize request")+ // Write the response from the model's Sectionize function back to the client+ w.Write(modelRes)+}diff --git a/server/main.go b/server/main.goindex 8f98eb28..c2ccbf9e 100644--- a/server/main.go+++ b/server/main.go@@ -21,8 +21,8 @@ func main() {r.HandleFunc("/proposal", handlers.ProposalHandler).Methods("POST")r.HandleFunc("/abort-proposal", handlers.AbortProposalHandler).Methods("DELETE")// r.HandleFunc("/revise-proposal", handlers.ReviseProposalHandler).Methods("PATCH")-r.HandleFunc("/summarize", handlers.SummarizeHandler).Methods("POST")+ r.HandleFunc("/sectionize", handlers.SectionizeHandler).Methods("POST") // Registering the new endpoint here// Get port from the environment variable or default to 8088port := os.Getenv("PORT")@@ -32,4 +32,4 @@ func main() {log.Printf("Plandex server is running on :%s", port)log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), r))-}+}\ No newline at end of filediff --git a/server/model/sectionize.go b/server/model/sectionize.goindex b5995038..5aee40a3 100644--- a/server/model/sectionize.go+++ b/server/model/sectionize.go@@ -2,13 +2,13 @@ package modelimport ("context"+ "encoding/json""fmt"+ "plandex-server/types"+"github.com/davecgh/go-spew/spew"- "github.com/plandex/plandex/shared"- "github.com/plandex/plandex/server/types""github.com/sashabaranov/go-openai"- "github.com/sashabaranov/go-openai/jsonschema")func Sectionize(text string) ([]byte, error) {@@ -16,31 +16,18 @@ func Sectionize(text string) ([]byte, error) {context.Background(),openai.ChatCompletionRequest{Model: openai.GPT3Dot5Turbo,- Functions: []openai.FunctionDefinition{{- Name: "sectionize",- Parameters: &jsonschema.Definition{- Type: jsonschema.Object,- Properties: map[string]jsonschema.Definition{- "text": {- Type: jsonschema.String,- Description: "The text that needs to be sectionized",- },- },- Required: []string{"text"},- },- }},Messages: []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem,- Content: "You are an AI that breaks up text into logical sections. For code, each function would be its own section. Sections can also contain subsections.",+ Content: "You are an AI specialized in processing text and code, dividing them into logical sections and subsections based on their content. After sectionization, you should call the 'create_sections' function with your sectionization results.",},{Role: openai.ChatMessageRoleUser,- Content: fmt.Sprintf("Please sectionize the text below: \n %s", text),+ Content: fmt.Sprintf("Sectionize the text below, identifying logical sections and subsections, and call 'create_sections' with the sectionized results: %s",+ text),},},- },- )+ })if err != nil {return nil, err@@ -48,14 +35,14 @@ func Sectionize(text string) ([]byte, error) {var byteRes []bytefor _, choice := range resp.Choices {- if choice.FinishReason == "function_call" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "sectionize" {+ if choice.FinishReason == "stop" && choice.Message.Role == "assistant" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "create_sections" {fnCall := choice.Message.FunctionCallbyteRes = []byte(fnCall.Arguments)}}if len(byteRes) == 0 {- return nil, fmt.Errorf("no sectionize function call found in response")+ return nil, fmt.Errorf("no 'create_sections' function call found in response")}// validate the JSON response@@ -68,8 +55,3 @@ func Sectionize(text string) ([]byte, error) {return byteRes, nil}-- spew.Dump(sectionizeResp)-- return byteRes, nil-}diff --git a/shared/reply.go b/shared/reply.goindex f6f28ecf..97e8e647 100644--- a/shared/reply.go+++ b/shared/reply.go@@ -73,13 +73,15 @@ func (r *replyInfo) AddChunk(chunk string) {prevFullLine := r.lines[r.lineIndex-1]// fmt.Println("Previous full line:", strconv.Quote(prevFullLine)) // Logging the full line that's being checked+ prevFullLineTrimmed := strings.TrimSpace(prevFullLine)+if r.maybeFilePath != "" {// fmt.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePath- if strings.HasPrefix(prevFullLine, "```") {+ if strings.HasPrefix(prevFullLineTrimmed, "```") {r.currentFilePath = r.maybeFilePathr.maybeFilePath = ""// fmt.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path- } else if prevFullLine != "" {+ } else if prevFullLineTrimmed != "" {// turns out previous maybeFilePath was not a file path since there's a non-empty line before finding opening ticksr.maybeFilePath = ""}@@ -90,8 +92,8 @@ func (r *replyInfo) AddChunk(chunk string) {// fmt.Println("Current file path is empty--checking for possible file path...")var gotPath string- if (strings.HasPrefix(prevFullLine, "-")) || strings.HasPrefix(prevFullLine, "-file:") || strings.HasPrefix(prevFullLine, "- file:") || (strings.HasPrefix(prevFullLine, "**") && strings.HasSuffix(prevFullLine, "**")) {- p := strings.TrimPrefix(prevFullLine, "**")+ if (strings.HasPrefix(prevFullLineTrimmed, "-")) || strings.HasPrefix(prevFullLineTrimmed, "-file:") || strings.HasPrefix(prevFullLineTrimmed, "- file:") || (strings.HasPrefix(prevFullLineTrimmed, "**") && strings.HasSuffix(prevFullLineTrimmed, "**")) {+ p := strings.TrimPrefix(prevFullLineTrimmed, "**")p = strings.TrimPrefix(p, "-")p = strings.TrimSpace(p)p = strings.TrimSuffix(p, "**")@@ -100,7 +102,7 @@ func (r *replyInfo) AddChunk(chunk string) {p = strings.TrimSpace(p)gotPath = p} else {- // fmt.Println("No possible file path detected.", strconv.Quote(prevFullLine))+ // fmt.Println("No possible file path detected.", strconv.Quote(prevFullLineTrimmed))}if gotPath != "" {@@ -113,7 +115,7 @@ func (r *replyInfo) AddChunk(chunk string) {}}} else {- if strings.HasPrefix(prevFullLine, "```") {+ if strings.HasPrefix(prevFullLineTrimmed, "```") {r.currentFilePath = ""// fmt.Println("Exited file block.")} else {diff --git a/shared/reply_test.go b/shared/reply_test.goindex 38e5f4c1..73bac4a5 100644--- a/shared/reply_test.go+++ b/shared/reply_test.go@@ -7,35 +7,40 @@ import ()type TestExample struct {- FilePath string+ N intNumPaths int}var examples = []TestExample{{- FilePath: "reply_test_examples/1.md",+ N: 1,NumPaths: 2,},{- FilePath: "reply_test_examples/2.md",+ N: 2,NumPaths: 2,},{- FilePath: "reply_test_examples/3.md",+ N: 3,NumPaths: 2,},{- FilePath: "reply_test_examples/4.md",+ N: 4,NumPaths: 1,},+ {+ N: 5,+ NumPaths: 2,+ },}func TestReplyTokenCounter(t *testing.T) {for _, example := range examples {- fmt.Println(example.FilePath)+ filePath := fmt.Sprintf("reply_test_examples/%d.md", example.N)+ fmt.Println(filePath)- bytes, err := os.ReadFile(example.FilePath)+ bytes, err := os.ReadFile(filePath)if err != nil {t.Error(err)}@@ -58,6 +63,8 @@ func TestReplyTokenCounter(t *testing.T) {files, tokensByFilePath := counter.FinishAndRead()+ fmt.Printf("%d files: %v\n", len(files), files)+if len(files) != example.NumPaths {t.Error(fmt.Sprintf("Expected %d file paths", example.NumPaths))}diff --git a/shared/reply_test_examples/5.md b/shared/reply_test_examples/5.mdnew file mode 100644index 00000000..f68314f6--- /dev/null+++ b/shared/reply_test_examples/5.md@@ -0,0 +1,39 @@+Given that a summarization utility exists, the plan can be further simplified to utilize that. Here is the updated plan:++1. Update the shared/types.go file to introduce a new boolean field indicating if a message has been summarized.++ - shared/types.go:++ ```go+ type ChatCompletionMessage struct {+ // existing fields+ ...+ Summarized bool+ }+ ```++2. Modify the loadConversation function in cli/lib/conversation.go to take advantage of this new field.++ - cli/lib/conversation.go:+ ```go+ // modified part of loadConversation+ ...+ messages = append(messages, openai.ChatCompletionMessage{+ Role: currentRole,+ Content: loadContent(filePath, currentRole),+ Summarized: checkIfMsgSummarized(filePath, currentRole)+ })+ ...+ ```+ - Add the helper functions, checkIfMsgSummarized to check if a given message has already been summarized.++3. In the server/model/proposal/create.go, handle the token limit error by introducing a summarization step.++ - Before calling the CreateChatCompletionStream, check the number of tokens in the request if they exceed the limit.+ - If they do, find the pairs of conversation and attempt to summarize starting from the second.+ - Use the model.Summarize() function provided by the system in step 2 above to handle this summarization.++4. Lastly, handle the superfluous WriteHeader call.+ - For the superfluous WriteHeader call, ensure that all response modifications (like setting headers) are made before calling WriteHeader() and before writing to the response body.++Note: It's still necessary to track which parts of the conversation have already been summarized and avoid summarizing them again if the token limit is still exceeded. This can be achieved by storing a "summarized" flag in each chat message (ChatCompletionMessage).diff --git a/shared/types.go b/shared/types.goindex 973878c6..8b8489d3 100644--- a/shared/types.go+++ b/shared/types.go@@ -25,6 +25,10 @@ type SummarizeResponse struct {FileName string `json:"fileName"`}+type SectionizeRequest struct {+ Text string `json:"text"`+}+type ModelContextPart struct {Name string `json:"name"`Summary string `json:"summary"`