InjectContext 注入上下文到系统提示词
(ctx context.Context, systemPrompt string)
| 36 | |
| 37 | // InjectContext 注入上下文到系统提示词 |
| 38 | func (ci *ContextInjector) InjectContext(ctx context.Context, systemPrompt string) string { |
| 39 | var additions []string |
| 40 | |
| 41 | // 注入日期时间 |
| 42 | if ci.config.EnableDateTime { |
| 43 | additions = append(additions, ci.buildDateTimeContext()) |
| 44 | } |
| 45 | |
| 46 | // 注入位置信息 |
| 47 | if ci.config.EnableLocation && ci.config.LocationProvider != nil { |
| 48 | if locCtx := ci.buildLocationContext(ctx); locCtx != "" { |
| 49 | additions = append(additions, locCtx) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // 注入 Session 状态 |
| 54 | if ci.config.EnableSessionState && ci.config.SessionStateProvider != nil { |
| 55 | if stateCtx := ci.buildSessionStateContext(ctx); stateCtx != "" { |
| 56 | additions = append(additions, stateCtx) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // 注入用户信息 |
| 61 | if ci.config.EnableUserInfo && ci.config.UserInfoProvider != nil { |
| 62 | if userCtx := ci.buildUserInfoContext(ctx); userCtx != "" { |
| 63 | additions = append(additions, userCtx) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // 注入系统信息 |
| 68 | if ci.config.EnableSystemInfo { |
| 69 | additions = append(additions, ci.buildSystemInfoContext()) |
| 70 | } |
| 71 | |
| 72 | // 注入自定义上下文 |
| 73 | if ci.config.CustomContext != "" { |
| 74 | additions = append(additions, ci.config.CustomContext) |
| 75 | } |
| 76 | |
| 77 | // 如果没有需要注入的内容,直接返回原始提示词 |
| 78 | if len(additions) == 0 { |
| 79 | return systemPrompt |
| 80 | } |
| 81 | |
| 82 | // 构建完整的系统提示词 |
| 83 | var builder strings.Builder |
| 84 | builder.WriteString(systemPrompt) |
| 85 | |
| 86 | if !strings.HasSuffix(systemPrompt, "\n") { |
| 87 | builder.WriteString("\n") |
| 88 | } |
| 89 | |
| 90 | builder.WriteString("\n## Context Information\n\n") |
| 91 | builder.WriteString(strings.Join(additions, "\n\n")) |
| 92 | |
| 93 | return builder.String() |
| 94 | } |
| 95 |