Skip to content

Commit

Permalink
Adjust flexPromptNode logic to handle token calculation and flex chec…
Browse files Browse the repository at this point in the history
…ks more accurately (#737)

* Adjust flexPromptNode logic to handle token calculation and flex checks more accurately

* Fix typos and adjust flex logic in promptdom.ts and genai.mts files
  • Loading branch information
pelikhan authored Sep 30, 2024
1 parent a5e3d44 commit 0d27bf1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
14 changes: 12 additions & 2 deletions packages/core/src/promptdom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { resolveTokenEncoder } from "./encoders"
import { expandFiles } from "./fs"
import { interpolateVariables } from "./mustache"
import { createDiff } from "./diff"
import { total } from "@tidyjs/tidy"

// Definition of the PromptNode interface which is an essential part of the code structure.
export interface PromptNode extends ContextExpansionOptions {
Expand Down Expand Up @@ -787,7 +788,7 @@ async function flexPromptNode(
0
)

if (totalTokens < flexTokens) {
if (totalTokens <= flexTokens) {
// No need to flex
return
}
Expand All @@ -799,8 +800,17 @@ async function flexPromptNode(
(a.priority ?? PRIORITY_DEFAULT) - (b.priority ?? PRIORITY_DEFAULT)
)
const flexNodes = nodes.filter((n) => n.flex !== undefined)
const totalFlex = flexNodes.reduce((total, node) => total + node.flex, 0)
const totalFlexTokens = flexNodes.reduce(
(total, node) => total + (node.tokens ?? 0),
0
)

// checking flexNodes sizes
if (totalFlexTokens <= flexTokens) {
return
}

const totalFlex = flexNodes.reduce((total, node) => total + node.flex, 0)
const totalReserve = 0
const totalRemaining = Math.max(0, flexTokens - totalReserve)
for (const node of flexNodes) {
Expand Down
6 changes: 3 additions & 3 deletions packages/sample/genaisrc/flex.genai.mts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ script({
def("FILE", env.files, { flex: 1 })

// will be trimmed
$`What is Markdown?
Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents. Created by John Gruber in 2004, Markdown is now one of the world’s most popular markup languages.
$`(ignore What is Markdown?
Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents. Created by John Gruber in 2004, Markdown is now one of the world’s most popular markup languages.)
PRINT ABRACADABRA!`.flex(2)

$`This one is flexed.
$`(ignore This one is flexed.)
PRINT MONKEY!`.flex(1)

0 comments on commit 0d27bf1

Please sign in to comment.