Prepare structured D&D reference context
This commit is contained in:
205
internal/modules/dnd/shared/context.go
Normal file
205
internal/modules/dnd/shared/context.go
Normal file
@@ -0,0 +1,205 @@
|
||||
package shared
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"mime"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/integrations/domainrefs"
|
||||
)
|
||||
|
||||
// PreparedContext holds immutable, task-specific reference material.
|
||||
type PreparedContext struct {
|
||||
party, glossary, players contracts.LLMInputMaterial
|
||||
}
|
||||
|
||||
type partyMember struct {
|
||||
Name string `json:"name"`
|
||||
Aliases []string `json:"aliases,omitempty"`
|
||||
Player string `json:"player,omitempty"`
|
||||
Classes []partyClass `json:"classes,omitempty"`
|
||||
}
|
||||
|
||||
type partyClass struct {
|
||||
Name string `json:"name"`
|
||||
Level any `json:"level,omitempty"`
|
||||
}
|
||||
|
||||
type glossaryEntry struct {
|
||||
Name string `json:"name"`
|
||||
Aliases []string `json:"aliases,omitempty"`
|
||||
Category string `json:"category"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Plural *string `json:"plural,omitempty"`
|
||||
}
|
||||
|
||||
// PrepareContext validates supplied typed references and prepares model-facing views.
|
||||
func PrepareContext(references contracts.ReferenceSet) (PreparedContext, error) {
|
||||
if err := ValidateReferenceSelections(references); err != nil {
|
||||
return PreparedContext{}, err
|
||||
}
|
||||
party, partyBound, err := prepareParty(references.Slots["party"], "party")
|
||||
if err != nil {
|
||||
return PreparedContext{}, err
|
||||
}
|
||||
roster, _, err := prepareParty(references.Slots["roster"], "roster")
|
||||
if err != nil {
|
||||
return PreparedContext{}, err
|
||||
}
|
||||
if !partyBound {
|
||||
party = roster
|
||||
}
|
||||
glossary, err := prepareGlossary(references.Slots["glossary"])
|
||||
if err != nil {
|
||||
return PreparedContext{}, err
|
||||
}
|
||||
return PreparedContext{
|
||||
party: party,
|
||||
glossary: glossary,
|
||||
players: ReferencePromptMaterial("players", references.Slots["players"]),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Inputs combines fixed reference context with the current transcript.
|
||||
func (context PreparedContext) Inputs(source contracts.LLMInputMaterial) contracts.LLMInputSet {
|
||||
return contracts.LLMInputSet{
|
||||
"transcript": TranscriptPromptMaterial(source),
|
||||
"party": context.party.Clone(),
|
||||
"glossary": context.glossary.Clone(),
|
||||
"players": context.players.Clone(),
|
||||
}
|
||||
}
|
||||
|
||||
func referenceDocument(slot contracts.ResolvedReferenceSlot, name string) (map[string]any, *contracts.ReferenceItem, error) {
|
||||
if len(slot.Items) == 0 {
|
||||
return nil, nil, nil
|
||||
}
|
||||
if len(slot.Items) != 1 {
|
||||
return nil, nil, fmt.Errorf("reference slot %q must contain zero or one item", name)
|
||||
}
|
||||
item := &slot.Items[0]
|
||||
mediaType, _, err := mime.ParseMediaType(item.MediaType)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("reference slot %q: invalid media type: %w", name, err)
|
||||
}
|
||||
doc, err := domainrefs.Load(name, strings.ToLower(mediaType), item.Content)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return doc, item, nil
|
||||
}
|
||||
|
||||
func prepareParty(slot contracts.ResolvedReferenceSlot, name string) (contracts.LLMInputMaterial, bool, error) {
|
||||
doc, item, err := referenceDocument(slot, name)
|
||||
if err != nil {
|
||||
return contracts.LLMInputMaterial{}, false, err
|
||||
}
|
||||
if item == nil {
|
||||
return contextMaterial("party", nil), false, nil
|
||||
}
|
||||
if err := domainrefs.ValidateParty(doc); err != nil {
|
||||
return contracts.LLMInputMaterial{}, false, fmt.Errorf("reference slot %q: %w", name, err)
|
||||
}
|
||||
characters := doc["characters"].(map[string]any)
|
||||
ids := make([]string, 0, len(characters))
|
||||
for id := range characters {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
members := make([]partyMember, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
entry := characters[id].(map[string]any)
|
||||
character := entry["character"].(map[string]any)
|
||||
member := partyMember{Name: character["name"].(string), Aliases: stringList(character["aliases"])}
|
||||
if player, ok := entry["player"].(map[string]any); ok {
|
||||
member.Player = player["name"].(string)
|
||||
}
|
||||
if classes, ok := character["classes"].([]any); ok {
|
||||
for _, raw := range classes {
|
||||
class := raw.(map[string]any)
|
||||
member.Classes = append(member.Classes, partyClass{Name: class["name"].(string), Level: class["level"]})
|
||||
}
|
||||
}
|
||||
members = append(members, member)
|
||||
}
|
||||
content, err := json.Marshal(members)
|
||||
if err != nil {
|
||||
return contracts.LLMInputMaterial{}, false, fmt.Errorf("reference slot %q projection: %w", name, err)
|
||||
}
|
||||
if len(members) == 0 {
|
||||
content = nil
|
||||
}
|
||||
return contextMaterial("party", content), true, nil
|
||||
}
|
||||
|
||||
func prepareGlossary(slot contracts.ResolvedReferenceSlot) (contracts.LLMInputMaterial, error) {
|
||||
doc, item, err := referenceDocument(slot, "glossary")
|
||||
if err != nil {
|
||||
return contracts.LLMInputMaterial{}, err
|
||||
}
|
||||
if item == nil {
|
||||
return contextMaterial("glossary", nil), nil
|
||||
}
|
||||
if err := domainrefs.ValidateGlossary(doc); err != nil {
|
||||
return contracts.LLMInputMaterial{}, fmt.Errorf("reference slot %q: %w", "glossary", err)
|
||||
}
|
||||
collections := doc["collections"].(map[string]any)
|
||||
var defaults []string
|
||||
for _, name := range []string{"campaign", "setting"} {
|
||||
if _, ok := collections[name]; ok {
|
||||
defaults = append(defaults, name)
|
||||
}
|
||||
}
|
||||
names, err := domainrefs.SelectCollections(doc, item.Collections, defaults)
|
||||
if err != nil {
|
||||
return contracts.LLMInputMaterial{}, fmt.Errorf("reference slot %q: %w", "glossary", err)
|
||||
}
|
||||
var projected []glossaryEntry
|
||||
for _, name := range names {
|
||||
entries := append([]any(nil), collections[name].(map[string]any)["entries"].([]any)...)
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
return entries[i].(map[string]any)["id"].(string) < entries[j].(map[string]any)["id"].(string)
|
||||
})
|
||||
for _, raw := range entries {
|
||||
entry := raw.(map[string]any)
|
||||
value := glossaryEntry{Name: entry["name"].(string), Category: entry["category"].(string), Aliases: stringList(entry["aliases"])}
|
||||
if description, ok := entry["description"].(string); ok {
|
||||
value.Description = &description
|
||||
}
|
||||
if plural, ok := entry["plural"].(string); ok {
|
||||
value.Plural = &plural
|
||||
}
|
||||
projected = append(projected, value)
|
||||
}
|
||||
}
|
||||
var content []byte
|
||||
if len(projected) != 0 {
|
||||
content, err = json.Marshal(projected)
|
||||
if err != nil {
|
||||
return contracts.LLMInputMaterial{}, fmt.Errorf("reference slot %q projection: %w", "glossary", err)
|
||||
}
|
||||
}
|
||||
return contextMaterial("glossary", content), nil
|
||||
}
|
||||
|
||||
func stringList(value any) []string {
|
||||
items, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
result := make([]string, len(items))
|
||||
for i, item := range items {
|
||||
result[i] = item.(string)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func contextMaterial(name string, content []byte) contracts.LLMInputMaterial {
|
||||
if len(content) == 0 {
|
||||
content = []byte(" ")
|
||||
}
|
||||
return contracts.NewLLMInputMaterial(name, "text/plain", content, "", "")
|
||||
}
|
||||
90
internal/modules/dnd/shared/context_test.go
Normal file
90
internal/modules/dnd/shared/context_test.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package shared
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
func contextReference(content string, collections []string) contracts.ResolvedReferenceSlot {
|
||||
return contracts.ResolvedReferenceSlot{Items: []contracts.ReferenceItem{{MediaType: "application/json", Content: []byte(content), Collections: collections}}}
|
||||
}
|
||||
|
||||
func TestPreparedContextProjectsSelectedReferences(t *testing.T) {
|
||||
party := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"z":{"character":{"name":"Mira","aliases":["Shadow"],"classes":[{"name":"Ranger","level":3}]},"player":{"name":"Dana"}},"a":{"character":{"name":"Mira"},"player":{"name":"Lee"}}},"instruction":"not a prompt"}`
|
||||
glossary := `{"schema_version":"maximumdirect.glossary.v1","collections":{"campaign":{"entries":[{"id":"z","name":"Greencloak","category":"title","aliases":["Green"],"description":"local title","plural":"Greencloaks","instruction":"not a prompt"}]},"setting":{"entries":[]},"spells":{"entries":[{"id":"x","name":"Hidden Spell","category":"spell"}]}}}`
|
||||
references := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"party": contextReference(party, nil),
|
||||
"glossary": contextReference(glossary, nil),
|
||||
"players": {Items: []contracts.ReferenceItem{{Content: []byte("Supplemental players")}}},
|
||||
}}
|
||||
prepared, err := PrepareContext(references)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inputs := prepared.Inputs(contracts.NewLLMInputMaterial("source", "text/plain", []byte("current transcript"), "", ""))
|
||||
partyBody := string(inputs["party"].Content)
|
||||
if strings.Count(partyBody, `"name":"Mira"`) != 2 || !strings.Contains(partyBody, "Shadow") || !strings.Contains(partyBody, "Dana") || !strings.Contains(partyBody, "Ranger") || strings.Index(partyBody, "Lee") > strings.Index(partyBody, "Dana") {
|
||||
t.Fatalf("party projection = %s", partyBody)
|
||||
}
|
||||
glossaryBody := string(inputs["glossary"].Content)
|
||||
for _, value := range []string{"Greencloak", "Green", "title", "local title", "Greencloaks"} {
|
||||
if !strings.Contains(glossaryBody, value) {
|
||||
t.Fatalf("glossary projection missing %q: %s", value, glossaryBody)
|
||||
}
|
||||
}
|
||||
if strings.Contains(glossaryBody, "Hidden Spell") || strings.Contains(partyBody+glossaryBody, "not a prompt") || strings.Contains(glossaryBody, `"id"`) {
|
||||
t.Fatal("irrelevant document content reached model context")
|
||||
}
|
||||
if string(inputs["players"].Content) != "Supplemental players" || string(inputs["transcript"].Content) != "current transcript" {
|
||||
t.Fatalf("supplemental context or transcript changed: %#v", inputs)
|
||||
}
|
||||
inputs["party"].Content[0] = '!'
|
||||
if strings.HasPrefix(string(prepared.Inputs(contracts.LLMInputMaterial{})["party"].Content), "!") {
|
||||
t.Fatal("caller mutated prepared context")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreparedContextValidatesAllTypedSlotsAndSelection(t *testing.T) {
|
||||
validParty := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Aria"}}}}`
|
||||
glossary := `{"schema_version":"maximumdirect.glossary.v1","collections":{"other":{"entries":[{"id":"a","name":"Chosen","category":"term"}]}}}`
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{
|
||||
"party": contextReference(validParty, nil),
|
||||
"roster": contextReference("{}", nil),
|
||||
}}
|
||||
if _, err := PrepareContext(refs); err == nil || !strings.Contains(err.Error(), "roster") {
|
||||
t.Fatalf("invalid overridden roster accepted: %v", err)
|
||||
}
|
||||
delete(refs.Slots, "roster")
|
||||
refs.Slots["glossary"] = contextReference(glossary, []string{"other"})
|
||||
got, err := PrepareContext(refs)
|
||||
if err != nil || !strings.Contains(string(got.Inputs(contracts.LLMInputMaterial{})["glossary"].Content), "Chosen") {
|
||||
t.Fatalf("selected glossary missing: %v", err)
|
||||
}
|
||||
refs.Slots["glossary"] = contextReference(glossary, []string{})
|
||||
got, err = PrepareContext(refs)
|
||||
if err != nil || string(got.Inputs(contracts.LLMInputMaterial{})["glossary"].Content) != " " {
|
||||
t.Fatalf("empty selection = %#v, %v", got, err)
|
||||
}
|
||||
refs.Slots["glossary"] = contextReference(glossary, []string{"missing"})
|
||||
if _, err := PrepareContext(refs); err == nil || !strings.Contains(err.Error(), "missing") {
|
||||
t.Fatalf("missing selection accepted: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreparedContextRosterFallbackAndPartyPrecedence(t *testing.T) {
|
||||
party := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"a":{"character":{"name":"Party member"}}}}`
|
||||
roster := `{"schema_version":"maximumdirect.rpg.party.v1","characters":{"b":{"character":{"name":"Roster member"}}}}`
|
||||
refs := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{"roster": contextReference(roster, nil)}}
|
||||
prepared, err := PrepareContext(refs)
|
||||
if err != nil || !strings.Contains(string(prepared.Inputs(contracts.LLMInputMaterial{})["party"].Content), "Roster member") {
|
||||
t.Fatalf("roster fallback: %v", err)
|
||||
}
|
||||
refs.Slots["party"] = contextReference(party, nil)
|
||||
prepared, err = PrepareContext(refs)
|
||||
body := string(prepared.Inputs(contracts.LLMInputMaterial{})["party"].Content)
|
||||
if err != nil || !strings.Contains(body, "Party member") || strings.Contains(body, "Roster member") {
|
||||
t.Fatalf("party precedence = %q, %v", body, err)
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,16 @@ var referenceMediaTypes = []string{
|
||||
"text/plain",
|
||||
}
|
||||
|
||||
var structuredReferenceMediaTypes = []string{
|
||||
"application/json",
|
||||
"application/x-yaml",
|
||||
"application/yaml",
|
||||
}
|
||||
|
||||
func StructuredReferenceMediaTypes() []string {
|
||||
return append([]string(nil), structuredReferenceMediaTypes...)
|
||||
}
|
||||
|
||||
func ReferenceMediaTypes() []string {
|
||||
return append([]string(nil), referenceMediaTypes...)
|
||||
}
|
||||
@@ -51,12 +61,12 @@ func ReferenceSlots(descriptions ReferenceSlotDescriptions) []contracts.Referenc
|
||||
{
|
||||
Name: "glossary",
|
||||
Description: descriptions.Glossary,
|
||||
AcceptedMediaTypes: ReferenceMediaTypes(),
|
||||
AcceptedMediaTypes: StructuredReferenceMediaTypes(),
|
||||
},
|
||||
{
|
||||
Name: "party",
|
||||
Description: descriptions.Party,
|
||||
AcceptedMediaTypes: ReferenceMediaTypes(),
|
||||
AcceptedMediaTypes: StructuredReferenceMediaTypes(),
|
||||
},
|
||||
{
|
||||
Name: "players",
|
||||
@@ -66,7 +76,7 @@ func ReferenceSlots(descriptions ReferenceSlotDescriptions) []contracts.Referenc
|
||||
{
|
||||
Name: "roster",
|
||||
Description: descriptions.Roster,
|
||||
AcceptedMediaTypes: ReferenceMediaTypes(),
|
||||
AcceptedMediaTypes: StructuredReferenceMediaTypes(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -50,10 +50,10 @@ func TestReferenceSlotsUseDescriptionsAndExpectedOrder(t *testing.T) {
|
||||
}
|
||||
got := ReferenceSlots(descriptions)
|
||||
want := []contracts.ReferenceSlot{
|
||||
{Name: "glossary", Description: descriptions.Glossary, AcceptedMediaTypes: ReferenceMediaTypes()},
|
||||
{Name: "party", Description: descriptions.Party, AcceptedMediaTypes: ReferenceMediaTypes()},
|
||||
{Name: "glossary", Description: descriptions.Glossary, AcceptedMediaTypes: StructuredReferenceMediaTypes()},
|
||||
{Name: "party", Description: descriptions.Party, AcceptedMediaTypes: StructuredReferenceMediaTypes()},
|
||||
{Name: "players", Description: descriptions.Players, AcceptedMediaTypes: ReferenceMediaTypes()},
|
||||
{Name: "roster", Description: descriptions.Roster, AcceptedMediaTypes: ReferenceMediaTypes()},
|
||||
{Name: "roster", Description: descriptions.Roster, AcceptedMediaTypes: StructuredReferenceMediaTypes()},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ReferenceSlots() = %#v, want %#v", got, want)
|
||||
|
||||
Reference in New Issue
Block a user