Skip to content

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

sectionization logic -- now disabled, will try diffing

Dane Schneidere6938b3a89c4
diff --git a/cli/cmd/new.go b/cli/cmd/new.go
index fc78d377..a31b9cb1 100644
--- a/cli/cmd/new.go
+++ b/cli/cmd/new.go
@@ -56,6 +56,8 @@ func new(cmd *cobra.Command, args []string) {
name = lib.GetFileNameWithoutExt(summaryResp.FileName)
}
+ fmt.Println("Creating plan '" + name + "'... ")
+
// Check git installed
if !lib.IsCommandAvailable("git") {
log.Fatalln("Error: git is required")
@@ -80,13 +82,17 @@ func new(cmd *cobra.Command, args []string) {
exists := !os.IsNotExist(err)
postfix := 1
+ var nameWithPostfix string
for exists {
postfix += 1
- nameWithPostfix := fmt.Sprintf("%s.%d", name, postfix)
+ nameWithPostfix = fmt.Sprintf("%s.%d", name, postfix)
rootDir = filepath.Join(plandexDir, nameWithPostfix)
_, err = os.Stat(rootDir)
exists = !os.IsNotExist(err)
}
+ if nameWithPostfix != "" {
+ name = nameWithPostfix
+ }
// Create current plan json file with current plan name
planFilePath := filepath.Join(plandexDir, "current_plan.json")
diff --git a/cli/go.mod b/cli/go.mod
index 005ba213..83ed97ad 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -3,7 +3,6 @@ module plandex
go 1.21.0
require (
- github.com/davecgh/go-spew v1.1.1
github.com/looplab/fsm v1.0.1
github.com/spf13/cobra v1.7.0
golang.org/x/term v0.12.0
diff --git a/cli/lib/api.go b/cli/lib/api.go
index 19c55928..7508bc67 100644
--- a/cli/lib/api.go
+++ b/cli/lib/api.go
@@ -249,17 +249,15 @@ func (api *API) Sectionize(text string) (*shared.SectionizeResponse, error) {
}
defer resp.Body.Close()
- body, err := io.ReadAll(resp.Body)
+ rawBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
- fmt.Println("Sectionize response body:")
- fmt.Println(string(body))
-
var sectionized shared.SectionizeResponse
- err = json.Unmarshal(body, &sectionized)
+ err = json.Unmarshal(rawBody, &sectionized)
if err != nil {
+ fmt.Printf("Failed JSON: %s\n", rawBody) // Printing the JSON causing the failure
return nil, err
}
diff --git a/cli/lib/context_load.go b/cli/lib/context_load.go
index 058cd116..1daae8ec 100644
--- a/cli/lib/context_load.go
+++ b/cli/lib/context_load.go
@@ -14,8 +14,8 @@ import (
"strings"
"sync"
"sync/atomic"
+ "time"
- "github.com/davecgh/go-spew/spew"
"github.com/plandex/plandex/shared"
)
@@ -25,7 +25,12 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
// fmt.Fprintf(os.Stderr, "Loading context from %s\n", contextStateFilePath)
- maxTokens := min(params.MaxTokens, shared.MaxTokens)
+ var maxTokens int
+ if params.MaxTokens == -1 {
+ maxTokens = shared.MaxTokens
+ } else {
+ maxTokens = min(params.MaxTokens, shared.MaxTokens)
+ }
func() {
contextStateFile, err := os.Open(contextStateFilePath)
@@ -219,7 +224,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
go func() {
defer wg.Done()
- flattenedPaths := FlattenPaths(inputFilePaths, params, 0)
+ flattenedPaths := FlattenPaths(inputFilePaths, params)
if params.NamesOnly {
body := strings.Join(flattenedPaths, "\n")
@@ -317,9 +322,41 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
}()
- summaryResp, err := Api.Summarize(body)
- if err != nil {
- log.Fatalf("Failed to summarize the file %s: %v", path, err)
+ errCh := make(chan error, 2)
+ summaryCh := make(chan shared.SummarizeResponse, 1)
+ // sectionizeCh := make(chan shared.SectionizeResponse, 1)
+
+ go func() {
+ resp, err := Api.Summarize(body)
+ if err != nil {
+ errCh <- fmt.Errorf("failed to summarize the file %s: %v", path, err)
+ return
+ }
+ summaryCh <- *resp
+ }()
+
+ // go func() {
+ // resp, err := Api.Sectionize(body)
+ // if err != nil {
+ // errCh <- fmt.Errorf("failed to sectionize the file %s: %v", path, err)
+ // return
+ // }
+ // sectionizeCh <- *resp
+ // }()
+
+ // var sectionizeResp shared.SectionizeResponse
+ var summaryResp shared.SummarizeResponse
+
+ // Waiting for the summary response or error
+ for i := 0; i < 1; i++ {
+ select {
+ case err := <-errCh:
+ log.Fatalf("Failed to summarize or sectionize the file %s: %v", path, err)
+ case summaryResp = <-summaryCh:
+ // case sectionizeResp = <-sectionizeCh:
+ case <-time.After(time.Second * 30): // adjust the timeout as necessary
+ log.Fatalf("Timeout while waiting to receive the responses for file %s", path)
+ }
}
// get just the filename
@@ -332,6 +369,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
FilePath: path,
Sha: sha,
NumTokens: numTokens,
+ // SectionEnds: sectionizeResp.SectionEnds,
UpdatedAt: StringTs(),
}
@@ -394,13 +432,6 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
log.Fatalf("Failed to summarize content from URL %s: %v", url, err)
}
- sectionizeResp, err := Api.Sectionize(body)
- if err != nil {
- log.Fatalf("Failed to sectionize content from URL %s: %v", url, err)
- }
- fmt.Println("Sectionize response:")
- spew.Dump(sectionizeResp)
-
contextPart := shared.ModelContextPart{
Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), SanitizeAndClipURL(url, 70)),
Summary: summaryResp.Summary,
@@ -512,7 +543,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {
log.Fatalf("failed to commit submodule updates in root dir: %s\n", err)
}
- fmt.Fprint(os.Stderr, "✅ "+msg+"\n")
+ fmt.Fprint(os.Stderr, "\n✅ "+msg+"\n")
return tokensAdded, totalTokens
}
diff --git a/cli/lib/fs.go b/cli/lib/fs.go
index e0bc9f87..a9fb563e 100644
--- a/cli/lib/fs.go
+++ b/cli/lib/fs.go
@@ -19,6 +19,7 @@ var CurrentPlanName string
var CurrentPlanRootDir string
var PlanSubdir string
var PlanFilesDir string
+var PlanSectionsDir string
var ConversationSubdir string
var ContextSubdir string
@@ -91,6 +92,7 @@ func LoadCurrentPlan() error {
CurrentPlanRootDir = filepath.Join(PlandexDir, CurrentPlanName)
PlanSubdir = filepath.Join(CurrentPlanRootDir, "plan")
PlanFilesDir = filepath.Join(PlanSubdir, "files")
+ PlanSectionsDir = filepath.Join(PlanSubdir, "sections")
ConversationSubdir = filepath.Join(CurrentPlanRootDir, "conversation")
ContextSubdir = filepath.Join(CurrentPlanRootDir, "context")
@@ -140,52 +142,41 @@ func CwdIsPlan() bool {
return parentDir == PlandexDir
}
-func FlattenPaths(fileOrDirPaths []string, params *types.LoadContextParams, depth int) []string {
+func FlattenPaths(fileOrDirPaths []string, params *types.LoadContextParams) []string {
var wg sync.WaitGroup
resPathsChan := make(chan string, len(fileOrDirPaths))
for _, path := range fileOrDirPaths {
- fileInfo, err := os.Stat(path)
- if err != nil {
- log.Fatalf("Failed to read the file %s: %v", path, err)
- }
+ wg.Add(1)
+ go func(p string) {
+ defer wg.Done()
+ depth := 0
- if fileInfo.IsDir() {
- if !params.Recursive {
- log.Fatalf("The path %s is a directory. Please use the --recursive / -r flag to load the directory recursively.", path)
- }
- wg.Add(1)
- go func(p string) {
- defer wg.Done()
- err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- log.Fatalf("Failed to read the file %s: %v", path, err)
+ err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err // Handling error more gracefully
+ }
+
+ if info.IsDir() {
+ if info.Name() == ".git" || info.Name() == ".plandex" {
+ return filepath.SkipDir
}
- if info.IsDir() {
- if info.Name() == ".git" || info.Name() == ".plandex" {
- return filepath.SkipDir
- }
- if depth < params.MaxDepth {
- for _, subPath := range FlattenPaths([]string{path}, params, depth+1) {
- resPathsChan <- subPath
- }
- } else if params.NamesOnly {
- resPathsChan <- path
- }
- } else {
- resPathsChan <- path
+ if depth >= params.MaxDepth {
+ return filepath.SkipDir
}
- return nil
- })
- if err != nil {
- log.Fatalf("Failed to process directory %s: %v", p, err)
+ depth++ // Incrementing depth here
}
- }(path)
- } else {
- resPathsChan <- path
- }
+
+ resPathsChan <- path
+ return nil
+ })
+
+ if err != nil {
+ log.Printf("Failed to process directory %s: %v", p, err) // Logging error instead of fatal
+ }
+ }(path)
}
go func() {
diff --git a/cli/lib/plan.go b/cli/lib/plan.go
index ec260bba..1ba8ee5b 100644
--- a/cli/lib/plan.go
+++ b/cli/lib/plan.go
@@ -22,53 +22,79 @@ func (s *safePlanFiles) Add(key string, value string) {
var planFiles safePlanFiles
-func worker(PlanFilesDir string, srcPath string, info os.FileInfo, err error, errCh chan<- error) {
- if err != nil {
- errCh <- err
- return
- }
- if info.IsDir() {
- return
- }
-
+func worker(dir string, srcPath string, info os.FileInfo, err error, doneCh chan<- error) {
// Compute relative path
- relPath, err := filepath.Rel(PlanFilesDir, srcPath)
+ relPath, err := filepath.Rel(dir, srcPath)
if err != nil {
- errCh <- err
+ doneCh <- err
return
}
// Read file content
content, err := os.ReadFile(srcPath)
if err != nil {
- errCh <- err
+ doneCh <- err
return
}
// Add file content to planFiles with relative path as key
planFiles.Add(relPath, string(content))
+ doneCh <- nil
}
func getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {
planFiles.data = make(map[string]string)
- // Check if filesDir exists
_, err := os.Stat(PlanFilesDir)
- exists := !os.IsNotExist(err)
+ filesDirExists := !os.IsNotExist(err)
+
+ _, err = os.Stat(PlanSectionsDir)
+ sectionsDirExists := !os.IsNotExist(err)
+
+ numFiles := 0
+
+ if filesDirExists || sectionsDirExists {
+ doneCh := make(chan error)
+
+ if filesDirExists {
+ // Enumerate all paths in [planDir]/files
+ err = filepath.Walk(PlanFilesDir, func(srcPath string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if info.IsDir() {
+ return nil
+ }
+ numFiles++
+ go worker(PlanFilesDir, srcPath, info, err, doneCh)
+ return nil
+ })
+ }
- if exists {
- errCh := make(chan error)
- // Enumerate all paths in [planDir]/files
- err = filepath.Walk(PlanFilesDir, func(srcPath string, info os.FileInfo, err error) error {
- go worker(PlanFilesDir, srcPath, info, err, errCh)
- return nil
- })
+ if sectionsDirExists {
+ // Enumerate all paths in [planDir]/sections
+ err = filepath.Walk(PlanSectionsDir, func(srcPath string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+ if info.IsDir() {
+ return nil
+ }
+ numFiles++
+ go worker(PlanSectionsDir, srcPath, info, err, doneCh)
+ return nil
+ })
+ }
- close(errCh)
- for err := range errCh {
- if err != nil {
- fmt.Fprintf(os.Stderr, "Error processing files: %v", err)
- return shared.CurrentPlanFiles{}, err
+ numFinished := 0
+ for numFinished < numFiles {
+ select {
+ case err := <-doneCh:
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error processing files: %v", err)
+ return shared.CurrentPlanFiles{}, err
+ }
+ numFinished++
}
}
}
@@ -77,19 +103,46 @@ func getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {
}
func getCurrentPlanFilePaths() ([]string, error) {
- // Check if filesDir exists
_, err := os.Stat(PlanFilesDir)
- exists := !os.IsNotExist(err)
+ filesDirExists := !os.IsNotExist(err)
+
+ _, err = os.Stat(PlanSectionsDir)
+ sectionsDirExists := !os.IsNotExist(err)
filePaths := make([]string, 0)
- if exists {
+ if filesDirExists {
// Enumerate all paths in [planDir]/files
err = filepath.Walk(PlanFilesDir, func(srcPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
+ if info.IsDir() {
+ return nil
+ }
+
+ filePaths = append(filePaths, srcPath)
+ return nil
+ })
+
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error listing files: %v", err)
+ return []string{}, err
+ }
+ }
+
+ if sectionsDirExists {
+ // Enumerate all paths in [planDir]/sections
+ err = filepath.Walk(PlanSectionsDir, func(srcPath string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+
+ if info.IsDir() {
+ return nil
+ }
+
filePaths = append(filePaths, srcPath)
return nil
})
diff --git a/cli/lib/proposal.go b/cli/lib/proposal.go
index de7221a4..fcd17010 100644
--- a/cli/lib/proposal.go
+++ b/cli/lib/proposal.go
@@ -20,6 +20,7 @@ type key struct {
}
func Propose(prompt string) error {
+ var err error
fmt.Println("Sending prompt... ")
s := spinner.New(spinner.CharSets[14], 100*time.Millisecond)
s.Start()
@@ -45,27 +46,17 @@ func Propose(prompt string) error {
var state *fsm.FSM
var streamFinished bool
var filesFinished bool
- finishedByFile := make(map[string]bool)
+ finishedByPath := make(map[string]bool)
jsonBuffers := make(map[string]string)
- contextTokensByFile := make(map[string]int)
+ numStreamedTokensByPath := make(map[string]int)
replyTokenCounter := shared.NewReplyInfo()
var tokensAddedByFile map[string]int
- currentPlanTokensByFilePath := make(map[string]int)
- currrentPlanTokensPath := filepath.Join(CurrentPlanRootDir, "tokens.json")
- if _, err := os.Stat(currrentPlanTokensPath); os.IsNotExist(err) {
- currentPlanTokensByFilePath = make(map[string]int)
- } else {
- fileBytes, err := os.ReadFile(currrentPlanTokensPath)
- if err != nil {
- return fmt.Errorf("failed to open current plan token count file: %s\n", err)
- }
- err = json.Unmarshal(fileBytes, &currentPlanTokensByFilePath)
- if err != nil {
- return fmt.Errorf("failed to parse current plan token count json: %s\n", err)
- }
+ currentPlanTokensByFilePath, err := loadCurrentPlanTokensByFilePath()
+ if err != nil {
+ return fmt.Errorf("failed to load token counts: %s\n", err)
}
var parentProposalId string
@@ -139,6 +130,8 @@ func Propose(prompt string) error {
running := false
queue := make(chan types.OnStreamPlanParams, 1)
+ var apiReq *shared.PromptRequest
+
var handleStream types.OnStreamPlan
handleStream = func(params types.OnStreamPlanParams) {
if running {
@@ -247,7 +240,12 @@ func Propose(prompt string) error {
// plan build mode started
} else {
- wroteFile, err := receiveFileChunk(content, desc, jsonBuffers, contextTokensByFile, finishedByFile)
+ wroteFile, err := receiveFileChunk(&receiveFileChunkParams{
+ Content: content,
+ JsonBuffers: jsonBuffers,
+ NumStreamedTokensByPath: numStreamedTokensByPath,
+ FinishedByPath: finishedByPath,
+ })
if err != nil {
onError(err)
@@ -262,13 +260,13 @@ func Propose(prompt string) error {
for _, filePath := range files {
contextPart, foundContext := contextByFilePath[filePath]
filePathInPlan := isFilePathInPlan(filePath)
- contextTokens := contextTokensByFile[filePath]
+ numStreamedTokens := numStreamedTokensByPath[filePath]
added := tokensAddedByFile[filePath]
fmtStr := "- %s | %d tokens"
- fmtArgs := []interface{}{filePath, contextTokens}
+ fmtArgs := []interface{}{filePath, numStreamedTokens}
- finished := finishedByFile[filePath]
+ _, finished := finishedByPath[filePath]
if finished {
fmtStr += " | done ✅"
@@ -295,7 +293,14 @@ func Propose(prompt string) error {
}
if wroteFile {
- if len(finishedByFile) == len(files) {
+ fmt.Printf("Wrote %d / %d files", len(finishedByPath), len(files))
+ if len(finishedByPath) == len(files) {
+ err = writeFilesFromSections(apiReq, finishedByPath)
+ if err != nil {
+ onError(err)
+ return
+ }
+
filesFinished = true
if streamFinished {
@@ -310,7 +315,7 @@ func Propose(prompt string) error {
}
- apiReq, err := Api.Propose(prompt, parentProposalId, handleStream)
+ apiReq, err = Api.Propose(prompt, parentProposalId, handleStream)
if err != nil {
backToMain()
return fmt.Errorf("failed to send prompt to server: %s\n", err)
diff --git a/cli/lib/stream.go b/cli/lib/stream.go
index 125413f6..96bdc95c 100644
--- a/cli/lib/stream.go
+++ b/cli/lib/stream.go
@@ -3,101 +3,303 @@ package lib
import (
"encoding/json"
"fmt"
+ "log"
"os"
"path/filepath"
+ "strings"
"github.com/plandex/plandex/shared"
)
-func receiveFileChunk(content string, desc *shared.PlanDescription, jsonBuffers map[string]string, numTokensByFile map[string]int, finishedByFile map[string]bool) (bool, error) {
+type receiveFileChunkParams struct {
+ Content string
+ JsonBuffers map[string]string
+ NumStreamedTokensByPath map[string]int
+ FinishedByPath map[string]bool
+}
+
+func receiveFileChunk(params *receiveFileChunkParams) (bool, error) {
+ content := params.Content
+ jsonBuffers := params.JsonBuffers
+ numStreamedTokensByPath := params.NumStreamedTokensByPath
+ finishedByPath := params.FinishedByPath
+
var chunk shared.PlanChunk
err := json.Unmarshal([]byte(content), &chunk)
if err != nil {
return false, fmt.Errorf("error parsing plan chunk: %v", err)
+ }
+ _, sectionNum, err := shared.SplitSectionPath(chunk.Path)
+ if err != nil {
+ return false, fmt.Errorf("error parsing section number: %v", err)
}
+ isSection := sectionNum >= 0
- var filePath string
- // if chunk.IsExec {
- // filePath = filepath.Join(PlanSubdir, "exec.sh")
- // } else {
- filePath = filepath.Join(PlanFilesDir, chunk.FilePath)
- // }
+ // fmt.Println("path: " + chunk.Path)
+ // fmt.Println("isSection: " + fmt.Sprintf("%t", isSection))
+ // fmt.Println("sectionNum: " + fmt.Sprintf("%d", sectionNum))
+ // fmt.Println("filePath: " + filePath)
- buffer := jsonBuffers[chunk.FilePath]
+ buffer, isFirstWriteToPath := jsonBuffers[chunk.Path]
buffer += chunk.Content
- jsonBuffers[chunk.FilePath] = buffer
+ jsonBuffers[chunk.Path] = buffer
numTokens := int(shared.GetNumTokens(chunk.Content))
- numTokensByFile[chunk.FilePath] += numTokens
+ if isFirstWriteToPath {
+ numStreamedTokensByPath[chunk.Path] = numTokens
+ } else {
+ numStreamedTokensByPath[chunk.Path] += numTokens
+ }
var streamed shared.StreamedFile
- err = json.Unmarshal([]byte(jsonBuffers[chunk.FilePath]), &streamed)
+ err = json.Unmarshal([]byte(jsonBuffers[chunk.Path]), &streamed)
if err == nil {
- // full file content received
- err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)
+ var writeToPath string
+
+ if isSection {
+ // log.Printf("Section. Writing to section path '%s'\n", chunk.Path)
+ writeToPath = filepath.Join(PlanSectionsDir, chunk.Path)
+ } else {
+ // log.Printf("Note section. Writing to file path '%s'\n", chunk.Path)
+ writeToPath = filepath.Join(PlanFilesDir, chunk.Path)
+ }
+
+ // log.Printf("Writing to file or section path '%s'\n", writeToPath)
+ err := os.MkdirAll(filepath.Dir(writeToPath), os.ModePerm)
if err != nil {
+ log.Printf("failed to create directory: %s\n", err)
return false, fmt.Errorf("failed to create directory: %s\n", err)
}
- file, err := os.OpenFile(filePath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY,
+ file, err := os.OpenFile(writeToPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY,
0644)
if err != nil {
- return false, fmt.Errorf("failed to open plan file '%s': %v\n", filePath,
+ log.Printf("failed to open plan file '%s': %v\n", writeToPath, err)
+ return false, fmt.Errorf("failed to open plan file '%s': %v\n", writeToPath,
err)
}
defer file.Close()
_, err = file.WriteString(streamed.Content)
if err != nil {
- return false, fmt.Errorf("failed to write plan file '%s': %v\n", filePath, err)
+ log.Printf("failed to write plan file '%s': %v\n", writeToPath, err)
+ return false, fmt.Errorf("failed to write plan file '%s': %v\n", writeToPath, err)
+ }
+
+ err = writeTokenCounts(&chunk, numStreamedTokensByPath)
+ if err != nil {
+ return false, fmt.Errorf("failed to write token counts: %s\n", err)
}
- currentPlanTokensByFilePath := make(map[string]int)
- currrentPlanTokensPath := filepath.Join(CurrentPlanRootDir, "tokens.json")
+ // fmt.Println("Wrote to file " + filePath)
- // Read the existing token counts if the file exists.
- if _, err := os.Stat(currrentPlanTokensPath); !os.IsNotExist(err) {
- fileBytes, err := os.ReadFile(currrentPlanTokensPath)
- if err != nil {
- return false, fmt.Errorf("failed to read current plan token count file: %s", err)
- }
- err = json.Unmarshal(fileBytes, &currentPlanTokensByFilePath)
- if err != nil {
- return false, fmt.Errorf("failed to parse current plan token count json: %s", err)
- }
+ finishedByPath[chunk.Path] = true
+
+ return true, nil
+
+ } else {
+ return false, nil
+ }
+
+}
+
+func writeTokenCounts(chunk *shared.PlanChunk, numTokensByPath map[string]int) error {
+ currentPlanTokensByPath := make(map[string]int)
+ currrentPlanTokensPath := filepath.Join(CurrentPlanRootDir, "tokens.json")
+
+ // Read the existing token counts if the file exists.
+ if _, err := os.Stat(currrentPlanTokensPath); !os.IsNotExist(err) {
+ fileBytes, err := os.ReadFile(currrentPlanTokensPath)
+ if err != nil {
+ return fmt.Errorf("failed to read current plan token count file: %s", err)
+ }
+ err = json.Unmarshal(fileBytes, &currentPlanTokensByPath)
+ if err != nil {
+ return fmt.Errorf("failed to parse current plan token count json: %s", err)
}
+ }
+
+ // Update token count for this path.
+ currentPlanTokensByPath[chunk.Path] = numTokensByPath[chunk.Path]
- // Update token count for this file.
- currentPlanTokensByFilePath[chunk.FilePath] = numTokensByFile[chunk.FilePath]
+ // Write the updated token counts.
+ tokensFileBytes, err := json.Marshal(currentPlanTokensByPath)
+ if err != nil {
+ return fmt.Errorf("failed to marshal current plan token count json: %s", err)
+ }
+
+ // Open the file for writing with truncation.
+ tokensFile, err := os.OpenFile(currrentPlanTokensPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
+ if err != nil {
+ return fmt.Errorf("failed to open current plan token count file for writing: %s", err)
+ }
+ defer tokensFile.Close()
+
+ _, err = tokensFile.Write(tokensFileBytes)
+ if err != nil {
+ return fmt.Errorf("failed to write current plan token count file: %s", err)
+ }
+
+ return nil
+}
- // Write the updated token counts.
- tokensFileBytes, err := json.Marshal(currentPlanTokensByFilePath)
+func loadCurrentPlanTokensByFilePath() (map[string]int, error) {
+ currentPlanTokensByPath := make(map[string]int)
+ currrentPlanTokensPath := filepath.Join(CurrentPlanRootDir, "tokens.json")
+ if _, err := os.Stat(currrentPlanTokensPath); os.IsNotExist(err) {
+ // do nothing
+ } else {
+ fileBytes, err := os.ReadFile(currrentPlanTokensPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open current plan token count file: %s\n", err)
+ }
+ err = json.Unmarshal(fileBytes, &currentPlanTokensByPath)
if err != nil {
- return false, fmt.Errorf("failed to marshal current plan token count json: %s", err)
+ return nil, fmt.Errorf("failed to parse current plan token count json: %s\n", err)
}
+ }
+
+ currentPlanTokensByFilePath := make(map[string]int)
- // Open the file for writing with truncation.
- tokensFile, err := os.OpenFile(currrentPlanTokensPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644)
+ for path, numTokens := range currentPlanTokensByPath {
+ filePath, _, err := shared.SplitSectionPath(path)
if err != nil {
- return false, fmt.Errorf("failed to open current plan token count file for writing: %s", err)
+ return nil, fmt.Errorf("error parsing section number: %v", err)
}
- defer tokensFile.Close()
+ currentPlanTokensByFilePath[filePath] += numTokens
+ }
- _, err = tokensFile.Write(tokensFileBytes)
+ return currentPlanTokensByFilePath, nil
+}
+
+func writeFilesFromSections(apiReq *shared.PromptRequest, finishedByPath map[string]bool) error {
+ log.Println("Starting writeFilesFromSections...")
+
+ var filePaths []string
+
+ for path := range finishedByPath {
+ filePath, sectionNum, err := shared.SplitSectionPath(path)
if err != nil {
- return false, fmt.Errorf("failed to write current plan token count file: %s", err)
+ return fmt.Errorf("error parsing section number: %v", err)
+ }
+ if sectionNum >= 0 {
+ filePaths = append(filePaths, filePath)
}
+ }
- // fmt.Println("Wrote to file " + filePath)
+ log.Printf("File paths to process: %v\n", filePaths)
- finishedByFile[chunk.FilePath] = true
+ errCh := make(chan error)
+ doneCh := make(chan bool)
+ numWritten := 0
- return true, nil
+ for _, filePath := range filePaths {
+ go func(filePath string) {
+ log.Printf("Processing file: %s\n", filePath)
- } else {
- return false, nil
+ origPath := filepath.Join(".", filePath)
+ planFilesPath := filepath.Join(PlanFilesDir, filePath)
+
+ // read the original file
+ origBytes, err := os.ReadFile(origPath)
+ if err != nil {
+ log.Printf("failed to read original file '%s': %v\n", origPath, err)
+ errCh <- fmt.Errorf("failed to read original file '%s': %v\n", origPath, err)
+ return
+ }
+ origContent := string(origBytes)
+
+ // get the full sections from the original file
+ var contextPart *shared.ModelContextPart
+ for _, part := range apiReq.ModelContext {
+ if part.FilePath == filePath {
+ contextPart = &part
+ break
+ }
+ }
+ if contextPart == nil {
+ log.Printf("failed to find context part for file '%s'\n", filePath)
+ errCh <- fmt.Errorf("failed to find context part for file '%s'\n", filePath)
+ return
+ }
+ origSections := shared.GetFullSections(origContent, contextPart.SectionEnds)
+ fileContent := origContent
+
+ // list existing section files for this file path
+ sectionsDir := filepath.Dir(filepath.Join(PlanSectionsDir, filePath))
+ sectionFiles, err := os.ReadDir(sectionsDir)
+ if err != nil {
+ log.Printf("failed to read section files for '%s': %v\n", filePath, err)
+ errCh <- fmt.Errorf("failed to read section files for '%s': %v\n", filePath, err)
+ return
+ }
+ for _, sectionFile := range sectionFiles {
+ name := sectionFile.Name()
+ sectionPath := filepath.Join(filepath.Dir(filePath), name)
+
+ _, sectionNum, err := shared.SplitSectionPath(sectionPath)
+ if err != nil || sectionNum < 0 {
+ log.Printf("failed to parse section number for '%s': %v\n", sectionPath, err)
+ errCh <- fmt.Errorf("failed to parse section number for '%s': %v\n", sectionPath, err)
+ return
+ }
+
+ if sectionNum >= len(origSections) {
+ log.Printf("failed to find section %d in file '%s'\n", sectionNum, filePath)
+ errCh <- fmt.Errorf("failed to find section %d in file '%s'\n", sectionNum, filePath)
+ return
+ }
+
+ origSection := origSections[sectionNum]
+
+ // read the section file
+ sectionBytes, err := os.ReadFile(filepath.Join(sectionsDir, name))
+ if err != nil {
+ log.Printf("failed to read section file '%s': %v\n", sectionPath, err)
+ errCh <- fmt.Errorf("failed to read section file '%s': %v\n", sectionPath, err)
+ return
+ }
+
+ sectionContent := string(sectionBytes)
+
+ // replace the section in the original file
+ fileContent = strings.Replace(fileContent, origSection, sectionContent, 1)
+ }
+
+ // ensure directory exists
+ err = os.MkdirAll(filepath.Dir(planFilesPath), os.ModePerm)
+ if err != nil {
+ log.Printf("failed to create directory: %s\n", err)
+ errCh <- fmt.Errorf("failed to create directory: %s\n", err)
+ return
+ }
+
+ // write the file
+ err = os.WriteFile(planFilesPath, []byte(fileContent), 0644)
+ if err != nil {
+ log.Printf("failed to write file '%s': %v\n", planFilesPath, err)
+ errCh <- fmt.Errorf("failed to write file '%s': %v\n", planFilesPath, err)
+ return
+ }
+
+ // log.Printf("File written successfully: %s\n", planFilesPath)
+ doneCh <- true
+ }(filePath)
}
+ for numWritten < len(filePaths) {
+ select {
+ case err := <-errCh:
+ return err
+ case <-doneCh:
+ numWritten++
+ // log.Printf("Number of files written: %d\n", numWritten)
+ }
+ }
+
+ // log.Println("Completed writeFilesFromSections.")
+
+ return nil
}
diff --git a/server/model/fix_json.go b/server/model/fix_json.go
new file mode 100644
index 00000000..848e52a3
--- /dev/null
+++ b/server/model/fix_json.go
@@ -0,0 +1,87 @@
+package model
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/davecgh/go-spew/spew"
+ "github.com/sashabaranov/go-openai"
+ "github.com/sashabaranov/go-openai/jsonschema"
+)
+
+type fixed struct {
+ FixedJson string `json:"fixedJson"`
+}
+
+func FixJson(invalidJson string) ([]byte, error) {
+ messages := []openai.ChatCompletionMessage{
+ {
+ Role: openai.ChatMessageRoleSystem,
+ Content: `You are an AI JSON fixer. You take invalid JSON and fix it so that it becomes valid. You should call the 'fixed' function with the 'fixedJson' parameter, a string containing valid JSON. You must *always* call the 'fixed' function and never call any other function.`,
+ },
+ {
+ Role: openai.ChatMessageRoleUser,
+ Content: fmt.Sprintf("Fix the following invalid JSON and call the 'fixed' function with the result:\n\n%s",
+ invalidJson),
+ },
+ }
+
+ resp, err := Client.CreateChatCompletion(
+ context.Background(),
+ openai.ChatCompletionRequest{
+ Model: openai.GPT4,
+ Functions: []openai.FunctionDefinition{{
+ Name: "fixed",
+ Parameters: &jsonschema.Definition{
+ Type: jsonschema.Object,
+ Properties: map[string]jsonschema.Definition{
+ "fixedJson": {
+ Type: jsonschema.String,
+ Description: "Valid json.",
+ Items: &jsonschema.Definition{
+ Type: jsonschema.String,
+ },
+ },
+ },
+ Required: []string{"fixedJson"},
+ },
+ }},
+ Messages: messages,
+ })
+
+ if err != nil {
+ return nil, err
+ }
+
+ spew.Dump(resp)
+
+ var byteRes []byte
+ for _, choice := range resp.Choices {
+ if choice.FinishReason == "function_call" && choice.Message.Role == "assistant" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "fixed" {
+ fnCall := choice.Message.FunctionCall
+ byteRes = []byte(fnCall.Arguments)
+ }
+ }
+
+ if len(byteRes) == 0 {
+ return nil, fmt.Errorf("no 'fixed' function call found in response")
+ }
+
+ // Clean the body of the response
+ // cleanBody, err := shared.CleanJson(byteRes)
+ // if err != nil {
+ // return nil, fmt.Errorf("error cleaning JSON: %w", err)
+ // }
+
+ // validate the JSON response
+ var fixResp fixed
+ err = json.Unmarshal(byteRes, &fixResp)
+
+ if err != nil {
+ fmt.Printf("Failed JSON: %s\n", byteRes) // Printing the JSON causing the failure
+ return nil, fmt.Errorf("error unmarshalling JSON: %w", err)
+ }
+
+ return byteRes, nil
+}
diff --git a/server/model/context.go b/server/model/lib/context.go
similarity index 55%
rename from server/model/context.go
rename to server/model/lib/context.go
index f36b529a..ca5494ac 100644
--- a/server/model/context.go
+++ b/server/model/lib/context.go
@@ -1,4 +1,4 @@
-package model
+package lib
import (
"fmt"
@@ -13,22 +13,33 @@ func FormatModelContext(context shared.ModelContext) (string, int) {
for _, part := range context {
var message string
var fmtStr string
- var labelArg string
+ var args []any
if part.FilePath != "" {
- fmtStr = "\n\n- %s:\n\n```%s```"
- labelArg = part.FilePath
+ if len(part.SectionEnds) > 0 {
+
+ sections := shared.GetFullSections(part.Body, part.SectionEnds)
+
+ for i, section := range sections {
+ fmtStr += "\n\n- %s:\n\n```\n%s\n```"
+ args = append(args, fmt.Sprintf("%s-%d", part.FilePath, i), section)
+ }
+
+ } else {
+ fmtStr = "\n\n- %s:\n\n```\n%s\n```"
+ args = append(args, part.FilePath, part.Body)
+ }
} else if part.Url != "" {
- fmtStr = "\n\n- %s:\n\n```%s```"
- labelArg = part.Url
+ fmtStr = "\n\n- %s:\n\n```\n%s\n```"
+ args = append(args, part.Url, part.Body)
} else {
- fmtStr = "\n\n- content%s:\n\n```%s```"
- labelArg = part.Name
+ fmtStr = "\n\n- content%s:\n\n```\n%s\n```"
+ args = append(args, part.Name, part.Body)
}
- numTokens += part.NumTokens + shared.GetNumTokens(fmt.Sprintf(fmtStr, labelArg, ""))
+ numTokens += part.NumTokens + shared.GetNumTokens(fmt.Sprintf(fmtStr, ""))
- message = fmt.Sprintf(fmtStr, labelArg, part.Body)
+ message = fmt.Sprintf(fmtStr, args...)
contextMessages = append(contextMessages, message)
}
diff --git a/server/model/lib/sections.go b/server/model/lib/sections.go
new file mode 100644
index 00000000..e253f665
--- /dev/null
+++ b/server/model/lib/sections.go
@@ -0,0 +1,37 @@
+package lib
+
+import (
+ "strings"
+)
+
+func GetSectionEnds(text string, lines []string) []int {
+ var indexes []int
+ currentPosition := 0 // Variable to keep track of the current position in the text
+
+ for _, line := range lines {
+ // Finding the index of the line in the text, starting from currentPosition
+ index := strings.Index(text[currentPosition:], line)
+
+ if index != -1 {
+ // Since we are slicing the text, we need to add currentPosition to get the actual index
+ index += currentPosition
+
+ // Updating the currentPosition to be after the current match
+ currentPosition = index + len(line)
+
+ // Appending the actual index of the match
+ indexes = append(indexes, index)
+ }
+ }
+
+ return indexes[1:] // Removing the first index since it's always 0
+}
+
+func CleanSectionJson(json []byte) []byte {
+ s := string(json)
+
+ strings.ReplaceAll(s, `\n`, "")
+ strings.ReplaceAll(s, `\t`, "")
+
+ return []byte(s)
+}
diff --git a/server/model/proposal/confirm.go b/server/model/proposal/confirm.go
index 867ee835..62dd12b9 100644
--- a/server/model/proposal/confirm.go
+++ b/server/model/proposal/confirm.go
@@ -70,13 +70,13 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {
fmtArgs := []interface{}{}
if fileContext != nil {
- fmtStr += "Original file %s:\n```\n%s\n```"
+ fmtStr += "Original %s:\n```\n%s\n```"
fmtArgs = []interface{}{filePath, fileContext.Body}
}
currentState := proposal.Request.CurrentPlan.Files[filePath]
if currentState != "" {
- fmtStr += "\nCurrent state of file %s in the plan:\n```\n%s\n```"
+ fmtStr += "\nCurrent state of %s in the plan:\n```\n%s\n```"
fmtArgs = append(fmtArgs, filePath, currentState)
}
@@ -95,20 +95,25 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {
openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: fmt.Sprintf(`
- Based on your previous response, call the 'writeFile' function with the full content of the file %s as raw text, including any updates. If the current state of the file within the plan is included above, apply your changes to the *current file*, not the original file. If there is no current file, apply your changes to the original file. You must include the entire file and not leave anything out, even if it is already present the source file. Do not include any placeholders or references to the original file. Output the updated entire file. Only call the 'writeFile' function in your reponse. Don't call any other function.
+ Based on your previous response, call the 'write' function with the full content of the file or file section %s as raw text, including any updates. If the current state of the file+section within the plan is included above, apply your changes to the *current file+section*, not the original file+section. If there is no current file+section, apply your changes to the original file+section. You must include the entire file+section and not leave anything out, even if it is already present the original file+section. Do not include any placeholders or references to the original file+section. Output the updated entire file. Only call the 'write' function in your reponse. Don't call any other function.
`, filePath),
})
+ fmt.Println("Calling model for file: " + filePath)
+ for _, msg := range fileMessages {
+ fmt.Printf("%s: %s\n", msg.Role, msg.Content)
+ }
+
modelReq := openai.ChatCompletionRequest{
Model: openai.GPT4,
Functions: []openai.FunctionDefinition{{
- Name: "writeFile",
+ Name: "write",
Parameters: &jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"content": {
Type: jsonschema.String,
- Description: "The full content of the file, including any updates from the previous response, as raw text",
+ Description: "The full content of the file+section, including any updates from the previous response, as raw text",
},
},
Required: []string{"content"},
@@ -182,7 +187,7 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {
}
} else {
- onError(fmt.Errorf("Stream finished without 'writeFile' function call. Reason: %s", choice.FinishReason))
+ onError(fmt.Errorf("Stream finished without 'write' function call. Reason: %s", choice.FinishReason))
return
}
@@ -193,7 +198,7 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {
delta := response.Choices[0].Delta
if delta.FunctionCall == nil {
- fmt.Printf("\nStream received data not for 'writeFile' function call")
+ fmt.Printf("\nStream received data not for 'write' function call")
continue
} else {
content = delta.FunctionCall.Arguments
@@ -204,8 +209,8 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {
})
chunk := &shared.PlanChunk{
- FilePath: filePath,
- Content: content,
+ Path: filePath,
+ Content: content,
}
// fmt.Printf("%s: %s", filePath, content)
diff --git a/server/model/proposal/create.go b/server/model/proposal/create.go
index 07c9f3e9..9cf72618 100644
--- a/server/model/proposal/create.go
+++ b/server/model/proposal/create.go
@@ -8,6 +8,7 @@ import (
"time"
"plandex-server/model"
+ "plandex-server/model/lib"
"plandex-server/types"
"github.com/google/uuid"
@@ -15,9 +16,7 @@ import (
"github.com/sashabaranov/go-openai"
)
-const systemMessageHead = `You are Plandex, an AI programming and system administration assistant. You offer a structured, versioned, and iterative approach to AI-driven development.
-
- You and the programmer collaborate to create a 'plan' for the task at hand. A plan is a set of files with an attached context.` +
+const systemMessageHead = `You are Plandex, an AI programming and system administration assistant. You and the programmer collaborate to create a 'plan' for the task at hand. A plan is a set of files with an attached context.` +
"Your instructions:\n\n```\n" +
@@ -29,17 +28,17 @@ const systemMessageHead = `You are Plandex, an AI programming and system adminis
- Ask the user for more information or context and stop there.
2. Decide whether this task is small enough to be completed in a single response.
- a. If so, write out the code to complete the task. Precede the code block with the file path like this '- file_path:'--for example:
- - src/main.rs:
- - lib/utils.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.*
+ a. If so, write out the code to complete the task. Precede the code block with the file path + section like this '- file_path-section_num:'--for example:
+ - src/main.rs-1:
+ - lib/utils.go-2:
+ - main.py-8:
+ File+section paths should always come *before* the opening triple backticks of a code block. They should *not* be included in the code block itself.
+ File+section 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.*
b. If not:
- Explicitly say "I will break this large task into subtasks."
- Divide the task into smaller subtasks and list them in a numbered list. Stop there.
- Always precede code blocks the file path as described above in 2a. Code must *always* be labelled with the path. You can have multiple code blocks labelled with the same file path.
+ Always precede code blocks the file path+section as described above in 2a. Code must *always* be labelled with the path+section.
Every file you reference 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/utils.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/utils.go'.
@@ -47,13 +46,15 @@ const systemMessageHead = `You are Plandex, an AI programming and system adminis
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.
+ An exception to the above instructions on comments are if a file+section block is empty because you removed everything in it. In that case, leave a brief one-line comment starting with 'Plandex: removed' that says what was removed so that the file+section block isn't empty.
+
At the end of a plan, you can suggest additional iterations to make the plan better. You can also ask the user to load more files or information into context if it would help you make a better plan.` +
"\n```\n\n" +
"User-provided context:"
var systemHeadNumTokens = shared.GetNumTokens(systemMessageHead)
-const promptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\nPlease respond according to the 'Your instructions' section above. Remember to precede code blocks with the file path *exactly* as described in 2a. Do not use any other formatting for file paths."
+const promptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\nPlease respond according to the 'Your instructions' section above. Remember to precede code blocks with the file path+section *exactly* as described in 2a. Do not use any other formatting for file paths or file sections."
var promptWrapperTokens = shared.GetNumTokens(fmt.Sprintf(promptWrapperFormatStr, ""))
@@ -67,7 +68,7 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) error
return nil
}
- contextText, contextTokens := model.FormatModelContext(req.ModelContext)
+ contextText, contextTokens := lib.FormatModelContext(req.ModelContext)
systemMessageText := systemMessageHead + contextText
systemMessage := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleSystem,
diff --git a/server/model/proposal/describe.go b/server/model/proposal/describe.go
index 686a7bf5..f957977d 100644
--- a/server/model/proposal/describe.go
+++ b/server/model/proposal/describe.go
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"plandex-server/model"
- "strings"
"github.com/plandex/plandex/shared"
"github.com/sashabaranov/go-openai"
@@ -77,13 +76,5 @@ func genPlanDescriptionJson(proposalId string, ctx context.Context) (*shared.Pla
return nil, err
}
- for i, filePath := range planDesc.Files {
- filePath = strings.TrimSpace(filePath)
- filePath = strings.TrimPrefix(filePath, "-")
- filePath = strings.TrimSpace(filePath)
- planDesc.Files[i] = filePath
- fmt.Println("file path: " + filePath)
- }
-
return &planDesc, nil
}
diff --git a/server/model/proposal/lorem_ipsum.go b/server/model/proposal/lorem_ipsum.go
index e6962820..0ced5613 100644
--- a/server/model/proposal/lorem_ipsum.go
+++ b/server/model/proposal/lorem_ipsum.go
@@ -70,7 +70,7 @@ func streamLoremIpsum(onStream types.OnStreamFunc) {
func streamFilesLoremIpsum(onStream types.OnStreamFunc) {
writeChunk := func(filePath string, isExec bool, content string) {
- chunk := shared.PlanChunk{FilePath: filePath, Content: content /*IsExec: isExec*/}
+ chunk := shared.PlanChunk{Path: filePath, Content: content}
chunkJson, _ := json.Marshal(chunk)
onStream(string(chunkJson), nil)
time.Sleep(50 * time.Millisecond) // Adding a small delay between files for effect
diff --git a/server/model/sectionize.go b/server/model/sectionize.go
index f8f6929d..519a9476 100644
--- a/server/model/sectionize.go
+++ b/server/model/sectionize.go
@@ -5,20 +5,25 @@ import (
"encoding/json"
"fmt"
- "plandex-server/types"
+ "plandex-server/model/lib"
"github.com/davecgh/go-spew/spew"
+ "github.com/plandex/plandex/shared"
"github.com/sashabaranov/go-openai"
"github.com/sashabaranov/go-openai/jsonschema"
)
+type sectionizeResult = struct {
+ Sections []string `json:"sections"`
+}
+
func Sectionize(text string) ([]byte, error) {
resp, err := Client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
- Model: openai.GPT3Dot5Turbo16K,
+ Model: openai.GPT4,
Functions: []openai.FunctionDefinition{{
- Name: "sectionize",
+ Name: "sectionized",
Parameters: &jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
@@ -35,12 +40,37 @@ func Sectionize(text string) ([]byte, error) {
}},
Messages: []openai.ChatCompletionMessage{
{
- Role: openai.ChatMessageRoleSystem,
- Content: "You are an AI specialized in processing text and code, dividing them into logical sections based on their content. You should call the 'sectionize' function with an array of sections. Make sure the sections add up to the original text, don't overlap, don't leave any gaps, and are in the right order (i.e. the first section should come first, the second section should come second, etc.). If the text is code, try not to split up functions unless they are very long. Only call the 'sectionize' function and don't call any other function.",
+ Role: openai.ChatMessageRoleSystem,
+ Content: `You are an AI specialized in breaking code up into sections based on purpose and functionality.
+
+ Your instructions:
+
+ 1. Break up the provided text into sections based on purpose and functionality.
+ 1a. If the text is code, try to group together related operations.
+ 1b. If the text is natural language, try to group together related ideas.
+
+ 2. Call the 'sectionized' function with the the 'sections' parameter. For each section, provide a string containing *just the first line that begins the section.*
+
+ When breaking up the text into sections, follow these guidelines.
+ - Sections should be roughly 50-100 lines in size.
+ - A file should be broken up into no more than 5-10 sections.
+ - For a short file, it's good to have a small number of sections, like 2-3 sections.
+ - Sections should be understandable in isolation.
+ - If in doubt, lean towards fewer sections rather than more sections.
+ - Blocks of code that are commented out should be given their own sections.
+ - Lean towards not breaking up functions or methods into multiple sections unless they are very long.
+ - Lean towards not breaking up variable definitions, type definitions, or control flow blocks into multiple sections unless they are very long.
+ - Lean towards not breaking up comment blocks into multiple sections unless they are very long.
+ - Lean towards not breaking up paragraphs into multiple sections unless they are very long.
+ - Lean towards keeping 'header' information like package declarations, imports, and initialization logic together in one section unless it would be very long.
+ - If there's no way to break up the text according to these instructions, call 'sectionized' with an empty array.
+
+ Important: you *must always* call the 'sectionized' function and never call any other function.
+ `,
},
{
Role: openai.ChatMessageRoleUser,
- Content: fmt.Sprintf("Sectionize the text below, identifying logical sections, and call 'sectionize' with the sectionized results.\n\nBelow is the text to be sectionized:\n\n%s",
+ Content: fmt.Sprintf("Break up the following text into sections as described in your instructions above and call the 'sectionized' function with the result: \n\n%s",
text),
},
},
@@ -50,25 +80,42 @@ func Sectionize(text string) ([]byte, error) {
return nil, err
}
+ spew.Dump(resp)
+
var byteRes []byte
for _, choice := range resp.Choices {
- if choice.FinishReason == "stop" && choice.Message.Role == "assistant" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "sectionize" {
+ if choice.FinishReason == "function_call" && choice.Message.Role == "assistant" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "sectionized" {
fnCall := choice.Message.FunctionCall
byteRes = []byte(fnCall.Arguments)
}
}
if len(byteRes) == 0 {
- return nil, fmt.Errorf("no 'sectionize' function call found in response")
+ return nil, fmt.Errorf("no 'sectionized' function call found in response")
}
+ // Clean the body of the response
+ cleanBody := lib.CleanSectionJson(byteRes)
+
// validate the JSON response
- var sectionizeResp types.SectionizeResponse
- if err := json.Unmarshal(byteRes, &sectionizeResp); err != nil {
- return nil, err
+ var res sectionizeResult
+ err = json.Unmarshal(cleanBody, &res)
+
+ if err != nil {
+ fmt.Printf("Failed JSON: %s\n", cleanBody) // Printing the JSON causing the failure
+ return nil, fmt.Errorf("error unmarshalling JSON: %w", err)
+ }
+
+ // spew.Dump(sectionizedResp)
+
+ sectionizedResp := shared.SectionizeResponse{
+ SectionEnds: lib.GetSectionEnds(text, res.Sections),
}
- spew.Dump(sectionizeResp)
+ byteRes, err = json.Marshal(sectionizedResp)
+ if err != nil {
+ return nil, err
+ }
return byteRes, nil
}
diff --git a/server/model/summarize.go b/server/model/summarize.go
index d2e6decd..d89d4927 100644
--- a/server/model/summarize.go
+++ b/server/model/summarize.go
@@ -12,6 +12,7 @@ import (
)
func Summarize(text string) ([]byte, int, error) {
+
resp, err := Client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
@@ -27,7 +28,7 @@ func Summarize(text string) ([]byte, int, error) {
},
"summary": {
Type: jsonschema.String,
- Description: "A concise summary of the text.",
+ Description: "A brief summary of the text. A few sentences at most",
},
"fileName": {
Type: jsonschema.String,
diff --git a/server/types/plan.go b/server/types/plan.go
index f7bdbac6..931d6cfb 100644
--- a/server/types/plan.go
+++ b/server/types/plan.go
@@ -1,22 +1,14 @@
package types
type Plan struct {
- ProposalId string
- NumFiles int
- Files map[string]string
- // HasExec bool
- // Exec string
- // ExecErr error
- // ExecFinished bool
+ ProposalId string
+ NumFiles int
+ Files map[string]string
FilesFinished map[string]bool
FileErrs map[string]error
ProposalStage
}
func (s *Plan) DidFinish() bool {
- // if s.HasExec && !s.ExecFinished {
- // return false
- // }
-
return len(s.FilesFinished) == int(s.NumFiles)
}
diff --git a/shared/reply.go b/shared/reply.go
index 7b0e1fc9..6ca557bc 100644
--- a/shared/reply.go
+++ b/shared/reply.go
@@ -34,6 +34,10 @@ func (r *replyInfo) AddToken(token string, addToTotal bool) {
if addToTotal {
r.numTokens++
+
+ if r.currentFilePath != "" {
+ r.numTokensByFile[r.currentFilePath]++
+ }
}
if token == "\n" {
@@ -124,7 +128,6 @@ func (r *replyInfo) AddToken(token string, addToTotal bool) {
} else {
r.files[r.currentFilePath] = true
r.currentFileLines = append(r.currentFileLines, prevFullLine)
- r.numTokensByFile[r.currentFilePath]++
// r.contentByFile[r.currentFilePath] += prevFullLine + "\n"
// fmt.Printf("Added %d tokens to %s\n", tokens, r.currentFilePath) // Logging token addition
diff --git a/shared/sections.go b/shared/sections.go
new file mode 100644
index 00000000..6ee72fe2
--- /dev/null
+++ b/shared/sections.go
@@ -0,0 +1,54 @@
+package shared
+
+import (
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+func GetFullSections(text string, sectionEnds []int) []string {
+ var sections []string
+ startIndex := 0
+
+ for _, endIndex := range sectionEnds {
+ // If endIndex goes beyond text length, clip it to text length
+ if endIndex > len(text) {
+ endIndex = len(text)
+ }
+
+ // Extract section and append to sections
+ section := text[startIndex:endIndex]
+ sections = append(sections, section)
+
+ // Update startIndex for the next iteration
+ startIndex = endIndex
+ }
+
+ // Adding the last section if there's any remaining text
+ if startIndex < len(text) {
+ sections = append(sections, text[startIndex:])
+ }
+
+ return sections
+}
+
+var sectionRegex = regexp.MustCompile(`-\d+$`)
+
+func SplitSectionPath(path string) (string, int, error) {
+ var sectionNum int = -1
+ var err error
+ sectionNumStr := strings.ReplaceAll(sectionRegex.FindString(path), "-", "")
+
+ if sectionNumStr == "" {
+ return path, -1, nil
+ }
+
+ if sectionNumStr != "" {
+ sectionNum, err = strconv.Atoi(sectionNumStr)
+ if err != nil {
+ return "", -1, err
+ }
+ }
+
+ return path[:len(path)-(len(sectionNumStr)+1)], sectionNum, nil
+}
diff --git a/shared/tokens.go b/shared/tokens.go
index eb68ab6c..6f792bda 100644
--- a/shared/tokens.go
+++ b/shared/tokens.go
@@ -7,8 +7,8 @@ import (
"github.com/pkoukk/tiktoken-go"
)
-const MaxTokens int = 7000 // leave room for the model ouput
-const MaxContextTokens int = 6000 // leave room for the conversation history
+const MaxTokens int = 7500 // leave room for the model ouput
+const MaxContextTokens int = 6500 // leave room for the conversation history
func GetNumTokens(text string) (numTokens int) {
tkm, err := tiktoken.EncodingForModel("gpt-4")
diff --git a/shared/types.go b/shared/types.go
index 572e61a5..d36eab1e 100644
--- a/shared/types.go
+++ b/shared/types.go
@@ -39,18 +39,19 @@ type SectionizeRequest struct {
}
type SectionizeResponse struct {
- Sections []string `json:"sections"`
+ SectionEnds []int `json:"sectionEnds"`
}
type ModelContextPart struct {
- Name string `json:"name"`
- Summary string `json:"summary"`
- Body string `json:"body"`
- Url string `json:"url"`
- FilePath string `json:"filePath"`
- Sha string `json:"sha"`
- NumTokens int `json:"numTokens"`
- UpdatedAt string `json:"updatedAt"`
+ Name string `json:"name"`
+ Summary string `json:"summary"`
+ Body string `json:"body"`
+ Url string `json:"url"`
+ FilePath string `json:"filePath"`
+ Sha string `json:"sha"`
+ NumTokens int `json:"numTokens"`
+ UpdatedAt string `json:"updatedAt"`
+ SectionEnds []int `json:"sectionEnds"`
}
type ModelContext []ModelContextPart
@@ -63,9 +64,9 @@ type ModelContextState struct {
}
type PlanChunk struct {
- Type string `json:"type"`
- FilePath string `json:"filePath"`
- Content string `json:"content"`
+ Type string `json:"type"`
+ Path string `json:"path"`
+ Content string `json:"content"`
}
type PlanDescription struct {