Skip to content

Commit 4e85ec6

Browse files
committed
Tons of minor fixes
1 parent 3a05484 commit 4e85ec6

File tree

5 files changed

+140
-47
lines changed

5 files changed

+140
-47
lines changed

ai.go

Lines changed: 97 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -384,9 +384,9 @@ func FindHttpBody(fullBody []byte) (HTTPOutput, []byte, error) {
384384

385385
//if httpOutput.Status >= 300 && httpOutput.Status != 404 {
386386
if httpOutput.Status >= 300 {
387-
if debug {
388-
log.Printf("[INFO] Translated action failed with status: %d. Rerun Autocorrecting feature!. Body: %s", httpOutput.Status, string(marshalledBody))
389-
}
387+
//if debug {
388+
// log.Printf("[DEBUG] Translated action failed with status: %d. Rerun Autocorrecting feature!. Body: %s", httpOutput.Status, string(marshalledBody))
389+
//}
390390

391391
return *httpOutput, []byte{}, errors.New(fmt.Sprintf("Status: %d", httpOutput.Status))
392392
}
@@ -528,6 +528,14 @@ func FindNextApiStep(originalFields []Valuereplace, action Action, stepOutput []
528528
return "", action, fmt.Errorf("Ran action towards App %s with Action %s, but it failed. Try to re-authenticate the app with the correct URL", action.AppName, actionName), additionalInfo
529529
}
530530

531+
fullUrl := ""
532+
url1, urlOk := resultMap["url"]
533+
if urlOk {
534+
if val, ok := url1.(string); ok {
535+
fullUrl = val
536+
}
537+
}
538+
531539
body := []byte{}
532540
body1, bodyOk := resultMap["body"]
533541
if !bodyOk {
@@ -568,9 +576,9 @@ func FindNextApiStep(originalFields []Valuereplace, action Action, stepOutput []
568576
body = []byte(val)
569577
}
570578

571-
if debug {
572-
log.Printf("[DEBUG] Inside body handler: %s", string(body))
573-
}
579+
//if debug {
580+
// log.Printf("[DEBUG] Inside body handler: %s", string(body))
581+
//}
574582

575583
// Should turn body into a string and check OpenAPI for problems if status is bad
576584
if status >= 0 && status < 300 {
@@ -585,7 +593,7 @@ func FindNextApiStep(originalFields []Valuereplace, action Action, stepOutput []
585593
} else if status >= 400 {
586594
// Auto-correct
587595
// Auto-fix etc
588-
log.Printf("[INFO] Trying autocorrect. See body: %s", string(body))
596+
//log.Printf("[INFO] Trying autocorrect. See body: %s", string(body))
589597

590598
useApp := action.AppName
591599
if len(originalAppname) > 0 {
@@ -598,7 +606,7 @@ func FindNextApiStep(originalFields []Valuereplace, action Action, stepOutput []
598606
}
599607

600608
// Body = previous requests' body
601-
action, additionalInfo, err := RunSelfCorrectingRequest(originalFields, action, status, additionalInfo, string(body), useApp, inputdata, curAttempt)
609+
action, additionalInfo, err := RunSelfCorrectingRequest(originalFields, action, status, additionalInfo, fullUrl, string(body), useApp, inputdata, curAttempt)
602610
if err != nil {
603611
if !strings.Contains(err.Error(), "missing_fields") {
604612
log.Printf("[ERROR] Error running self-correcting request: %s", err)
@@ -632,7 +640,7 @@ func FindNextApiStep(originalFields []Valuereplace, action Action, stepOutput []
632640
// 1. The fully filled-in action
633641
// 2. The additional info from the previous request
634642
// 3. Any error that may have occurred
635-
func RunSelfCorrectingRequest(originalFields []Valuereplace, action Action, status int, additionalInfo, outputBody, appname, inputdata string, attempt ...int) (Action, string, error) {
643+
func RunSelfCorrectingRequest(originalFields []Valuereplace, action Action, status int, additionalInfo, fullUrl, outputBody, appname, inputdata string, attempt ...int) (Action, string, error) {
636644
// Add all fields with value from here
637645
additionalInfo = ""
638646
inputBody := "{\n"
@@ -692,9 +700,9 @@ func RunSelfCorrectingRequest(originalFields []Valuereplace, action Action, stat
692700

693701
// Check if the amount of {} in inputBody is the same
694702
if strings.Count(inputBody, "{") != strings.Count(inputBody, "}") {
695-
if debug {
696-
log.Printf("[ERROR] Debug: Input body has mismatched curly braces ({*%d vs }*%d). Fixing it. InputBody pre-fix: %s", strings.Count(inputBody, "{"), strings.Count(inputBody, "}"), inputBody)
697-
}
703+
//if debug {
704+
// log.Printf("[ERROR] Debug: Input body has mismatched curly braces ({*%d vs }*%d). Fixing it. InputBody pre-fix: %s", strings.Count(inputBody, "{"), strings.Count(inputBody, "}"), inputBody)
705+
//}
698706

699707
// FIXME: Doesn't take into account key vs value, as it shouldn't change the value.
700708
if strings.Count(inputBody, "{") > strings.Count(inputBody, "}") {
@@ -719,6 +727,10 @@ func RunSelfCorrectingRequest(originalFields []Valuereplace, action Action, stat
719727
inputFields += fmt.Sprintf("\n%s=%s", field.Key, field.Value)
720728
}
721729

730+
if len(fullUrl) > 0 && strings.Contains(fullUrl, "http") {
731+
fullUrl = fmt.Sprintf("- API URL: %s", fullUrl)
732+
}
733+
722734
systemMessage := fmt.Sprintf(`INTRODUCTION
723735
724736
Return all key:value pairs from the last user message, but with modified values to fix ALL the HTTP errors at once. Don't add any comments. Do not try the same thing twice, and use your existing knowledge of the API name and action to reformat the output until it works. All fields in "Required data" MUST be a part of the output if possible. Output MUST be valid JSON.
@@ -727,9 +739,7 @@ END INTRODUCTION
727739
---
728740
INPUTDATA
729741
730-
Action ID: %s
731742
API name: %s
732-
Action details: %s
733743
Required data: %s
734744
735745
END INPUTDATA
@@ -738,18 +748,18 @@ VALIDATION RULES:
738748
739749
- Modify ONLY the fields directly related to the HTTP error
740750
- Use ONLY values derived from:
741-
a) Error message context
742-
b) Existing JSON structure
743-
c) Minimal necessary changes to resolve the error
751+
a) INPUTDATA
752+
b) Error message context
753+
c) Known documentation about the API
744754
745755
END VALIDATION RULES
746756
---
747757
CONSTRAINTS
748758
749-
- Do NOT invent values
759+
- If the path is wrong, change it to be relevant to the input data. It may be /api paths or entirely different
750760
- Do NOT add irrelevant headers or body fields
751761
- MUST use keys present in original JSON
752-
- Make sure all "Required data" values are in the output.
762+
- Make sure all "Required data" values are in the output
753763
- Do not focus on authentication unless necessary
754764
755765
END CONSTRAINTS
@@ -764,35 +774,40 @@ END OUTPUT FORMATTING
764774
---
765775
ERROR HANDLING
766776
767-
- First try to fix the request based on the error message and the existing content in the body and queries.
768-
- You SHOULD add relevant fields to the body that are missing.
777+
- Fix the request based on the API context and the existing content in the path, body and queries
778+
- You SHOULD add relevant fields to the body that are missing
779+
- Modify the "path" field according to what seems wrong with the API URL. Do NOT remove this field.
780+
- Do NOT error-handle authentication issues unless it seems possible
769781
770782
END ERROR HANDLING
771-
`, action.ID, action.AppName, action.Description, inputFields)
783+
`, action.AppName, /*action.Description, */ inputFields)
772784

773785

774786
inputData := ""
775-
if len(attempt) > 0 {
787+
if len(attempt) > 1 {
776788
currentAttempt := attempt[0]
777789
if currentAttempt > 4 {
778-
inputData += fmt.Sprintf(`IF we are missing a value from the user, return the format {"success": false, "missing_fields": ["field1", "field2"]} to indicate the missing fields. Do NOT do this unless it is absolutely necessary, make SURE the fields are missing. Before doing this, ensure the body and query fields are in the right format.\n\n`)
790+
inputData += fmt.Sprintf(`IF we are missing a value from the user, return the format {"success": false, "missing_fields": ["field1", "field2"]} to indicate the missing fields. If the "path" is wrong, rewrite it. Do not use it for authentication fields such as "apikey". Do NOT do this unless it is absolutely necessary, make SURE the fields are missing. Before returning missing fields, ALWAYS ensure and retry the path, body and query fields to ensure they are correct according to the input data.\n\n`)
779791
}
780792
}
781793

782794
// We are using a unique Action ID here most of the time, meaning the chat will be continued.
783795
inputBody = FixContentOutput(inputBody)
784796

785797
inputData += fmt.Sprintf(`Precise JSON Field Correction Instructions:
786-
Given the HTTP API context for %s with action %s:
798+
API context for %s with action %s:
799+
%s
787800
- HTTP Status: %d
788-
- Detailed Errors: %s
801+
- API Body Output: '''
802+
%s
803+
'''
789804
790805
Input JSON Payload (ensure VALID JSON):
791-
%s`, appname, action.Name, status, outputBody, inputBody)
806+
%s`, appname, action.Name, fullUrl, status, outputBody, inputBody)
792807

793808
// Use this for debugging
794809
if debug {
795-
log.Printf("[DEBUG] SYSTEM MESSAGE: %#v\n\nINPUTDATA:\n\n\n%s\n\n\n\n", systemMessage, inputData)
810+
log.Printf("\n\n[DEBUG] SYSTEM MESSAGE: %#v\n\nINPUTDATA:\n\n\n%s\n\n\n\n", systemMessage, inputData)
796811
}
797812

798813
contentOutput, err := RunAiQuery(systemMessage, inputData)
@@ -1321,6 +1336,9 @@ func FixContentOutput(contentOutput string) string {
13211336
contentOutput = strings.Trim(contentOutput, "\n")
13221337
contentOutput = strings.Trim(contentOutput, "\t")
13231338

1339+
// Fix issues with newlines in keys. Replace with raw newlines
1340+
contentOutput = strings.ReplaceAll(contentOutput, "\\n", "\n")
1341+
13241342
// Attempts to balance it automatically
13251343
contentOutput = balanceJSONLikeString(contentOutput)
13261344

@@ -1335,7 +1353,7 @@ func FixContentOutput(contentOutput string) string {
13351353
log.Printf("[WARNING] Failed to marshal indent tmpMap in FixContentOutput (1): %s", err)
13361354
}
13371355
} else {
1338-
log.Printf("[WARNING] Failed to unmarshal tmpMap in FixContentOutput (2): %s", err)
1356+
log.Printf("[WARNING] Failed to unmarshal tmpMap in FixContentOutput (2): %s => %s", string(contentOutput), err)
13391357
}
13401358

13411359
return contentOutput
@@ -1594,11 +1612,18 @@ func AutofixAppLabels(app WorkflowApp, label string, keys []string) (WorkflowApp
15941612
userMessage := fmt.Sprintf("Out of the following actions, which action matches '%s'?\n", label)
15951613

15961614
//changedNames := map[string]string{}
1615+
parsedLabel := strings.ToLower(strings.ReplaceAll(label, " ", "_"))
15971616
for _, action := range app.Actions {
15981617
if action.Name == "custom_action" {
15991618
continue
16001619
}
16011620

1621+
parsedActionName := strings.ToLower(strings.ReplaceAll(action.Name, " ", "_"))
1622+
if parsedActionName == parsedLabel {
1623+
return app, action
1624+
}
1625+
1626+
16021627
//userMessage += fmt.Sprintf("%s\n", action.Name)
16031628
/*
16041629
newName := action.Name
@@ -3577,7 +3602,7 @@ func getSelectedAppParameters(ctx context.Context, user User, selectedAction Wor
35773602
} else {
35783603
// Since we are trying to fill them in anyway :)
35793604
if len(sampleBody) == 0 {
3580-
log.Printf("[INFO] No matching body found for app %s. Err: %s", appname, err)
3605+
log.Printf("[INFO] No matching body found for app %s with action %s. Err: %s", appname, selectedAction.Name, err)
35813606
sampleBody = formattedFields
35823607
}
35833608
}
@@ -4314,6 +4339,8 @@ func MatchBodyWithInputdata(inputdata, appname, actionName, body string, appCont
43144339
actionName = strings.ReplaceAll(actionName, "get ", "")
43154340
} else if strings.HasPrefix(actionName, "delete ") {
43164341
actionName = strings.ReplaceAll(actionName, "delete ", "")
4342+
} else {
4343+
log.Printf("[DEBUG] Action name %s does not have standard HTTP verb prefix", actionName)
43174344
}
43184345

43194346
if strings.HasPrefix(inputdata, "//") {
@@ -4607,8 +4634,47 @@ func runSelfCorrectingRequest(action Action, status int, additionalInfo, outputB
46074634
}
46084635

46094636
func GetAppSingul(sourcepath, appname string) (*WorkflowApp, *openapi3.Swagger, error) {
4637+
var err error
46104638
returnApp := &WorkflowApp{}
46114639
openapiDef := &openapi3.Swagger{}
4640+
if !standalone {
4641+
log.Printf("[DEBUG] In GetAppSingul from non-standalone mode, using GetApp for '%s'", appname)
4642+
ctx := context.Background()
4643+
4644+
foundApp, err := HandleAlgoliaAppSearch(ctx, appname)
4645+
if err != nil {
4646+
return returnApp, openapiDef, err
4647+
}
4648+
4649+
if debug {
4650+
log.Printf("[DEBUG] Found app ID %s in algolia for name %s", foundApp.ObjectID, appname)
4651+
}
4652+
4653+
returnApp, err = GetApp(ctx, foundApp.ObjectID, User{}, false)
4654+
if err != nil {
4655+
return returnApp, openapiDef, err
4656+
} else {
4657+
parsedOpenapi, err := GetOpenApiDatastore(ctx, foundApp.ObjectID)
4658+
if err != nil {
4659+
log.Printf("[DEBUG] Failed getting OpenAPI from datastore for app %s: %s", appname, err)
4660+
}
4661+
4662+
if parsedOpenapi.Success && len(parsedOpenapi.Body) > 0 {
4663+
swaggerLoader := openapi3.NewSwaggerLoader()
4664+
swaggerLoader.IsExternalRefsAllowed = true
4665+
openapiDef, err = swaggerLoader.LoadSwaggerFromData([]byte(parsedOpenapi.Body))
4666+
if err != nil {
4667+
log.Printf("[ERROR] Failed to load swagger for app %s: %s", appname, err)
4668+
}
4669+
} else {
4670+
log.Printf("[ERROR] Bad OpenAPI found in datastore for app %s", appname)
4671+
}
4672+
4673+
return returnApp, openapiDef, nil
4674+
}
4675+
}
4676+
4677+
46124678
if len(appname) == 0 {
46134679
return returnApp, openapiDef, errors.New("Appname not set")
46144680
}
@@ -4626,7 +4692,6 @@ func GetAppSingul(sourcepath, appname string) (*WorkflowApp, *openapi3.Swagger,
46264692
searchname := strings.ReplaceAll(strings.ToLower(appname), " ", "_")
46274693
appPath := fmt.Sprintf("%s/apps/%s.json", sourcepath, searchname)
46284694

4629-
var err error
46304695
responseBody := []byte{}
46314696

46324697
_, statErr := os.Stat(appPath)
@@ -4753,7 +4818,7 @@ func GetAppSingul(sourcepath, appname string) (*WorkflowApp, *openapi3.Swagger,
47534818
log.Printf("[ERROR] Error writing file: %s", err)
47544819
return &parsedApp, openapiDef, err
47554820
} else {
4756-
log.Printf("[DEBUG] Wrote app to file: %s", appPath)
4821+
log.Printf("[INFO] Wrote app to file: %s", appPath)
47574822
}
47584823
}
47594824

db-connector.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2317,7 +2317,7 @@ func GetApp(ctx context.Context, id string, user User, skipCache bool) (*Workflo
23172317
}
23182318

23192319
if id == "integration" {
2320-
return workflowApp, errors.New("App ID 'integration' is for the integration framework. Uses the Shuffle-ai app.")
2320+
return workflowApp, errors.New("App ID 'integration' is for Singul. Uses the Shuffle-AI app. This error is from GetApp(integration) which does not work. Contact [email protected] if this persists.")
23212321
}
23222322

23232323
nameKey := "workflowapp"
@@ -4035,7 +4035,11 @@ func GetOrg(ctx context.Context, id string) (*Org, error) {
40354035
cacheData := []byte(cache.([]uint8))
40364036
err = json.Unmarshal(cacheData, &curOrg)
40374037
if err == nil {
4038-
return curOrg, nil
4038+
if curOrg.Id == "" {
4039+
return curOrg, errors.New("Org doesn't exist")
4040+
} else {
4041+
return curOrg, nil
4042+
}
40394043
}
40404044
} else {
40414045
//log.Printf("[DEBUG] Failed getting cache for org: %s", err)
@@ -4082,6 +4086,18 @@ func GetOrg(ctx context.Context, id string) (*Org, error) {
40824086
err = nil
40834087
} else {
40844088
log.Printf("[ERROR] Problem in org loading (2) for %s: %s", key, err)
4089+
if strings.Contains(err.Error(), `no such entity`) && project.CacheDb {
4090+
neworg, err := json.Marshal(curOrg)
4091+
if err != nil {
4092+
return &Org{}, err
4093+
}
4094+
4095+
// Set cache for it
4096+
err = SetCache(ctx, cacheKey, neworg, 30)
4097+
if err != nil {
4098+
log.Printf("[ERROR] Failed updating org cache (3): %s", err)
4099+
}
4100+
}
40854101
//orgErr = err
40864102
return &Org{}, err
40874103
}

notifications.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,10 @@ func forwardNotificationRequest(ctx context.Context, title, description, referen
625625
}
626626

627627
func CreateOrgNotification(ctx context.Context, title, description, referenceUrl, orgId string, adminsOnly bool) error {
628+
if standalone {
629+
return nil
630+
}
631+
628632
if len(orgId) == 0 {
629633
log.Printf("[ERROR] No org ID provided to create notification '%s'", title)
630634
return errors.New("no org ID provided")

shared.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20379,6 +20379,8 @@ func PrepareSingleAction(ctx context.Context, user User, appId string, body []by
2037920379
if len(decision) > 0 {
2038020380
decisionId = decision[0]
2038120381
}
20382+
} else if strings.ToLower(appId) == "integration" || strings.ToLower(appId) == "singul" {
20383+
log.Printf("[INFO] Running single action for 'integration' app => Singul")
2038220384
} else if strings.ToLower(appId) == "http" {
2038320385

2038420386
// Find the app and the ID for it
@@ -20474,6 +20476,10 @@ func PrepareSingleAction(ctx context.Context, user User, appId string, body []by
2047420476
}
2047520477

2047620478
} else {
20479+
// Integration handler as it has no name
20480+
//action.AppName = "Shuffle-AI"
20481+
//action.Name = "run_schemaless"
20482+
2047720483
newApp, err := GetApp(ctx, appId, user, false)
2047820484
if err != nil || len(newApp.ID) == 0 {
2047920485
log.Printf("[WARNING] Error getting app (execute SINGLE app action): %s", appId)
@@ -20767,6 +20773,7 @@ func PrepareSingleAction(ctx context.Context, user User, appId string, body []by
2076720773
workflowExecution.WorkflowId = action.SourceWorkflow
2076820774
workflowExecution.Workflow.ID = action.SourceWorkflow
2076920775

20776+
workflowExecution.ExecutionArgument = oldExec.ExecutionArgument
2077020777
workflowExecution.ExecutionSource = action.SourceWorkflow
2077120778
workflowExecution.ExecutionParent = action.SourceExecution
2077220779

@@ -21093,7 +21100,7 @@ func runAppRebuildFromSingleAction(appId string) {
2109321100
ctx := context.Background()
2109421101
app, err := GetApp(ctx, appId, User{}, false)
2109521102
if err != nil {
21096-
log.Printf("[WARNING] Error getting app (execute SINGLE app action): %s", appId)
21103+
log.Printf("[WARNING] Error getting app (execute SINGLE app action - 2): %s", appId)
2109721104
return
2109821105
}
2109921106

0 commit comments

Comments
 (0)