← Library AI AI-Powered

AIRerankOp

Reranks a list of candidates by relevance to a query — returns a permutation of indices sorted best-first.

Inputs

Field Type Description
Query *string The reference query or criteria to rank against
Candidates *[]string Items to rerank

Outputs

Field Type Description
Result []int Permutation of candidate indices, best-first

Reasoning is captured by WithReasoningLog — no graph output needed.

Params

Key Type Default Description
max_retries string "3" Number of retries on parse error

Typical Use Cases

  • Reranking vector-search results for final relevance
  • Recommendation ordering by user intent
  • Priority sorting of retrieved support articles
  • Ordering candidates before presenting top-K to the user

Returns indices, not strings. The output is a full permutation of the candidate indices in descending relevance order. Use SliceFirstOp to get the top result, or SliceTopKOp to trim to a fixed K.

Complete Runnable Example

Reranks a list of Go articles by relevance to a performance query, returning a permutation of indices best-first.

main.go
package main

import (
	"context"
	"encoding/json"
	"log"
	"os"
	"time"

	"github.com/akennis/sparsi-go/library"
	_ "github.com/akennis/dagor/operator/builtin"

	"github.com/panjf2000/ants/v2"
	"github.com/akennis/dagor"
	"github.com/akennis/dagor/graph"
)

func main() {
	query := "How do I improve Go application performance?"
	articles := []string{
		"Introduction to Go modules and dependency management",
		"Profiling and optimizing Go programs for speed",
		"Building REST APIs with Go and the net/http package",
		"Go garbage collection tuning and memory optimization",
		"Unit testing best practices in Go",
	}

	library.RegisterConst("query_val", query)
	library.RegisterConst("articles_val", articles)

	g, err := graph.NewBuilder("rerank_demo").
		Vertex("q_src").Op("query_val").
		Output("Result", "query_wire").

		Vertex("a_src").Op("articles_val").
		Output("Result", "articles_wire").

		Vertex("rerank").Op("AIRerankOp").
		Input("Query", "query_wire").
		Input("Candidates", "articles_wire").
		Output("Result", "ranked_indices").

		Build()
	if err != nil {
		log.Fatalf("build: %v", err)
	}

	pool, err := ants.NewPool(4)
	if err != nil {
		log.Fatalf("pool: %v", err)
	}
	defer pool.Release()

	eng, err := dagor.NewEngine(g, pool)
	if err != nil {
		log.Fatalf("engine: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	if err := eng.Run(ctx); err != nil {
		log.Fatalf("run: %v", err)
	}

	out := map[string]any{}
	if raw, ok := eng.GetOutput("ranked_indices"); ok {
		out["ranked_indices"] = *raw.(*[]int)
	}

	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	enc.Encode(out)
}