Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ optional. The organization's are a floor its apps can tighten but not loosen.
| `data_policy` | `allow_training` and `retention`, applied to every routed request as a floor under whatever it asked for. The stricter of the two scopes wins. A model that declares no `data_policy` meets no floor, so this narrows LLM, search and image routing to declared models. A policy has no `region`, and one sent is refused: where work is done is the agent's own `region`, or a direct call's `data_policy.region`; see [Regions](#regions) |
| `quota` | What one end user may spend in a UTC day, in place of the deployment's default: the organization's for every user of its apps, the app's over it, and a named user's own (`/v1/policies/users/{user_id}`) over both. Unlike the rest, a more specific level wins rather than the stricter. See [Daily limits](#daily-limits) |
| `tool_output_retention` | How long sessions keep what their tools were given and gave back: `none`, or `1h` to `3650d` such as `30d`. The shortest of the organization's, the app's and the agent config's `tools.output_retention` applies. See [What is recorded](#what-is-recorded) |
| `prompt_injection` | Screens the newest input of every LLM response (the user's turn and any tool results) with the decision model router, using the default route (Jev), at the same time as the model call. Deltas are not held; the end of the response waits for the verdict (at most 2s), and an injection fails the response before its tool calls can be acted on |
| `prompt_injection` | Screens the newest input of every LLM response (the user's turn and any tool results) for prompt injection. The decision model router reads it on its default route (Jev) while the model answers. Deltas are not held. The end of the response waits for the verdict (at most 2s), and an injection fails the response before its tool calls can be acted on. The decision model reads text only, so a response whose newest input has an image is always refused, even without `prompt_injection_fail_closed`. That covers a photo, a camera or video frame, and a screenshot a tool returns. Each passage a knowledge lookup finds is screened before the model reads it. A flagged passage is left out, and the model is told how many were withheld. With `prompt_injection_fail_closed` on, a passage the screen could not check is left out too |
| `prompt_injection_fail_closed` | With `prompt_injection` on, refuses a response the screen could not check (the decision model failed, took longer than 2s, or the deployment has none), so every screened response is refused on a deployment with no decision model. The refusal is a 503 `prompt_injection_unchecked` that a caller may retry, not the 400 `prompt_injection` a flagged input gets. Without the setting, such a response goes through unchecked. True at either scope turns it on |

The screen asks one question per harm in OpenRouter's prompt injection list (instruction
Expand Down
2 changes: 1 addition & 1 deletion acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7626,7 +7626,7 @@ components:
data_policy:
$ref: '#/components/schemas/PolicyDataPolicy'
prompt_injection:
description: Screen what every LLM response is asked for prompt injection. The newest input - the user's turn and any tool results - goes to a decision model beside the model call, so it adds nothing to time to first token. The end of the response is held until the verdict, and a response whose input reads as an injection fails with prompt_injection before its tool calls can be acted on.
description: 'Check what each LLM response is about to read for prompt injection: the user''s turn and any tool results. The check runs while the model answers, so it adds nothing to time to first token. If the input reads as an injection, the response fails with prompt_injection before its tool calls can be acted on. The check can''t read images, so a response whose newest input has an image fails with prompt_injection too. That includes photos, camera and video frames, and screenshots a tool returns, so leave this off for an agent that has to see. A passage a knowledge lookup finds is checked before the model reads it, and a passage that reads as an injection is left out of the lookup''s answer.'
type: boolean
prompt_injection_fail_closed:
description: Refuse a response when the prompt injection screen cannot check it, for example because the decision model is down or too slow. The response then fails with prompt_injection_unchecked (a 503 you can retry), and its tool calls are not acted on. With no decision model on this deployment, every screened response is refused. Left out or false, such a response goes through unchecked. It only applies where prompt_injection is on. True at either scope turns it on, so an app cannot turn its organization's off.
Expand Down
8 changes: 8 additions & 0 deletions acceleration/internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,9 @@ type Options struct {
// KnowledgeLimit caps how many passages one lookup returns. Zero leaves the store's
// own default.
KnowledgeLimit int
// ScreenKnowledge judges each passage a lookup found before the model reads it. A passage
// it refuses is left out of the lookup's answer. Nil screens nothing.
ScreenKnowledge func(ctx context.Context, owner routing.Owner, passage string) error
// Search is what the agent may find out that neither it nor the handbook knows,
// because it depends on today. Without it, or without a target, the search tool is not
// offered, for the same reason the lookup is not: an agent that promises to check and
Expand Down Expand Up @@ -865,10 +868,15 @@ func New(options Options) (*Agent, error) {
// A knowledge store without a namespace reads nothing, so the agent is treated as
// having none rather than being offered a search that would always fail.
if options.Knowledge != nil && options.KnowledgeNamespace != "" {
var screen func(context.Context, string) error
if options.ScreenKnowledge != nil {
screen = func(ctx context.Context, passage string) error { return options.ScreenKnowledge(ctx, owner, passage) }
Comment thread
kanat marked this conversation as resolved.
Resolved
}
agent.knowledge = newKnowledgeReader(
options.Knowledge.For(owner),
options.KnowledgeNamespace,
options.KnowledgeLimit,
screen,
)
}

Expand Down
5 changes: 5 additions & 0 deletions acceleration/internal/agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,8 @@ type AgentSuite struct {
// base, and namespace is which one it reads.
knows *stubKnowledge
namespace string
// screensKnowledge is the agent's ScreenKnowledge. Nil screens nothing.
screensKnowledge func(ctx context.Context, owner routing.Owner, passage string) error
// finds is what the agent may find out about now, when a test gives it a search
// provider.
finds *stubSearch
Expand Down Expand Up @@ -1101,6 +1103,7 @@ func (s *AgentSuite) SetupTest() {
s.incognito = false
s.knows = nil
s.namespace = ""
s.screensKnowledge = nil
s.finds = nil
s.drawings = nil
s.attribution = routing.Attribution{}
Expand Down Expand Up @@ -1258,6 +1261,7 @@ func (s *AgentSuite) joinText() {
LLMTarget: "en-low-latency",
Knowledge: reading,
KnowledgeNamespace: s.namespace,
ScreenKnowledge: s.screensKnowledge,
Guardrail: s.screening(),
Logger: logger,

Expand Down Expand Up @@ -1451,6 +1455,7 @@ func (s *AgentSuite) joinWithVoice(streamingVoice bool, wrapVoice func(*stubTTS)
Memory: remembering,
Knowledge: reading,
KnowledgeNamespace: s.namespace,
ScreenKnowledge: s.screensKnowledge,
Search: finding,
SearchTarget: searchTarget,
Guardrail: s.screening(),
Expand Down
3 changes: 2 additions & 1 deletion acceleration/internal/agent/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,8 @@ type LookedUp struct {
TurnID string
Query string
// Documents is how many passages bore on the question. Zero means the knowledge base
// had nothing, which is why the agent said it did not know.
// had nothing, which is why the agent said it did not know. A passage the prompt
// injection screen withheld is not counted, since the model never read it.
Documents int
}

Expand Down
42 changes: 35 additions & 7 deletions acceleration/internal/agent/knowledge.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"strings"
"sync"

"github.com/GetStream/Vision-Agents/acceleration/internal/harness"
"github.com/GetStream/Vision-Agents/acceleration/internal/knowledge"
Expand All @@ -27,19 +28,39 @@ type knowledgeReader struct {
store knowledge.Store
namespace string
limit int
// screen judges each passage found before the model reads it. Nil screens nothing.
screen func(ctx context.Context, passage string) error
}

func newKnowledgeReader(store knowledge.Store, namespace string, limit int) *knowledgeReader {
return &knowledgeReader{store: store, namespace: namespace, limit: limit}
func newKnowledgeReader(store knowledge.Store, namespace string, limit int, screen func(context.Context, string) error) *knowledgeReader {
return &knowledgeReader{store: store, namespace: namespace, limit: limit, screen: screen}
}

// Search answers one question out of the knowledge base.
func (r *knowledgeReader) Search(ctx context.Context, question string) ([]knowledge.Document, error) {
return r.store.Search(ctx, knowledge.Query{
// Search answers one question out of the knowledge base. It leaves out every passage the
// screen refused, and says how many it left out.
func (r *knowledgeReader) Search(ctx context.Context, question string) ([]knowledge.Document, int, error) {
found, err := r.store.Search(ctx, knowledge.Query{
Namespace: r.namespace,
Text: question,
Limit: r.limit,
})
if err != nil || r.screen == nil {
return found, 0, err
}
verdicts := make([]error, len(found))
var wg sync.WaitGroup
for i, passage := range found {
// The source is screened with the text, since the model reads it too.
wg.Go(func() { verdicts[i] = r.screen(ctx, passage.Source+"\n\n"+passage.Text) })
}
wg.Wait()
kept := make([]knowledge.Document, 0, len(found))
for i, passage := range found {
if verdicts[i] == nil {
kept = append(kept, passage)
}
}
return kept, len(found) - len(kept), nil
}

// lookup answers a question out of the knowledge base and hands the passages to the model.
Expand Down Expand Up @@ -69,10 +90,17 @@ func (a *Agent) knowledgeAnswer(ctx context.Context, turnID, query string) (stri
if question == "" {
return "", harness.Correctable(errors.New("agent: a lookup needs something to look for"))
}
found, err := a.knowledge.Search(ctx, question)
found, withheld, err := a.knowledge.Search(ctx, question)
if err != nil {
return "", fmt.Errorf("agent: look up %q: %w", question, err)
}
a.emitter.Send(LookedUp{TurnID: turnID, Query: question, Documents: len(found)})
Comment thread
kanat marked this conversation as resolved.
Resolved
return knowledge.Prompt(found), nil
said := knowledge.Prompt(found)
switch {
case withheld == 1:
said += "\n\nThe prompt injection screen withheld one passage that matched."
case withheld > 1:
said += fmt.Sprintf("\n\nThe prompt injection screen withheld %d passages that matched.", withheld)
}
return said, nil
}
126 changes: 126 additions & 0 deletions acceleration/internal/agent/knowledge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ package agent
import (
"context"
"errors"
"strings"
"sync"

"github.com/GetStream/Vision-Agents/acceleration/internal/harness"
"github.com/GetStream/Vision-Agents/acceleration/internal/knowledge"
"github.com/GetStream/Vision-Agents/acceleration/internal/knowledge/turbopuffer"
"github.com/GetStream/Vision-Agents/acceleration/internal/policy"
"github.com/GetStream/Vision-Agents/acceleration/internal/routing"
"github.com/GetStream/Vision-Agents/acceleration/internal/stt"
)

Expand Down Expand Up @@ -121,6 +124,129 @@ func (s *AgentSuite) TestALookupAskedAsASkillStillRuns() {
s.Equal("where is my order", asked[0].Text)
}

// refusesPassages is a knowledge screen that refuses every passage holding flagged, as the
// policy's does with a passage that reads as a prompt injection.
func refusesPassages(flagged string) func(context.Context, routing.Owner, string) error {
return func(_ context.Context, _ routing.Owner, passage string) error {
if strings.Contains(passage, flagged) {
return policy.ErrPromptInjection
}
return nil
}
}

func (s *AgentSuite) TestALookupLeavesOutAPassageTheScreenRefusedAndSaysSo() {
s.reads(
knowledge.Document{Text: "Delivery is free over $50.", Source: "shipping.md"},
knowledge.Document{Text: "Returns are accepted within 30 days.", Source: "planted.md"},
knowledge.Document{Text: "Orders ship within two days.", Source: "dispatch.md"},
)
s.screensKnowledge = refusesPassages("planted.md")
s.join(false)
s.model.reply = []string{"Let me check that."}
s.asksFor("lookup", `{"query":"what does delivery cost"}`)
participant := stt.Participant{ID: "alice"}
s.speak(participant)

s.says(participant, "how much is delivery")

ran := s.awaitToolRan()
s.NoError(ran.Err, "a withheld passage is no broken tool")
s.Contains(ran.Result, "Delivery is free over $50.")
s.Contains(ran.Result, "Orders ship within two days.")
s.NotContains(ran.Result, "Returns are accepted", "the refused passage never reaches the model")
s.NotContains(ran.Result, "planted.md")
s.Contains(ran.Result, "The prompt injection screen withheld one passage that matched.")
s.eventually(func() bool { return countOf[LookedUp](s.reported()) == 1 }, "nothing was looked up")
looked, _ := firstOf[LookedUp](s.reported())
s.Equal(2, looked.Documents, "only the passages the model reads are counted")
}

func (s *AgentSuite) TestALookupWithholdsAPassageTheScreenRefusedForItsText() {
s.reads(
knowledge.Document{Text: "Delivery is free over $50.", Source: "shipping.md"},
knowledge.Document{Text: "Returns are accepted within 30 days.", Source: "returns.md"},
)
s.screensKnowledge = refusesPassages("Returns are accepted")
s.join(false)
s.model.reply = []string{"Let me check that."}
s.asksFor("lookup", `{"query":"what does delivery cost"}`)
participant := stt.Participant{ID: "alice"}
s.speak(participant)

s.says(participant, "how much is delivery")

ran := s.awaitToolRan()
s.NoError(ran.Err)
s.Contains(ran.Result, "Delivery is free over $50.")
s.NotContains(ran.Result, "returns.md", "the screen reads the passage's text, not only its source")
s.Contains(ran.Result, "The prompt injection screen withheld one passage that matched.")
}

func (s *AgentSuite) TestThePassageScreenIsAskedAsTheAgentsApp() {
s.reads(knowledge.Document{Text: "Delivery is free over $50.", Source: "shipping.md"})
var mu sync.Mutex
var asked []string
s.screensKnowledge = func(_ context.Context, owner routing.Owner, _ string) error {
mu.Lock()
defer mu.Unlock()
asked = append(asked, owner.CustomerID)
return nil
}
s.join(false)
s.model.reply = []string{"Let me check that."}
s.asksFor("lookup", `{"query":"what does delivery cost"}`)
participant := stt.Participant{ID: "alice"}
s.speak(participant)

s.says(participant, "how much is delivery")

s.NoError(s.awaitToolRan().Err)
mu.Lock()
defer mu.Unlock()
s.Equal([]string{"acme"}, asked, "the app's id decides whose policy screens the passage")
}

func (s *AgentSuite) TestALookupWhoseEveryPassageWasRefusedSaysHowMany() {
s.reads(
knowledge.Document{Text: "Returns are accepted within 30 days.", Source: "planted.md"},
knowledge.Document{Text: "Refunds take a week.", Source: "planted.md"},
)
s.screensKnowledge = refusesPassages("planted.md")
s.join(false)
s.model.reply = []string{"One moment."}
s.asksFor("lookup", `{"query":"how do returns work"}`)
participant := stt.Participant{ID: "alice"}
s.speak(participant)

s.says(participant, "how do I return this")

ran := s.awaitToolRan()
s.NoError(ran.Err)
s.NotContains(ran.Result, "Refunds take a week.")
s.Contains(ran.Result, "The prompt injection screen withheld 2 passages that matched.")
}

func (s *AgentSuite) TestALookupTheScreenPassesIsAnsweredWhole() {
passages := []knowledge.Document{
{Text: "Delivery is free over $50.", Source: "shipping.md"},
{Text: "Orders ship within two days.", Source: "dispatch.md"},
}
s.reads(passages...)
s.screensKnowledge = refusesPassages("planted.md")
s.join(false)
s.model.reply = []string{"Let me check that."}
s.asksFor("lookup", `{"query":"what does delivery cost"}`)
participant := stt.Participant{ID: "alice"}
s.speak(participant)

s.says(participant, "how much is delivery")

ran := s.awaitToolRan()
s.NoError(ran.Err)
s.Equal(knowledge.Prompt(passages), ran.Result, "the answer is what it is with no screen")
}

func (s *AgentSuite) TestAQuestionTheKnowledgeBaseDoesNotCoverIsAnsweredInWords() {
// An empty answer would have the model invent one, which on a support line is worse
// than admitting the handbook says nothing.
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/policies.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ type Policy struct {
Budget map[string]any `json:"budget,omitempty" deprecated:"true" doc:"Removed: spend limits are /v1/spend/limits, at every level. A policy that sends budget is refused with 400 budget_moved, and none is read back."`
Quota *Quota `json:"quota,omitempty"`
DataPolicy *PolicyDataPolicy `json:"data_policy,omitempty"`
PromptInjection *bool `json:"prompt_injection,omitempty" doc:"Screen what every LLM response is asked for prompt injection. The newest input - the user's turn and any tool results - goes to a decision model beside the model call, so it adds nothing to time to first token. The end of the response is held until the verdict, and a response whose input reads as an injection fails with prompt_injection before its tool calls can be acted on."`
PromptInjection *bool `json:"prompt_injection,omitempty" doc:"Check what each LLM response is about to read for prompt injection: the user's turn and any tool results. The check runs while the model answers, so it adds nothing to time to first token. If the input reads as an injection, the response fails with prompt_injection before its tool calls can be acted on. The check can't read images, so a response whose newest input has an image fails with prompt_injection too. That includes photos, camera and video frames, and screenshots a tool returns, so leave this off for an agent that has to see. A passage a knowledge lookup finds is checked before the model reads it, and a passage that reads as an injection is left out of the lookup's answer."`
PromptInjectionFailClosed *bool `json:"prompt_injection_fail_closed,omitempty" doc:"Refuse a response when the prompt injection screen cannot check it, for example because the decision model is down or too slow. The response then fails with prompt_injection_unchecked (a 503 you can retry), and its tool calls are not acted on. With no decision model on this deployment, every screened response is refused. Left out or false, such a response goes through unchecked. It only applies where prompt_injection is on. True at either scope turns it on, so an app cannot turn its organization's off."`
AllowedModels *[]string `json:"allowed_models,omitempty" example:"[\"deepseek/DeepSeek-V4-Flash-0731\"]" doc:"The only models requests may be routed to, as provider/model names, in every modality. Left out allows every model, and an empty list allows none. A request that could only go to models not on the list is refused, and a failover never reaches one."`
Tags map[string]string `json:"tags,omitempty" example:"{\"application\":\"support\"}" doc:"Labels recorded on every row of usage, over whatever the request labelled it with, so spend is attributed whatever a caller sends. Together with the request's own they must fit in 16 tags."`
Expand Down
5 changes: 5 additions & 0 deletions acceleration/internal/api/router_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,11 @@ func (s *RouterSuite) routers(limiter *quota.Limiter, gate routing.Gate, logger
return &scriptedLLM{refuses: fmt.Errorf("%w: instruction_override", policy.ErrPromptInjection)}, nil
})

// A model whose every request fails as a response with an image does while the screen is on.
reasoning.Register("unreadable", func(routing.Spec) (llmrouter.Provider, error) {
return &scriptedLLM{refuses: fmt.Errorf("%w: %w", policy.ErrPromptInjection, policy.ErrScreenImages)}, nil
})

// A model whose every request fails as a response does when the screen could not check
// its input under a policy that fails closed.
reasoning.Register("unchecked", func(routing.Spec) (llmrouter.Provider, error) {
Expand Down
Loading
Loading