use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use crate::KeepClient;
use crate::error::Result;
use crate::scope::Scope;
pub const FORGET_SOURCES_LIMIT: usize = 1000;
pub const SOURCE_ALLOWLIST_LIMIT: usize = 1000;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Episode {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub speaker: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub occurred_at: Option<String>,
pub text: String,
}
impl Episode {
pub fn new(text: impl Into<String>) -> Self {
Self {
id: None,
speaker: None,
occurred_at: None,
text: text.into(),
}
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn speaker(mut self, speaker: impl Into<String>) -> Self {
self.speaker = Some(speaker.into());
self
}
pub fn occurred_at(mut self, occurred_at: impl Into<String>) -> Self {
self.occurred_at = Some(occurred_at.into());
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct KnowledgeIngestRequest {
pub source_id: Option<String>,
pub title: Option<String>,
pub collection: Option<String>,
pub kind: Option<String>,
pub text: Option<String>,
pub occurred_at: Option<String>,
pub episodes: Option<Vec<Episode>>,
pub metadata: Option<BTreeMap<String, String>>,
pub replace: bool,
}
impl KnowledgeIngestRequest {
pub fn document(text: impl Into<String>) -> Self {
Self {
text: Some(text.into()),
..Self::default()
}
}
pub fn episodes(episodes: Vec<Episode>) -> Self {
Self {
episodes: Some(episodes),
..Self::default()
}
}
pub fn source_id(mut self, source_id: impl Into<String>) -> Self {
self.source_id = Some(source_id.into());
self
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn collection(mut self, collection: impl Into<String>) -> Self {
self.collection = Some(collection.into());
self
}
pub fn kind(mut self, kind: impl Into<String>) -> Self {
self.kind = Some(kind.into());
self
}
pub fn occurred_at(mut self, occurred_at: impl Into<String>) -> Self {
self.occurred_at = Some(occurred_at.into());
self
}
pub fn metadata(mut self, metadata: BTreeMap<String, String>) -> Self {
self.metadata = Some(metadata);
self
}
pub fn replace(mut self, replace: bool) -> Self {
self.replace = replace;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IngestReport {
#[serde(default)]
pub episodes_added: i64,
#[serde(default)]
pub episodes_unchanged: i64,
#[serde(default)]
pub replaced: bool,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KnowledgeIngestResult {
pub scope: String,
pub source_id: String,
pub partition: String,
pub collection: String,
#[serde(default)]
pub captured: bool,
#[serde(default)]
pub replaced: bool,
pub report: IngestReport,
#[serde(default)]
pub jobs: Value,
#[serde(default)]
pub enrichment: Value,
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct KnowledgeSearchRequest {
pub query: String,
pub limit: Option<usize>,
pub budget_tokens: Option<usize>,
pub as_of: Option<String>,
pub valid_at: Option<String>,
pub source_ids: Option<Vec<String>>,
pub collections: Option<Vec<String>>,
}
impl KnowledgeSearchRequest {
pub fn new(query: impl Into<String>) -> Self {
Self {
query: query.into(),
limit: None,
budget_tokens: None,
as_of: None,
valid_at: None,
source_ids: None,
collections: None,
}
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn budget_tokens(mut self, tokens: usize) -> Self {
self.budget_tokens = Some(tokens);
self
}
pub fn as_of(mut self, as_of: impl Into<String>) -> Self {
self.as_of = Some(as_of.into());
self
}
pub fn valid_at(mut self, valid_at: impl Into<String>) -> Self {
self.valid_at = Some(valid_at.into());
self
}
pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
self.source_ids = Some(source_ids);
self
}
pub fn collections(mut self, collections: Vec<String>) -> Self {
self.collections = Some(collections);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ItemRef {
pub kind: String,
pub id: String,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Citation {
#[serde(default)]
pub reference: String,
pub source_id: String,
#[serde(default)]
pub source_title: String,
#[serde(default)]
pub episode_id: String,
#[serde(default)]
pub speaker: String,
#[serde(default)]
pub occurred_at: Option<String>,
#[serde(default)]
pub char_start: i32,
#[serde(default)]
pub char_end: i32,
#[serde(default)]
pub quote: String,
#[serde(default)]
pub source_metadata: BTreeMap<String, String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SearchHit {
pub item: ItemRef,
#[serde(default)]
pub rank: usize,
pub score: f64,
pub text: String,
#[serde(default)]
pub tokens: usize,
pub source_id: String,
#[serde(default)]
pub occurred_at: Option<String>,
#[serde(default)]
pub fact: Option<Value>,
pub citation: Citation,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Allowance {
pub limit: usize,
pub used: usize,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KnowledgeSearchResult {
pub scope: String,
#[serde(default)]
pub hits: Vec<SearchHit>,
#[serde(default)]
pub used_tokens: usize,
#[serde(default)]
pub omitted: usize,
#[serde(default)]
pub degraded: Vec<String>,
#[serde(default)]
pub method: String,
#[serde(default)]
pub allowance: Option<Allowance>,
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct KnowledgeFetchRequest {
pub id: String,
pub budget_tokens: Option<usize>,
pub as_of: Option<String>,
pub valid_at: Option<String>,
pub source_ids: Option<Vec<String>>,
pub collections: Option<Vec<String>>,
}
impl KnowledgeFetchRequest {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
budget_tokens: None,
as_of: None,
valid_at: None,
source_ids: None,
collections: None,
}
}
pub fn budget_tokens(mut self, tokens: usize) -> Self {
self.budget_tokens = Some(tokens);
self
}
pub fn as_of(mut self, as_of: impl Into<String>) -> Self {
self.as_of = Some(as_of.into());
self
}
pub fn valid_at(mut self, valid_at: impl Into<String>) -> Self {
self.valid_at = Some(valid_at.into());
self
}
pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
self.source_ids = Some(source_ids);
self
}
pub fn collections(mut self, collections: Vec<String>) -> Self {
self.collections = Some(collections);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct KnowledgeCiteRequest {
pub id: String,
pub source_ids: Option<Vec<String>>,
pub collections: Option<Vec<String>>,
}
impl KnowledgeCiteRequest {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
source_ids: None,
collections: None,
}
}
pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
self.source_ids = Some(source_ids);
self
}
pub fn collections(mut self, collections: Vec<String>) -> Self {
self.collections = Some(collections);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KnowledgeCitations {
pub scope: String,
pub id: String,
#[serde(default)]
pub citations: Vec<Citation>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct KnowledgeIndexRequest {
pub level: u8,
pub collection: Option<String>,
pub prefix: Option<String>,
pub cursor: Option<usize>,
pub budget_tokens: Option<usize>,
pub source_ids: Option<Vec<String>>,
pub collections: Option<Vec<String>>,
}
impl KnowledgeIndexRequest {
pub fn level(level: u8) -> Self {
Self {
level,
..Self::default()
}
}
pub fn collection(mut self, collection: impl Into<String>) -> Self {
self.collection = Some(collection.into());
self
}
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
pub fn cursor(mut self, cursor: usize) -> Self {
self.cursor = Some(cursor);
self
}
pub fn budget_tokens(mut self, tokens: usize) -> Self {
self.budget_tokens = Some(tokens);
self
}
pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
self.source_ids = Some(source_ids);
self
}
pub fn collections(mut self, collections: Vec<String>) -> Self {
self.collections = Some(collections);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct KnowledgeTraverseRequest {
pub start: String,
pub depth: Option<usize>,
pub fanout: Option<usize>,
pub as_of: Option<String>,
pub valid_at: Option<String>,
pub source_ids: Option<Vec<String>>,
pub collections: Option<Vec<String>>,
}
impl KnowledgeTraverseRequest {
pub fn new(start: impl Into<String>) -> Self {
Self {
start: start.into(),
depth: None,
fanout: None,
as_of: None,
valid_at: None,
source_ids: None,
collections: None,
}
}
pub fn depth(mut self, depth: usize) -> Self {
self.depth = Some(depth);
self
}
pub fn fanout(mut self, fanout: usize) -> Self {
self.fanout = Some(fanout);
self
}
pub fn as_of(mut self, as_of: impl Into<String>) -> Self {
self.as_of = Some(as_of.into());
self
}
pub fn valid_at(mut self, valid_at: impl Into<String>) -> Self {
self.valid_at = Some(valid_at.into());
self
}
pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
self.source_ids = Some(source_ids);
self
}
pub fn collections(mut self, collections: Vec<String>) -> Self {
self.collections = Some(collections);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct KnowledgeSummarizeRequest {
pub source_id: Option<String>,
pub text: Option<String>,
pub episodes: Option<Vec<Episode>>,
pub source_ids: Option<Vec<String>>,
pub collections: Option<Vec<String>>,
}
impl KnowledgeSummarizeRequest {
pub fn source_id(source_id: impl Into<String>) -> Self {
Self {
source_id: Some(source_id.into()),
..Self::default()
}
}
pub fn text(text: impl Into<String>) -> Self {
Self {
text: Some(text.into()),
..Self::default()
}
}
pub fn episodes(episodes: Vec<Episode>) -> Self {
Self {
episodes: Some(episodes),
..Self::default()
}
}
pub fn source_ids(mut self, source_ids: Vec<String>) -> Self {
self.source_ids = Some(source_ids);
self
}
pub fn collections(mut self, collections: Vec<String>) -> Self {
self.collections = Some(collections);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenUsage {
pub input_tokens: u64,
pub output_tokens: u64,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KnowledgeSummary {
pub scope: String,
pub summary: String,
pub model: String,
pub usage: TokenUsage,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KnowledgeStatus {
pub scope: String,
pub enrichment: Value,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForgetSourceReceipt {
pub episodes: i64,
pub chunks: i64,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ForgottenSource {
pub source_id: String,
pub receipt: ForgetSourceReceipt,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KnowledgeForgetSourceResult {
pub scope: String,
pub source_id: String,
pub receipt: ForgetSourceReceipt,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KnowledgeForgetSourcesResult {
pub scope: String,
pub forgotten: Vec<ForgottenSource>,
pub missing: Vec<String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KnowledgeRebuildResult {
pub scope: String,
pub queued: usize,
pub jobs: Value,
}
#[derive(Debug, Clone, Copy)]
pub struct KnowledgeClient<'a> {
client: &'a KeepClient,
scope: Option<&'a Scope>,
}
impl<'a> KnowledgeClient<'a> {
pub(crate) fn new(client: &'a KeepClient, scope: Option<&'a Scope>) -> Self {
Self { client, scope }
}
fn base_body(&self) -> Map<String, Value> {
let mut body = Map::new();
if let Some(scope) = self.scope
&& !scope.is_empty()
{
body.insert("scope".into(), json!(scope));
}
body
}
pub async fn ingest(&self, req: KnowledgeIngestRequest) -> Result<KnowledgeIngestResult> {
let mut body = self.base_body();
if let Some(source_id) = req.source_id {
body.insert("source_id".into(), json!(source_id));
}
if let Some(title) = req.title {
body.insert("title".into(), json!(title));
}
if let Some(collection) = req.collection {
body.insert("collection".into(), json!(collection));
}
if let Some(kind) = req.kind {
body.insert("kind".into(), json!(kind));
}
if let Some(text) = req.text {
body.insert("text".into(), json!(text));
}
if let Some(occurred_at) = req.occurred_at {
body.insert("occurred_at".into(), json!(occurred_at));
}
if let Some(episodes) = req.episodes {
body.insert("episodes".into(), json!(episodes));
}
if let Some(metadata) = req.metadata {
body.insert("metadata".into(), json!(metadata));
}
if req.replace {
body.insert("replace".into(), json!(true));
}
self.client
.post_json("/v1/knowledge/ingest", Value::Object(body))
.await
}
pub async fn search(&self, req: KnowledgeSearchRequest) -> Result<KnowledgeSearchResult> {
let mut body = self.base_body();
body.insert("query".into(), json!(req.query));
if let Some(limit) = req.limit {
body.insert("limit".into(), json!(limit));
}
if let Some(budget_tokens) = req.budget_tokens {
body.insert("budget_tokens".into(), json!(budget_tokens));
}
if let Some(as_of) = req.as_of {
body.insert("as_of".into(), json!(as_of));
}
if let Some(valid_at) = req.valid_at {
body.insert("valid_at".into(), json!(valid_at));
}
if let Some(source_ids) = req.source_ids {
body.insert("source_ids".into(), json!(source_ids));
}
if let Some(collections) = req.collections {
body.insert("collections".into(), json!(collections));
}
self.client
.post_json("/v1/knowledge/search", Value::Object(body))
.await
}
pub async fn fetch(&self, req: KnowledgeFetchRequest) -> Result<Value> {
let mut body = self.base_body();
body.insert("id".into(), json!(req.id));
if let Some(budget_tokens) = req.budget_tokens {
body.insert("budget_tokens".into(), json!(budget_tokens));
}
if let Some(as_of) = req.as_of {
body.insert("as_of".into(), json!(as_of));
}
if let Some(valid_at) = req.valid_at {
body.insert("valid_at".into(), json!(valid_at));
}
if let Some(source_ids) = req.source_ids {
body.insert("source_ids".into(), json!(source_ids));
}
if let Some(collections) = req.collections {
body.insert("collections".into(), json!(collections));
}
self.client
.post_json("/v1/knowledge/fetch", Value::Object(body))
.await
}
pub async fn cite(&self, req: KnowledgeCiteRequest) -> Result<KnowledgeCitations> {
let mut body = self.base_body();
body.insert("id".into(), json!(req.id));
if let Some(source_ids) = req.source_ids {
body.insert("source_ids".into(), json!(source_ids));
}
if let Some(collections) = req.collections {
body.insert("collections".into(), json!(collections));
}
self.client
.post_json("/v1/knowledge/cite", Value::Object(body))
.await
}
pub async fn index(&self, req: KnowledgeIndexRequest) -> Result<Value> {
let mut body = self.base_body();
body.insert("level".into(), json!(req.level));
if let Some(collection) = req.collection {
body.insert("collection".into(), json!(collection));
}
if let Some(prefix) = req.prefix {
body.insert("prefix".into(), json!(prefix));
}
if let Some(cursor) = req.cursor {
body.insert("cursor".into(), json!(cursor));
}
if let Some(budget_tokens) = req.budget_tokens {
body.insert("budget_tokens".into(), json!(budget_tokens));
}
if let Some(source_ids) = req.source_ids {
body.insert("source_ids".into(), json!(source_ids));
}
if let Some(collections) = req.collections {
body.insert("collections".into(), json!(collections));
}
self.client
.post_json("/v1/knowledge/index", Value::Object(body))
.await
}
pub async fn traverse(&self, req: KnowledgeTraverseRequest) -> Result<Value> {
let mut body = self.base_body();
body.insert("start".into(), json!(req.start));
if let Some(depth) = req.depth {
body.insert("depth".into(), json!(depth));
}
if let Some(fanout) = req.fanout {
body.insert("fanout".into(), json!(fanout));
}
if let Some(as_of) = req.as_of {
body.insert("as_of".into(), json!(as_of));
}
if let Some(valid_at) = req.valid_at {
body.insert("valid_at".into(), json!(valid_at));
}
if let Some(source_ids) = req.source_ids {
body.insert("source_ids".into(), json!(source_ids));
}
if let Some(collections) = req.collections {
body.insert("collections".into(), json!(collections));
}
self.client
.post_json("/v1/knowledge/traverse", Value::Object(body))
.await
}
pub async fn status(&self) -> Result<KnowledgeStatus> {
let body = self.base_body();
self.client
.post_json("/v1/knowledge/status", Value::Object(body))
.await
}
pub async fn summarize(&self, req: KnowledgeSummarizeRequest) -> Result<KnowledgeSummary> {
let mut body = self.base_body();
if let Some(source_id) = req.source_id {
body.insert("source_id".into(), json!(source_id));
}
if let Some(text) = req.text {
body.insert("text".into(), json!(text));
}
if let Some(episodes) = req.episodes {
body.insert("episodes".into(), json!(episodes));
}
if let Some(source_ids) = req.source_ids {
body.insert("source_ids".into(), json!(source_ids));
}
if let Some(collections) = req.collections {
body.insert("collections".into(), json!(collections));
}
self.client
.post_json("/v1/knowledge/summarize", Value::Object(body))
.await
}
pub async fn forget_source(
&self,
source_id: impl Into<String>,
) -> Result<KnowledgeForgetSourceResult> {
let mut body = self.base_body();
body.insert("source_id".into(), json!(source_id.into()));
self.client
.post_json("/v1/knowledge/forget_source", Value::Object(body))
.await
}
pub async fn forget_sources(
&self,
source_ids: Vec<String>,
) -> Result<KnowledgeForgetSourcesResult> {
let mut body = self.base_body();
body.insert("source_ids".into(), json!(source_ids));
self.client
.post_json("/v1/knowledge/forget_sources", Value::Object(body))
.await
}
pub async fn rebuild_projection(&self) -> Result<KnowledgeRebuildResult> {
let body = self.base_body();
self.client
.post_json("/v1/knowledge/rebuild_projection", Value::Object(body))
.await
}
}