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
some cleanup and refactoring, splitting of text summary and filename model calls, basis for conversation summarization when exceeding context limit
Dane Schneider5713c5059264
diff --git a/cli/cmd/context_rm.go b/cli/cmd/context_rm.goindex 1a125cba..5ef663a0 100644--- a/cli/cmd/context_rm.go+++ b/cli/cmd/context_rm.go@@ -30,12 +30,6 @@ func contextRm(cmd *cobra.Command, args []string) {}defer contextStateFile.Close()- // var contextState shared.ModelContextState-- // data, err := io.ReadAll(contextStateFile)- // if err != nil {- // log.Fatalf("Error reading file: %v", err)- // }}func init() {diff --git a/cli/cmd/diffs.go b/cli/cmd/diffs.goindex f5384dcc..38b7156c 100644--- a/cli/cmd/diffs.go+++ b/cli/cmd/diffs.go@@ -48,8 +48,6 @@ func showDiffs() error {}defer os.RemoveAll(tempDir) // Cleanup temporary directory- fmt.Println("Temp directory:", tempDir)-// Copy relevant project files to the temporary directorypaths, err := lib.GetCurrentPlanFilePaths()ch := make(chan error)diff --git a/cli/cmd/revert.go b/cli/cmd/revert.godeleted file mode 100644index 5445d56e..00000000--- a/cli/cmd/revert.go+++ /dev/null@@ -1,21 +0,0 @@-package cmd--import (- "github.com/spf13/cobra"-)--var revertCmd = &cobra.Command{- Use: "revert [commit-sha]",- Short: "Revert plan to a previous commit",- Long: `Revert plan to a previous commit`,- Args: cobra.ExactArgs(1),- Run: revert,-}--func init() {- RootCmd.AddCommand(revertCmd)-}--func revert(cmd *cobra.Command, args []string) {--}diff --git a/cli/cmd/rewind.go b/cli/cmd/rewind.gonew file mode 100644index 00000000..ecbb9554--- /dev/null+++ b/cli/cmd/rewind.go@@ -0,0 +1,30 @@+package cmd++import (+ "github.com/spf13/cobra"+)++// rewindCmd represents the rewind command+var rewindCmd = &cobra.Command{+ Use: "rewind [step]",+ Aliases: []string{"rw"},+ Short: "Rewind the plan to an earlier state",+ Long: `By default it rollback the conversation by one message. It can accept 'step' to rollback by more steps. It can also accept --sha to rollback to a specific version in the plan git history.`,+ Args: cobra.MaximumNArgs(1),+ Run: rewind,+}++var sha string++func init() {+ // Add rewind command+ RootCmd.AddCommand(rewindCmd)++ // Add sha flag+ rewindCmd.Flags().StringVar(&sha, "sha", "", "Specify a commit sha to rewind to")+}++func rewind(cmd *cobra.Command, args []string) {+ // Argument parsing and rewind logic will be implemented++}diff --git a/cli/cmd/root.go b/cli/cmd/root.goindex cb8788cc..9abbbd8d 100644--- a/cli/cmd/root.go+++ b/cli/cmd/root.go@@ -10,7 +10,7 @@ import (// RootCmd represents the base command when called without any subcommandsvar RootCmd = &cobra.Command{Use: `plandex [command] [flags]`,- Short: "Plandex CLI: generate, iterate, and execute code with AI",+ Short: "Plandex: iterative development with AI",Run: func(cmd *cobra.Command, args []string) {run(cmd, args)},diff --git a/cli/lib/api.go b/cli/lib/api.goindex 8575e0fc..389fb5f0 100644--- a/cli/lib/api.go+++ b/cli/lib/api.go@@ -198,10 +198,10 @@ func (api *API) Abort(proposalId string) error {return nil}-func (api *API) Summarize(text string) (*shared.SummarizeResponse, error) {+func (api *API) ShortSummary(text string) (*shared.ShortSummaryResponse, error) {serverUrl := apiHost + "/summarize"- payload := shared.SummarizeRequest{+ payload := shared.ShortSummaryRequest{Text: text,}jsonData, err := json.Marshal(payload)@@ -220,10 +220,10 @@ func (api *API) Summarize(text string) (*shared.SummarizeResponse, error) {return nil, err}- // fmt.Println("Summarize response body:")+ // fmt.Println("ShortSummary response body:")// fmt.Println(string(body))- var summarized shared.SummarizeResponse+ var summarized shared.ShortSummaryResponseerr = json.Unmarshal(body, &summarized)if err != nil {return nil, err@@ -232,17 +232,36 @@ func (api *API) Summarize(text string) (*shared.SummarizeResponse, error) {return &summarized, nil}-func readUntilSeparator(reader *bufio.Reader, separator string) (string, error) {- var result []byte- sepBytes := []byte(separator)- for {- b, err := reader.ReadByte()- if err != nil {- return string(result), err- }- result = append(result, b)- if len(result) >= len(sepBytes) && bytes.HasSuffix(result, sepBytes) {- return string(result[:len(result)-len(separator)]), nil- }+func (api *API) FileName(text string) (*shared.FileNameResponse, error) {+ serverUrl := apiHost + "/filename"++ payload := shared.FileNameRequest{+ Text: text,+ }+ jsonData, err := json.Marshal(payload)+ if err != nil {+ return nil, err+ }++ resp, err := http.Post(serverUrl, "application/json", bytes.NewBuffer(jsonData))+ if err != nil {+ return nil, err}+ defer resp.Body.Close()++ body, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, err+ }++ // fmt.Println("FileName response body:")+ // fmt.Println(string(body))++ var fileName shared.FileNameResponse+ err = json.Unmarshal(body, &fileName)+ if err != nil {+ return nil, err+ }++ return &fileName, nil}diff --git a/cli/lib/context_fs.go b/cli/lib/context_fs.goindex 604abcf5..9acbbb47 100644--- a/cli/lib/context_fs.go+++ b/cli/lib/context_fs.go@@ -12,10 +12,7 @@ import (func WriteInitialContextState(contextDir string) error {contextState := shared.ModelContextState{- NumTokens: 0,- ActiveTokens: 0,- ChatFlexPct: 25,- PlanFlexPct: 50,+ NumTokens: 0,}contextStateFilePath := filepath.Join(contextDir, "context.json")contextStateFile, err := os.OpenFile(contextStateFilePath, os.O_CREATE|os.O_WRONLY, 0644)diff --git a/cli/lib/context_load.go b/cli/lib/context_load.goindex dfcd7c2e..3df7ac76 100644--- a/cli/lib/context_load.go+++ b/cli/lib/context_load.go@@ -110,16 +110,15 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {hash := sha256.Sum256([]byte(body))sha := hex.EncodeToString(hash[:])- summaryResp, err := Api.Summarize(body)+ fileNameResp, err := Api.FileName(body)if err != nil {log.Fatalf("Failed to summarize the text: %v", err)}- fileName := GetFileNameWithoutExt(summaryResp.FileName)+ fileName := GetFileNameWithoutExt(fileNameResp.FileName)contextPart := shared.ModelContextPart{- Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),- // Summary: summaryResp.Summary,+ Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),Body: body,Sha: sha,NumTokens: numTokens,@@ -185,16 +184,15 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {hash := sha256.Sum256([]byte(body))sha := hex.EncodeToString(hash[:])- summaryResp, err := Api.Summarize(body)+ fileNameResp, err := Api.FileName(body)if err != nil {log.Fatalf("Failed to summarize piped data: %v", err)}- fileName := GetFileNameWithoutExt(summaryResp.FileName)+ fileName := GetFileNameWithoutExt(fileNameResp.FileName)contextPart := shared.ModelContextPart{- Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),- // Summary: summaryResp.Summary,+ Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), fileName),Body: body,Sha: sha,NumTokens: numTokens,@@ -392,14 +390,13 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {hash := sha256.Sum256([]byte(body))sha := hex.EncodeToString(hash[:])- // summaryResp, err := Api.Summarize(body)+ // fileNameResp, err := Api.FileName(body)// if err != nil {// log.Fatalf("Failed to summarize content from URL %s: %v", url, err)// }contextPart := shared.ModelContextPart{- Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), SanitizeAndClipURL(url, 70)),- // Summary: summaryResp.Summary,+ Name: fmt.Sprintf("%d.%s", atomic.LoadUint32(&counter), SanitizeAndClipURL(url, 70)),Body: body,Sha: sha,NumTokens: numTokens,diff --git a/cli/lib/proposal.go b/cli/lib/proposal.goindex 45eaedbe..475eb57a 100644--- a/cli/lib/proposal.go+++ b/cli/lib/proposal.go@@ -30,12 +30,12 @@ func Propose(prompt string) error {s.Start()if CurrentPlanIsDraft() {- summaryResp, err := Api.Summarize(prompt)+ fileNameResp, err := Api.FileName(prompt)if err != nil {fmt.Fprintln(os.Stderr, "\nError summarizing prompt:", err)return err}- RenameCurrentDraftPlan(GetFileNameWithoutExt(summaryResp.FileName))+ RenameCurrentDraftPlan(GetFileNameWithoutExt(fileNameResp.FileName))}timestamp := StringTs()diff --git a/cli/lib/stream.go b/cli/lib/stream.goindex 3cc90034..a89c4fda 100644--- a/cli/lib/stream.go+++ b/cli/lib/stream.go@@ -1,6 +1,8 @@package libimport (+ "bufio"+ "bytes""encoding/json""fmt""log"@@ -251,3 +253,18 @@ func loadCurrentPlanTokensByFilePath() (map[string]int, error) {return currentPlanTokensByFilePath, nil}++func readUntilSeparator(reader *bufio.Reader, separator string) (string, error) {+ var result []byte+ sepBytes := []byte(separator)+ for {+ b, err := reader.ReadByte()+ if err != nil {+ return string(result), err+ }+ result = append(result, b)+ if len(result) >= len(sepBytes) && bytes.HasSuffix(result, sepBytes) {+ return string(result[:len(result)-len(separator)]), nil+ }+ }+}diff --git a/cli/types/types.go b/cli/types/types.goindex f009352f..77e9053c 100644--- a/cli/types/types.go+++ b/cli/types/types.go@@ -26,8 +26,9 @@ type OnStreamPlan func(params OnStreamPlanParams)// APIHandler is an interface that represents the public API functionstype APIHandler interface {Propose(prompt, parentProposalId string, onStream OnStreamPlan) (*shared.PromptRequest, error)- Summarize(text string) (*shared.SummarizeResponse, error)+ ShortSummary(text string) (*shared.ShortSummaryResponse, error)Abort(proposalId string) error+ FileName(text string) (*shared.FileNameResponse, error)}type AppendConversationParams struct {diff --git a/server/go.mod b/server/go.modindex e362e3fe..5a8de81e 100644--- a/server/go.mod+++ b/server/go.mod@@ -12,7 +12,14 @@ require (require (github.com/dlclark/regexp2 v1.10.0 // indirect+ github.com/fatih/color v1.9.0 // indirect+ github.com/fsnotify/fsnotify v1.4.9 // indirect+ github.com/githubnemo/CompileDaemon v1.4.0 // indirect+ github.com/mattn/go-colorable v0.1.4 // indirect+ github.com/mattn/go-isatty v0.0.11 // indirectgithub.com/pkoukk/tiktoken-go v0.1.6 // indirect+ github.com/radovskyb/watcher v1.0.7 // indirect+ golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 // indirect)require (diff --git a/server/go.sum b/server/go.sumindex 9707e0d3..f6c27d17 100644--- a/server/go.sum+++ b/server/go.sum@@ -4,19 +4,36 @@ github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsqgithub.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/drhodes/golorem v0.0.0-20220328165741-da82e5b29246 h1:m0+1paUpmLlBpUxldAEvJZVCrNQpt2iyecCw4TdHdOc=github.com/drhodes/golorem v0.0.0-20220328165741-da82e5b29246/go.mod h1:NsKVpF4h4j13Vm6Cx7Kf0V03aJKjfaStvm5rvK4+FyQ=+github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=+github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=+github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=+github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=+github.com/githubnemo/CompileDaemon v1.4.0 h1:z96Qu4tj+RzRfF+L7f1O6E8ion5JQlisWeXWc2wzwDQ=+github.com/githubnemo/CompileDaemon v1.4.0/go.mod h1:/G125r3YBIp6rcXtCZfiEHwFzcl7GSsNSwylxSNrkMA=github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=github.com/looplab/fsm v1.0.1 h1:OEW0ORrIx095N/6lgoGkFkotqH6s7vaFPsgjLAaF5QU=github.com/looplab/fsm v1.0.1/go.mod h1:PmD3fFvQEIsjMEfvZdrCDZ6y8VwKTwWNjlpEr6IKPO4=+github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=+github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=+github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=+github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=+github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=github.com/pkoukk/tiktoken-go v0.1.6 h1:JF0TlJzhTbrI30wCvFuiw6FzP2+/bR+FIxUdgEAcUsw=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/radovskyb/watcher v1.0.7 h1:AYePLih6dpmS32vlHfhCeli8127LzkIgwJGcwwe8tUE=+github.com/radovskyb/watcher v1.0.7/go.mod h1:78okwvY5wPdzcb1UYnip1pvrZNIVEIh/Cm+ZuvsUYIg=github.com/sashabaranov/go-openai v1.15.1 h1:BAV5LCVEzvZ3rN/Lh5NRVs2z6AahPt/jn5s2/cEEG0M=github.com/sashabaranov/go-openai v1.15.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=+golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=+golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=+golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/server/handlers/name.go b/server/handlers/name.gonew file mode 100644index 00000000..8a436309--- /dev/null+++ b/server/handlers/name.go@@ -0,0 +1,49 @@+package handlers++import (+ "encoding/json"+ "io"+ "log"+ "net/http"+ "plandex-server/model"++ "github.com/plandex/plandex/shared"+)++func FileNameHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for FileNameHandler")++ // 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 get the 'prompt'+ var requestBody shared.FileNameRequest+ 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 empty text field")+ http.Error(w, "text field is required", http.StatusBadRequest)+ return+ }++ modelResp, _, err := model.FileName(requestBody.Text)+ if err != nil {+ log.Printf("Error creating file name for text: %v\n", err)+ http.Error(w, "Error creating file name for text: "+err.Error(), http.StatusInternalServerError)+ return+ }++ log.Println("Successfully processed file name request")+ // Return the response from OpenAI to the client+ w.Write(modelResp)+}diff --git a/server/handlers/summarize.go b/server/handlers/summarize.goindex a6c16bdb..67a03a81 100644--- a/server/handlers/summarize.go+++ b/server/handlers/summarize.go@@ -10,8 +10,8 @@ import ("github.com/plandex/plandex/shared")-func SummarizeHandler(w http.ResponseWriter, r *http.Request) {- log.Println("Received a request for SummarizeHandler")+func ShortSummaryHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received a request for ShortSummaryHandler")// Read the request bodybody, err := io.ReadAll(r.Body)@@ -23,7 +23,7 @@ func SummarizeHandler(w http.ResponseWriter, r *http.Request) {defer r.Body.Close()// Unmarshal the request body to get the 'prompt'- var requestBody shared.SummarizeRequest+ var requestBody shared.ShortSummaryRequestif 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)@@ -36,7 +36,7 @@ func SummarizeHandler(w http.ResponseWriter, r *http.Request) {return}- modelResp, _, err := model.Summarize(requestBody.Text)+ modelResp, _, err := model.ShortSummary(requestBody.Text)if err != nil {log.Printf("Error summarizing text: %v\n", err)http.Error(w, "Error summarizing text: "+err.Error(), http.StatusInternalServerError)diff --git a/server/main.go b/server/main.goindex 96370b1c..b5f258a9 100644--- a/server/main.go+++ b/server/main.go@@ -21,7 +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("/short-summary", handlers.ShortSummaryHandler).Methods("POST")+ r.HandleFunc("/filename", handlers.FileNameHandler).Methods("POST")// Get port from the environment variable or default to 8088port := os.Getenv("PORT")diff --git a/server/model/fix_json.go b/server/model/fix_json.goindex 848e52a3..534a2c18 100644--- a/server/model/fix_json.go+++ b/server/model/fix_json.go@@ -1,3 +1,6 @@+// this file is unused as it hasn't yet been needed+// keeping it around for now in case it's useful at some point+package modelimport (diff --git a/server/model/name.go b/server/model/name.gonew file mode 100644index 00000000..5ce26820--- /dev/null+++ b/server/model/name.go@@ -0,0 +1,78 @@+package model++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"++ "github.com/plandex/plandex/shared"+ "github.com/sashabaranov/go-openai"+ "github.com/sashabaranov/go-openai/jsonschema"+)++func FileName(text string) ([]byte, int, error) {+ resp, err := Client.CreateChatCompletion(+ context.Background(),+ openai.ChatCompletionRequest{+ Model: openai.GPT3Dot5Turbo,+ Functions: []openai.FunctionDefinition{{+ Name: "nameFile",+ Parameters: &jsonschema.Definition{+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "fileName": {+ Type: jsonschema.String,+ Description: "A *short* file name for the text based on the content. Use dashes as word separators. No spaces or special characters. **2-3 words max**.",+ },+ },+ Required: []string{"fileName"},+ },+ }},+ Messages: []openai.ChatCompletionMessage{+ {+ Role: openai.ChatMessageRoleSystem,+ Content: "You are an AI namer that creates a valid filename for the content. Content can be any text, including programs/code, documentation, websites, and more. Most text will be related to software development.",+ },+ {+ Role: openai.ChatMessageRoleUser,+ Content: (`+ Create a file name using the 'nameFile' function. Only call the 'nameFile' function in your reponse. Don't call any other function.++ Text:++ ` + text),+ },+ },+ },+ )++ if err != nil {+ return nil, 0, err+ }++ var byteRes []byte+ for _, choice := range resp.Choices {+ if choice.FinishReason == "function_call" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "summarize" {+ fnCall := choice.Message.FunctionCall++ if strings.HasSuffix(fnCall.Arguments, ",\n}") { // remove trailing comma+ fnCall.Arguments = strings.TrimSuffix(fnCall.Arguments, ",\n}") + "\n}"+ }++ byteRes = []byte(fnCall.Arguments)+ }+ }++ if len(byteRes) == 0 {+ return nil, 0, fmt.Errorf("no summarize function call found in response")+ }++ // validate the JSON response+ var summarizeResp shared.FileNameResponse+ if err := json.Unmarshal(byteRes, &summarizeResp); err != nil {+ return nil, resp.Usage.CompletionTokens, err+ }++ return byteRes, resp.Usage.CompletionTokens, nil+}diff --git a/server/model/proposal/confirm.go b/server/model/proposal/confirm.goindex b2c1c491..7dc5b239 100644--- a/server/model/proposal/confirm.go+++ b/server/model/proposal/confirm.go@@ -10,6 +10,7 @@ import ("plandex-server/types""time"+ "github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai""github.com/sashabaranov/go-openai/jsonschema"@@ -392,6 +393,8 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {if delta.FunctionCall == nil {fmt.Printf("\nStream received data not for a function call")++ spew.Dump(delta)continue} else {content = delta.FunctionCall.Argumentsdiff --git a/server/model/proposal/create.go b/server/model/proposal/create.goindex d049259a..0f5d6599 100644--- a/server/model/proposal/create.go+++ b/server/model/proposal/create.go@@ -5,12 +5,14 @@ import ("encoding/json""fmt""os"+ "strings""time""plandex-server/model""plandex-server/model/lib""plandex-server/types"+ "github.com/davecgh/go-spew/spew""github.com/google/uuid""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai"@@ -148,6 +150,16 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) errorstream, err := model.Client.CreateChatCompletionStream(ctx, modelReq)if err != nil {fmt.Printf("Error creating proposal GPT4 stream: %v\n", err)++ spew.Dump(err)++ errStr := err.Error()+ if strings.Contains(errStr, "status code: 400") &&+ strings.Contains(errStr, "reduce the length of the messages") {+ fmt.Println("Token limit exceeded")++ }+proposals.Delete(proposalId)return err}diff --git a/server/model/summarize.go b/server/model/summarize.goindex 2c08e11c..1089dbb9 100644--- a/server/model/summarize.go+++ b/server/model/summarize.go@@ -11,8 +11,7 @@ import ("github.com/sashabaranov/go-openai/jsonschema")-func Summarize(text string) ([]byte, int, error) {-+func ShortSummary(text string) ([]byte, int, error) {resp, err := Client.CreateChatCompletion(context.Background(),openai.ChatCompletionRequest{@@ -26,12 +25,8 @@ func Summarize(text string) ([]byte, int, error) {Type: jsonschema.String,Description: "A brief summary of the text. A few sentences at most",},- "fileName": {- Type: jsonschema.String,- Description: "A *short* file name for the text based on the content. Use dashes as word separators. No spaces or special characters. A few words max.",- },},- Required: []string{"summary", "fileName"},+ Required: []string{"summary"},},}},Messages: []openai.ChatCompletionMessage{@@ -74,7 +69,70 @@ func Summarize(text string) ([]byte, int, error) {}// validate the JSON response- var summarizeResp shared.SummarizeResponse+ var summarizeResp shared.ShortSummaryResponse+ if err := json.Unmarshal(byteRes, &summarizeResp); err != nil {+ return nil, resp.Usage.CompletionTokens, err+ }++ return byteRes, resp.Usage.CompletionTokens, nil+}++func PlanSummary(conversation []*shared.ConversationMessage) ([]byte, int, error) {+ messages := []openai.ChatCompletionMessage{}++ for _, msg := range conversation {+ messages = append(messages, msg.Message)+ }++ messages = append(messages, openai.ChatCompletionMessage{+ Role: openai.ChatMessageRoleUser,+ Content: ``,+ })++ resp, err := Client.CreateChatCompletion(+ context.Background(),+ openai.ChatCompletionRequest{+ Model: openai.GPT4,+ Functions: []openai.FunctionDefinition{{+ Name: "summarize",+ Parameters: &jsonschema.Definition{+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "summary": {+ Type: jsonschema.String,+ Description: "A summary of the current state of the plan.",+ },+ },+ Required: []string{"summary"},+ },+ }},+ Messages: messages,+ },+ )++ if err != nil {+ return nil, 0, err+ }++ var byteRes []byte+ for _, choice := range resp.Choices {+ if choice.FinishReason == "function_call" && choice.Message.FunctionCall != nil && choice.Message.FunctionCall.Name == "summarize" {+ fnCall := choice.Message.FunctionCall++ if strings.HasSuffix(fnCall.Arguments, ",\n}") { // remove trailing comma+ fnCall.Arguments = strings.TrimSuffix(fnCall.Arguments, ",\n}") + "\n}"+ }++ byteRes = []byte(fnCall.Arguments)+ }+ }++ if len(byteRes) == 0 {+ return nil, 0, fmt.Errorf("no summarize function call found in response")+ }++ // validate the JSON response+ var summarizeResp shared.ShortSummaryResponseif err := json.Unmarshal(byteRes, &summarizeResp); err != nil {return nil, resp.Usage.CompletionTokens, err}diff --git a/server/types/conversation.go b/server/types/conversation.gonew file mode 100644index 00000000..50fd2134--- /dev/null+++ b/server/types/conversation.go@@ -0,0 +1,8 @@+package types++type Conversation struct {+ ProposalId string+ Summary string+ SummaryTokens int+ UpdatedAt int+}diff --git a/shared/tokens.go b/shared/tokens.goindex 6f792bda..acb2dd09 100644--- a/shared/tokens.go+++ b/shared/tokens.go@@ -17,6 +17,5 @@ func GetNumTokens(text string) (numTokens int) {log.Println(err)return}-return len(tkm.Encode(text, nil, nil))}diff --git a/shared/types.go b/shared/types.goindex 3ec8ad99..7028c032 100644--- a/shared/types.go+++ b/shared/types.go@@ -9,11 +9,8 @@ type CurrentPlanFiles struct {}type ConversationMessage struct {- Message openai.ChatCompletionMessage `json:"message"`- Tokens int `json:"tokens"`- Summarized bool `json:"summarized"`- Summary string `json:"summary"`- SummaryTokens int `json:"summaryTokens"`+ Message openai.ChatCompletionMessage `json:"message"`+ Tokens int `json:"tokens"`}type PromptRequest struct {@@ -25,12 +22,19 @@ type PromptRequest struct {ParentProposalId string `json:"parentProposalId"`}-type SummarizeRequest struct {+type ShortSummaryRequest struct {Text string `json:"text"`}-type SummarizeResponse struct {- Summary string `json:"summary"`+type ShortSummaryResponse struct {+ Summary string `json:"summary"`+}++type FileNameRequest struct {+ Text string `json:"text"`+}++type FileNameResponse struct {FileName string `json:"fileName"`}@@ -46,11 +50,8 @@ type ModelContextPart struct {type ModelContext []ModelContextParttype ModelContextState struct {- NumTokens int `json:"numTokens"`- Counter uint32 `json:"counter"`- ActiveTokens int `json:"activeTokens"`- ChatFlexPct int `json:"chatFlexPct"`- PlanFlexPct int `json:"planFlexPct"`+ NumTokens int `json:"numTokens"`+ Counter uint32 `json:"counter"`}type PlanChunk struct {