Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

chore: remove hyperswitch AI interactions and chat modules (#14006)

Sanchith Hegde0efb2b45cc02
diff --git a/config/config.example.toml b/config/config.example.toml
index a13959b1cd..09ec92d4e2 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1534,10 +1534,6 @@ version = "HOSTNAME" # value of HOSTNAME from deployment which tells its
enabled = true # Enable or disable platform features
allow_connected_merchants = false # Enable or disable connected merchant account features
-[chat]
-enabled = false # Enable or disable chat features
-hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host
-encryption_key = "" # Key to encrypt and decrypt chats
[trace_header]
header_name = "x-request-id" # HTTP header name for request tracing (can be x-trace-id, x-correlation-id, etc.)
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index fd06460df4..d6e79085dc 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -508,10 +508,6 @@ redis_ttl_buffer_in_seconds=300 # buffer time in seconds to be added to redis tt
redis_lock_expiry_seconds = 10 # Seconds before redis lock expires
delay_between_retries_in_milliseconds = 100 # Wait between attempts to acquire a contended lock
-[chat]
-enabled = false # Enable or disable chat features
-hyperswitch_ai_host = "http://0.0.0.0:8000" # Hyperswitch ai workflow host
-encryption_key = "" # Key to encrypt and decrypt chats
[sage]
enabled = false # Master switch for sage sessions
diff --git a/config/development.toml b/config/development.toml
index de53d02f62..27139906db 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -1648,10 +1648,6 @@ wallet = "apple_pay, google_pay, paze, samsung_pay, paypal"
cluster = "CLUSTER"
version = "HOSTNAME"
-[chat]
-enabled = false
-hyperswitch_ai_host = "http://0.0.0.0:8000"
-encryption_key = ""
[sage]
enabled = false # Master switch for sage sessions
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 690fdba633..dc7820d1bf 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -1451,10 +1451,6 @@ background_color = "#FFFFFF"
enabled = true
allow_connected_merchants = true
-[chat]
-enabled = false
-hyperswitch_ai_host = "http://0.0.0.0:8000"
-encryption_key = ""
[sage]
enabled = false # Master switch for sage sessions
diff --git a/crates/api_models/src/chat.rs b/crates/api_models/src/chat.rs
deleted file mode 100644
index 7cdb6e7c0f..0000000000
--- a/crates/api_models/src/chat.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-use common_utils::id_type;
-use hyperswitch_masking::Secret;
-use time::PrimitiveDateTime;
-
-#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
-pub struct ChatRequest {
- pub message: Secret<String>,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
-pub struct ChatResponse {
- pub response: Secret<serde_json::Value>,
- pub merchant_id: id_type::MerchantId,
- pub status: String,
- #[serde(skip_serializing)]
- pub query_executed: Option<Secret<String>>,
- #[serde(skip_serializing)]
- pub row_count: Option<i32>,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct ChatListRequest {
- pub merchant_id: Option<id_type::MerchantId>,
- pub limit: Option<i64>,
- pub offset: Option<i64>,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct ChatConversation {
- pub id: String,
- pub session_id: Option<String>,
- pub user_id: Option<String>,
- pub merchant_id: Option<String>,
- pub profile_id: Option<String>,
- pub org_id: Option<String>,
- pub role_id: Option<String>,
- pub user_query: Secret<String>,
- pub response: Secret<serde_json::Value>,
- pub database_query: Option<String>,
- pub interaction_status: Option<String>,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub created_at: PrimitiveDateTime,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct ChatListResponse {
- pub conversations: Vec<ChatConversation>,
-}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index fd227f6ab6..ba45f84f73 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -1,5 +1,4 @@
pub mod apple_pay_certificates_migration;
-pub mod chat;
pub mod connector_onboarding;
pub mod customer;
pub mod dispute;
diff --git a/crates/api_models/src/events/chat.rs b/crates/api_models/src/events/chat.rs
deleted file mode 100644
index 38f20b0c3b..0000000000
--- a/crates/api_models/src/events/chat.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use common_utils::events::{ApiEventMetric, ApiEventsType};
-
-use crate::chat::{ChatListRequest, ChatListResponse, ChatRequest, ChatResponse};
-
-common_utils::impl_api_event_type!(
- Chat,
- (ChatRequest, ChatResponse, ChatListRequest, ChatListResponse)
-);
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index ab617c2797..ad06f59516 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -6,7 +6,6 @@ pub mod authentication;
pub mod blocklist;
pub mod card_issuer;
pub mod cards_info;
-pub mod chat;
pub mod conditional_configs;
pub mod connector_enums;
pub mod connector_onboarding;
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 9703f2621f..c688c600b6 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -220,9 +220,6 @@ pub const X_PROXY_NAME: &str = "x-proxy-name";
/// Config Override Header for UCS
pub const X_CONFIG_OVERRIDE: &str = "x-config-override";
-/// Chat Session ID
-pub const X_CHAT_SESSION_ID: &str = "x-chat-session-id";
-
/// Merchant ID Header
pub const X_MERCHANT_ID: &str = "x-merchant-id";
@@ -272,12 +269,6 @@ pub const REQUEST_TIME_OUT: u64 = 30;
/// API client request timeout for ai service (in seconds)
pub const REQUEST_TIME_OUT_FOR_AI_SERVICE: u64 = 120;
-/// Default limit for list operations (can be used across different entities)
-pub const DEFAULT_LIST_LIMIT: i64 = 100;
-
-/// Default offset for list operations (can be used across different entities)
-pub const DEFAULT_LIST_OFFSET: i64 = 0;
-
/// Default number of card issuers returned in a list request
pub const DEFAULT_CARD_ISSUER_LIST_LIMIT: u8 = 30;
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index edc0059ea3..caae17c22b 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -143,7 +143,6 @@ pub enum ApiEventsType {
profile_acquirer_id: id_type::ProfileAcquirerId,
},
ThreeDsDecisionRule,
- Chat,
Oidc,
CardIssuers,
}
diff --git a/crates/diesel_models/src/hyperswitch_ai_interaction.rs b/crates/diesel_models/src/hyperswitch_ai_interaction.rs
deleted file mode 100644
index a22bd288c1..0000000000
--- a/crates/diesel_models/src/hyperswitch_ai_interaction.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use common_utils::encryption::Encryption;
-use diesel::{self, Identifiable, Insertable, Queryable, Selectable};
-use serde::{Deserialize, Serialize};
-use time::PrimitiveDateTime;
-
-use crate::schema::hyperswitch_ai_interaction;
-
-#[derive(
- Clone,
- Debug,
- Deserialize,
- Identifiable,
- Queryable,
- Selectable,
- Serialize,
- router_derive::DebugAsDisplay,
-)]
-#[diesel(table_name = hyperswitch_ai_interaction, primary_key(id, created_at), check_for_backend(diesel::pg::Pg))]
-pub struct HyperswitchAiInteraction {
- pub id: String,
- pub session_id: Option<String>,
- pub user_id: Option<String>,
- pub merchant_id: Option<String>,
- pub profile_id: Option<String>,
- pub org_id: Option<String>,
- pub role_id: Option<String>,
- pub user_query: Option<Encryption>,
- pub response: Option<Encryption>,
- pub database_query: Option<String>,
- pub interaction_status: Option<String>,
- pub created_at: PrimitiveDateTime,
-}
-
-#[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
-#[diesel(table_name = hyperswitch_ai_interaction)]
-pub struct HyperswitchAiInteractionNew {
- pub id: String,
- pub session_id: Option<String>,
- pub user_id: Option<String>,
- pub merchant_id: Option<String>,
- pub profile_id: Option<String>,
- pub org_id: Option<String>,
- pub role_id: Option<String>,
- pub user_query: Option<Encryption>,
- pub response: Option<Encryption>,
- pub database_query: Option<String>,
- pub interaction_status: Option<String>,
- pub created_at: PrimitiveDateTime,
-}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 550798b1fc..2dd2e7fb34 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -27,7 +27,6 @@ pub mod file;
pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
-pub mod hyperswitch_ai_interaction;
pub mod invoice;
#[cfg(feature = "kv_store")]
pub mod kv;
@@ -135,10 +134,9 @@ impl<'pool> DatabaseConnectionWithContext<'pool> {
pub use self::{
address::*, api_keys::*, callback_mapper::*, capture::*, cards_info::*, configs::*,
customers::*, dispute::*, ephemeral_key::*, events::*, file::*, generic_link::*,
- hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*, merchant_account::*,
- merchant_connector_account::*, payment_attempt::*, payment_intent::*, payment_method::*,
- payout_attempt::*, payouts::*, process_tracker::*, refund::*, reverse_lookup::*,
- user_authentication_method::*,
+ locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*,
+ payment_attempt::*, payment_intent::*, payment_method::*, payout_attempt::*, payouts::*,
+ process_tracker::*, refund::*, reverse_lookup::*, user_authentication_method::*,
};
/// The types and implementations provided by this module are required for the schema generated by
/// `diesel_cli` 2.0 to work with the types defined in Rust code. This is because
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index b920f33cff..adb54efee1 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -25,7 +25,6 @@ pub mod fraud_check;
pub mod generic_link;
pub mod generics;
pub mod gsm;
-pub mod hyperswitch_ai_interaction;
pub mod invoice;
pub mod locker_mock_up;
pub mod mandate;
diff --git a/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs b/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
deleted file mode 100644
index 3421aa82a9..0000000000
--- a/crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use diesel::{associations::HasTable, ExpressionMethods};
-
-use crate::{
- hyperswitch_ai_interaction::{HyperswitchAiInteraction, HyperswitchAiInteractionNew},
- query::generics,
- schema::hyperswitch_ai_interaction::dsl,
- DatabaseConnectionWithContext, StorageResult,
-};
-
-impl HyperswitchAiInteractionNew {
- pub async fn insert(
- self,
- conn: &DatabaseConnectionWithContext<'_>,
- ) -> StorageResult<HyperswitchAiInteraction> {
- generics::generic_insert(conn, self).await
- }
-}
-
-impl HyperswitchAiInteraction {
- pub async fn filter_by_optional_merchant_id(
- conn: &DatabaseConnectionWithContext<'_>,
- merchant_id: Option<&common_utils::id_type::MerchantId>,
- limit: i64,
- offset: i64,
- ) -> StorageResult<Vec<Self>> {
- generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
- conn,
- dsl::merchant_id.eq(merchant_id.cloned()),
- Some(limit),
- Some(offset),
- Some(dsl::created_at.desc()),
- )
- .await
- }
-}
diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs
index 0493ea3ff9..984407cf02 100644
--- a/crates/diesel_models/src/query/utils.rs
+++ b/crates/diesel_models/src/query/utils.rs
@@ -50,12 +50,6 @@ mod composite_key {
self.0
}
}
- impl CompositeKey for <schema::hyperswitch_ai_interaction::table as diesel::Table>::PrimaryKey {
- type UK = schema::hyperswitch_ai_interaction::dsl::id;
- fn get_local_unique_key(&self) -> Self::UK {
- self.0
- }
- }
impl CompositeKey for <schema_v2::incremental_authorization::table as diesel::Table>::PrimaryKey {
type UK = schema_v2::incremental_authorization::dsl::authorization_id;
fn get_local_unique_key(&self) -> Self::UK {
@@ -153,7 +147,6 @@ impl_get_primary_key_for_composite!(
schema::customers::table,
schema::blocklist::table,
schema::incremental_authorization::table,
- schema::hyperswitch_ai_interaction::table,
schema_v2::incremental_authorization::table,
schema::payout_attempt::table,
schema::payouts::table
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index cd7b90a3c8..dd6e2c0083 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -784,62 +784,6 @@ diesel::table! {
}
}
-diesel::table! {
- use diesel::sql_types::*;
- use crate::enums::diesel_exports::*;
-
- hyperswitch_ai_interaction (id, created_at) {
- #[max_length = 64]
- id -> Varchar,
- #[max_length = 64]
- session_id -> Nullable<Varchar>,
- #[max_length = 64]
- user_id -> Nullable<Varchar>,
- #[max_length = 64]
- merchant_id -> Nullable<Varchar>,
- #[max_length = 64]
- profile_id -> Nullable<Varchar>,
- #[max_length = 64]
- org_id -> Nullable<Varchar>,
- #[max_length = 64]
- role_id -> Nullable<Varchar>,
- user_query -> Nullable<Bytea>,
- response -> Nullable<Bytea>,
- database_query -> Nullable<Text>,
- #[max_length = 64]
- interaction_status -> Nullable<Varchar>,
- created_at -> Timestamp,
- }
-}
-
-diesel::table! {
- use diesel::sql_types::*;
- use crate::enums::diesel_exports::*;
-
- hyperswitch_ai_interaction_default (id, created_at) {
- #[max_length = 64]
- id -> Varchar,
- #[max_length = 64]
- session_id -> Nullable<Varchar>,
- #[max_length = 64]
- user_id -> Nullable<Varchar>,
- #[max_length = 64]
- merchant_id -> Nullable<Varchar>,
- #[max_length = 64]
- profile_id -> Nullable<Varchar>,
- #[max_length = 64]
- org_id -> Nullable<Varchar>,
- #[max_length = 64]
- role_id -> Nullable<Varchar>,
- user_query -> Nullable<Bytea>,
- response -> Nullable<Bytea>,
- database_query -> Nullable<Text>,
- #[max_length = 64]
- interaction_status -> Nullable<Varchar>,
- created_at -> Timestamp,
- }
-}
-
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -2031,8 +1975,6 @@ diesel::allow_tables_to_appear_in_same_query!(
fraud_check,
gateway_status_map,
generic_link,
- hyperswitch_ai_interaction,
- hyperswitch_ai_interaction_default,
incremental_authorization,
invoice,
locker_mock_up,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 23c899a9dc..5628457ff9 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -773,62 +773,6 @@ diesel::table! {
}
}
-diesel::table! {
- use diesel::sql_types::*;
- use crate::enums::diesel_exports::*;
-
- hyperswitch_ai_interaction (id, created_at) {
- #[max_length = 64]
- id -> Varchar,
- #[max_length = 64]
- session_id -> Nullable<Varchar>,
- #[max_length = 64]
- user_id -> Nullable<Varchar>,
- #[max_length = 64]
- merchant_id -> Nullable<Varchar>,
- #[max_length = 64]
- profile_id -> Nullable<Varchar>,
- #[max_length = 64]
- org_id -> Nullable<Varchar>,
- #[max_length = 64]
- role_id -> Nullable<Varchar>,
- user_query -> Nullable<Bytea>,
- response -> Nullable<Bytea>,
- database_query -> Nullable<Text>,
- #[max_length = 64]
- interaction_status -> Nullable<Varchar>,
- created_at -> Timestamp,
- }
-}
-
-diesel::table! {
- use diesel::sql_types::*;
- use crate::enums::diesel_exports::*;
-
- hyperswitch_ai_interaction_default (id, created_at) {
- #[max_length = 64]
- id -> Varchar,
- #[max_length = 64]
- session_id -> Nullable<Varchar>,
- #[max_length = 64]
- user_id -> Nullable<Varchar>,
- #[max_length = 64]
- merchant_id -> Nullable<Varchar>,
- #[max_length = 64]
- profile_id -> Nullable<Varchar>,
- #[max_length = 64]
- org_id -> Nullable<Varchar>,
- #[max_length = 64]
- role_id -> Nullable<Varchar>,
- user_query -> Nullable<Bytea>,
- response -> Nullable<Bytea>,
- database_query -> Nullable<Text>,
- #[max_length = 64]
- interaction_status -> Nullable<Varchar>,
- created_at -> Timestamp,
- }
-}
-
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1972,8 +1916,6 @@ diesel::allow_tables_to_appear_in_same_query!(
fraud_check,
gateway_status_map,
generic_link,
- hyperswitch_ai_interaction,
- hyperswitch_ai_interaction_default,
incremental_authorization,
invoice,
locker_mock_up,
diff --git a/crates/hyperswitch_domain_models/src/chat.rs b/crates/hyperswitch_domain_models/src/chat.rs
deleted file mode 100644
index fcde505ac1..0000000000
--- a/crates/hyperswitch_domain_models/src/chat.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-use common_utils::id_type;
-use hyperswitch_masking::Secret;
-
-#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
-pub struct GetDataMessage {
- pub message: Secret<String>,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
-pub struct HyperswitchAiDataRequest {
- pub merchant_id: id_type::MerchantId,
- pub profile_id: id_type::ProfileId,
- pub org_id: id_type::OrganizationId,
- pub query: GetDataMessage,
- pub entity_type: common_enums::EntityType,
-}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 24017e3a2a..1bff3fe974 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -8,7 +8,6 @@ pub mod callback_mapper;
pub mod card_issuer;
pub mod card_testing_guard_data;
pub mod cards_info;
-pub mod chat;
pub mod configs;
pub mod connector_endpoints;
pub mod consts;
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 75d7252a19..eac6339697 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -292,29 +292,6 @@ impl SecretsHandler for settings::UserAuthMethodSettings {
}
}
-#[async_trait::async_trait]
-impl SecretsHandler for settings::ChatSettings {
- async fn convert_to_raw_secret(
- value: SecretStateContainer<Self, SecuredSecret>,
- secret_management_client: &dyn SecretManagementInterface,
- ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
- let chat_settings = value.get_inner();
-
- let encryption_key = if chat_settings.enabled {
- secret_management_client
- .get_secret(chat_settings.encryption_key.clone())
- .await?
- } else {
- chat_settings.encryption_key.clone()
- };
-
- Ok(value.transition_state(|chat_settings| Self {
- encryption_key,
- ..chat_settings
- }))
- }
-}
-
#[async_trait::async_trait]
impl SecretsHandler for settings::SageSettings {
async fn convert_to_raw_secret(
@@ -625,11 +602,6 @@ pub(crate) async fn fetch_raw_secrets(
})
.await;
- #[allow(clippy::expect_used)]
- let chat = settings::ChatSettings::convert_to_raw_secret(conf.chat, secret_management_client)
- .await
- .expect("Failed to decrypt chat configs");
-
#[allow(clippy::expect_used)]
let sage = settings::SageSettings::convert_to_raw_secret(conf.sage, secret_management_client)
.await
@@ -678,7 +650,6 @@ pub(crate) async fn fetch_raw_secrets(
Settings {
server: conf.server,
application_source: conf.application_source,
- chat,
sage,
master_database,
accounts_database,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index baa1e89cde..6331fb9dfa 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -82,7 +82,6 @@ pub struct Settings<S: SecretState> {
pub application_source: common_enums::ApplicationSource,
pub proxy: Proxy,
pub env: Env,
- pub chat: SecretStateContainer<ChatSettings, S>,
pub sage: SecretStateContainer<SageSettings, S>,
pub master_database: SecretStateContainer<Database, S>,
/// Falls back to `master_database` when not configured.
@@ -479,14 +478,6 @@ pub struct Platform {
pub allow_connected_merchants: bool,
}
-#[derive(Debug, Deserialize, Clone, Default)]
-#[serde(default)]
-pub struct ChatSettings {
- pub enabled: bool,
- pub hyperswitch_ai_host: String,
- pub encryption_key: Secret<String>,
-}
-
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct SageSettings {
@@ -1537,7 +1528,6 @@ impl Settings<SecuredSecret> {
self.secrets.get_inner().validate()?;
self.locker.validate()?;
self.connectors.validate("connectors")?;
- self.chat.get_inner().validate()?;
self.sage.get_inner().validate()?;
self.cors.validate()?;
diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs
index 3b54f7fb7b..7782859933 100644
--- a/crates/router/src/configs/validations.rs
+++ b/crates/router/src/configs/validations.rs
@@ -334,18 +334,6 @@ impl super::settings::OpenRouter {
}
}
-impl super::settings::ChatSettings {
- pub fn validate(&self) -> Result<(), ApplicationError> {
- use common_utils::fp_utils::when;
-
- when(self.enabled && self.hyperswitch_ai_host.is_empty(), || {
- Err(ApplicationError::InvalidConfigurationValueError(
- "hyperswitch ai host must be set if chat is enabled".into(),
- ))
- })
- }
-}
-
impl super::settings::SageSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 30526246c9..30abd44146 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -14,7 +14,6 @@ pub mod cache;
pub mod card_issuer;
pub mod card_testing_guard;
pub mod cards_info;
-pub mod chat;
pub mod conditional_config;
pub mod configs;
#[cfg(feature = "olap")]
diff --git a/crates/router/src/core/chat.rs b/crates/router/src/core/chat.rs
deleted file mode 100644
index 6af3fb5217..0000000000
--- a/crates/router/src/core/chat.rs
+++ /dev/null
@@ -1,211 +0,0 @@
-use api_models::chat as chat_api;
-use common_utils::{
- consts,
- crypto::{DecodeMessage, GcmAes256},
- errors::CustomResult,
- request::{Method, RequestBuilder, RequestContent},
-};
-use error_stack::ResultExt;
-use external_services::http_client;
-use hyperswitch_domain_models::chat as chat_domain;
-use hyperswitch_masking::ExposeInterface;
-use router_env::{
- instrument, logger,
- tracing::{self, Instrument},
-};
-
-use crate::{
- db::errors::chat::ChatErrors,
- routes::{app::SessionStateInfo, SessionState},
- services::{authentication as auth, authorization::roles, ApplicationResponse},
- utils,
-};
-
-#[instrument(skip_all, fields(?session_id))]
-pub async fn get_data_from_hyperswitch_ai_workflow(
- state: SessionState,
- user_from_token: auth::UserFromToken,
- req: chat_api::ChatRequest,
- session_id: Option<&str>,
-) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> {
- let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
- &state,
- &user_from_token.role_id,
- &user_from_token.org_id,
- user_from_token
- .tenant_id
- .as_ref()
- .unwrap_or(&state.tenant.tenant_id),
- )
- .await
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Failed to retrieve role information")?;
- let url = format!(
- "{}/webhook",
- state.conf.chat.get_inner().hyperswitch_ai_host
- );
- let request_id = state
- .get_request_id()
- .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
-
- let request_body = chat_domain::HyperswitchAiDataRequest {
- query: chat_domain::GetDataMessage {
- message: req.message.clone(),
- },
- org_id: user_from_token.org_id.clone(),
- merchant_id: user_from_token.merchant_id.clone(),
- profile_id: user_from_token.profile_id.clone(),
- entity_type: role_info.get_entity_type(),
- };
- logger::info!("Request for AI service: {:?}", request_body);
-
- let mut request_builder = RequestBuilder::new()
- .method(Method::Post)
- .url(&url)
- .attach_default_headers()
- .header(consts::X_REQUEST_ID, &request_id)
- .set_body(RequestContent::Json(Box::new(request_body.clone())));
-
- if let Some(session_id) = session_id {
- request_builder = request_builder.header(consts::X_CHAT_SESSION_ID, session_id);
- }
-
- let request = request_builder.build();
-
- let response = http_client::send_request(
- &state.conf.proxy,
- request,
- Some(consts::REQUEST_TIME_OUT_FOR_AI_SERVICE),
- )
- .await
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Error when sending request to AI service")?
- .json::<chat_api::ChatResponse>()
- .await
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Error when deserializing response from AI service")?;
-
- let response_to_return = response.clone();
- tokio::spawn(
- async move {
- let new_hyperswitch_ai_interaction = utils::chat::construct_hyperswitch_ai_interaction(
- &state,
- &user_from_token,
- &req,
- &response,
- &request_id,
- )
- .await;
-
- match new_hyperswitch_ai_interaction {
- Ok(interaction) => {
- let db = state.store.as_ref();
- if let Err(e) = db.insert_hyperswitch_ai_interaction(interaction).await {
- logger::error!("Failed to insert hyperswitch_ai_interaction: {:?}", e);
- }
- }
- Err(e) => {
- logger::error!("Failed to construct hyperswitch_ai_interaction: {:?}", e);
- }
- }
- }
- .in_current_span(),
- );
-
- Ok(ApplicationResponse::Json(response_to_return))
-}
-
-#[instrument(skip_all)]
-pub async fn list_chat_conversations(
- state: SessionState,
- user_from_token: auth::UserFromToken,
- req: chat_api::ChatListRequest,
-) -> CustomResult<ApplicationResponse<chat_api::ChatListResponse>, ChatErrors> {
- let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
- &state,
- &user_from_token.role_id,
- &user_from_token.org_id,
- user_from_token
- .tenant_id
- .as_ref()
- .unwrap_or(&state.tenant.tenant_id),
- )
- .await
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Failed to retrieve role information")?;
-
- if !role_info.is_internal() {
- return Err(error_stack::Report::new(ChatErrors::UnauthorizedAccess)
- .attach_printable("Only internal roles are allowed for this operation"));
- }
-
- let db = state.store.as_ref();
- let hyperswitch_ai_interactions = db
- .list_hyperswitch_ai_interactions(
- req.merchant_id,
- req.limit.unwrap_or(consts::DEFAULT_LIST_LIMIT),
- req.offset.unwrap_or(consts::DEFAULT_LIST_OFFSET),
- )
- .await
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Error when fetching hyperswitch_ai_interactions")?;
-
- let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose();
- let key = match hex::decode(&encryption_key) {
- Ok(key) => key,
- Err(e) => {
- router_env::logger::error!("Failed to decode encryption key: {}", e);
- encryption_key.as_bytes().to_vec()
- }
- };
-
- let mut conversations = Vec::new();
-
- for interaction in hyperswitch_ai_interactions {
- let user_query_encrypted = interaction
- .user_query
- .ok_or(ChatErrors::InternalServerError)
- .attach_printable("Missing user_query field in hyperswitch_ai_interaction")?;
- let response_encrypted = interaction
- .response
- .ok_or(ChatErrors::InternalServerError)
- .attach_printable("Missing response field in hyperswitch_ai_interaction")?;
-
- let user_query_decrypted_bytes = GcmAes256
- .decode_message(&key, user_query_encrypted.into_inner())
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Failed to decrypt user query")?;
-
- let response_decrypted_bytes = GcmAes256
- .decode_message(&key, response_encrypted.into_inner())
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Failed to decrypt response")?;
-
- let user_query_decrypted = String::from_utf8(user_query_decrypted_bytes)
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Failed to convert decrypted user query to string")?;
-
- let response_decrypted = serde_json::from_slice(&response_decrypted_bytes)
- .change_context(ChatErrors::InternalServerError)
- .attach_printable("Failed to deserialize decrypted response")?;
-
- conversations.push(chat_api::ChatConversation {
- id: interaction.id,
- session_id: interaction.session_id,
- user_id: interaction.user_id,
- merchant_id: interaction.merchant_id,
- profile_id: interaction.profile_id,
- org_id: interaction.org_id,
- role_id: interaction.role_id,
- user_query: user_query_decrypted.into(),
- response: response_decrypted,
- database_query: interaction.database_query,
- interaction_status: interaction.interaction_status,
- created_at: interaction.created_at,
- });
- }
-
- return Ok(ApplicationResponse::Json(chat_api::ChatListResponse {
- conversations,
- }));
-}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index dae939ea75..bd90cfc0de 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -1,4 +1,3 @@
-pub mod chat;
pub mod customers_error_response;
pub mod error_handlers;
#[cfg(feature = "olap")]
diff --git a/crates/router/src/core/errors/chat.rs b/crates/router/src/core/errors/chat.rs
deleted file mode 100644
index d23f0e9bb7..0000000000
--- a/crates/router/src/core/errors/chat.rs
+++ /dev/null
@@ -1,43 +0,0 @@
-#[derive(Debug, thiserror::Error)]
-pub enum ChatErrors {
- #[error("User InternalServerError")]
- InternalServerError,
- #[error("Missing Config error")]
- MissingConfigError,
- #[error("Chat response deserialization failed")]
- ChatResponseDeserializationFailed,
- #[error("Unauthorized access")]
- UnauthorizedAccess,
-}
-
-impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ChatErrors {
- fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
- use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
- let sub_code = "AI";
- match self {
- Self::InternalServerError => {
- AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))
- }
- Self::MissingConfigError => {
- AER::InternalServerError(ApiError::new(sub_code, 1, self.get_error_message(), None))
- }
- Self::ChatResponseDeserializationFailed => {
- AER::BadRequest(ApiError::new(sub_code, 2, self.get_error_message(), None))
- }
- Self::UnauthorizedAccess => {
- AER::Unauthorized(ApiError::new(sub_code, 3, self.get_error_message(), None))
- }
- }
- }
-}
-
-impl ChatErrors {
- pub fn get_error_message(&self) -> String {
- match self {
- Self::InternalServerError => "Something went wrong".to_string(),
- Self::MissingConfigError => "Missing webhook url".to_string(),
- Self::ChatResponseDeserializationFailed => "Failed to parse chat response".to_string(),
- Self::UnauthorizedAccess => "Not authorized to access the resource".to_string(),
- }
- }
-}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 2c193aa549..0a060d00ce 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -22,7 +22,6 @@ pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
pub mod health_check;
-pub mod hyperswitch_ai_interaction;
pub mod kafka_store;
pub mod locker_mock_up;
pub mod mandate;
@@ -145,7 +144,6 @@ pub trait StorageInterface:
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
+ user_authentication_method::UserAuthenticationMethodInterface
- + hyperswitch_ai_interaction::HyperswitchAiInteractionInterface
+ AuthenticationInterface<Error = StorageError>
+ generic_link::GenericLinkInterface
+ relay::RelayInterface
diff --git a/crates/router/src/db/hyperswitch_ai_interaction.rs b/crates/router/src/db/hyperswitch_ai_interaction.rs
deleted file mode 100644
index 4ecf741a08..0000000000
--- a/crates/router/src/db/hyperswitch_ai_interaction.rs
+++ /dev/null
@@ -1,123 +0,0 @@
-use diesel_models::hyperswitch_ai_interaction as storage;
-use error_stack::report;
-use router_env::{instrument, tracing};
-
-use super::MockDb;
-use crate::{
- connection,
- core::errors::{self, CustomResult},
- services::Store,
-};
-
-#[async_trait::async_trait]
-pub trait HyperswitchAiInteractionInterface {
- async fn insert_hyperswitch_ai_interaction(
- &self,
- hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
- ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError>;
-
- async fn list_hyperswitch_ai_interactions(
- &self,
- merchant_id: Option<common_utils::id_type::MerchantId>,
- limit: i64,
- offset: i64,
- ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError>;
-}
-
-#[async_trait::async_trait]
-impl HyperswitchAiInteractionInterface for Store {
- #[instrument(skip_all)]
- async fn insert_hyperswitch_ai_interaction(
- &self,
- hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
- ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- hyperswitch_ai_interaction
- .insert(&conn)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn list_hyperswitch_ai_interactions(
- &self,
- merchant_id: Option<common_utils::id_type::MerchantId>,
- limit: i64,
- offset: i64,
- ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> {
- let conn = connection::pg_connection_read(self).await?;
- storage::HyperswitchAiInteraction::filter_by_optional_merchant_id(
- &conn,
- merchant_id.as_ref(),
- limit,
- offset,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-}
-
-#[async_trait::async_trait]
-impl HyperswitchAiInteractionInterface for MockDb {
- async fn insert_hyperswitch_ai_interaction(
- &self,
- hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
- ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> {
- let mut hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await;
- let hyperswitch_ai_interaction = storage::HyperswitchAiInteraction {
- id: hyperswitch_ai_interaction.id,
- session_id: hyperswitch_ai_interaction.session_id,
- user_id: hyperswitch_ai_interaction.user_id,
- merchant_id: hyperswitch_ai_interaction.merchant_id,
- profile_id: hyperswitch_ai_interaction.profile_id,
- org_id: hyperswitch_ai_interaction.org_id,
- role_id: hyperswitch_ai_interaction.role_id,
- user_query: hyperswitch_ai_interaction.user_query,
- response: hyperswitch_ai_interaction.response,
- database_query: hyperswitch_ai_interaction.database_query,
- interaction_status: hyperswitch_ai_interaction.interaction_status,
- created_at: hyperswitch_ai_interaction.created_at,
- };
- hyperswitch_ai_interactions.push(hyperswitch_ai_interaction.clone());
- Ok(hyperswitch_ai_interaction)
- }
-
- async fn list_hyperswitch_ai_interactions(
- &self,
- merchant_id: Option<common_utils::id_type::MerchantId>,
- limit: i64,
- offset: i64,
- ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> {
- let hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await;
-
- let offset_usize = offset.try_into().unwrap_or_else(|_| {
- common_utils::consts::DEFAULT_LIST_OFFSET
- .try_into()
- .unwrap_or(usize::MIN)
- });
-
- let limit_usize = limit.try_into().unwrap_or_else(|_| {
- common_utils::consts::DEFAULT_LIST_LIMIT
- .try_into()
- .unwrap_or(usize::MAX)
- });
-
- let filtered_interactions: Vec<storage::HyperswitchAiInteraction> =
- hyperswitch_ai_interactions
- .iter()
- .filter(
- |interaction| match (merchant_id.as_ref(), &interaction.merchant_id) {
- (Some(merchant_id), Some(interaction_merchant_id)) => {
- interaction_merchant_id == &merchant_id.get_string_repr().to_owned()
- }
- (None, _) => true,
- _ => false,
- },
- )
- .skip(offset_usize)
- .take(limit_usize)
- .cloned()
- .collect();
- Ok(filtered_interactions)
- }
-}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index c267d2a7d3..004f2c75f8 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -54,7 +54,6 @@ use time::PrimitiveDateTime;
use super::{
dashboard_metadata::DashboardMetadataInterface,
ephemeral_key::ClientSecretInterface,
- hyperswitch_ai_interaction::HyperswitchAiInteractionInterface,
role::RoleInterface,
user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
@@ -4614,29 +4613,6 @@ impl UserAuthenticationMethodInterface for KafkaStore {
}
}
-#[async_trait::async_trait]
-impl HyperswitchAiInteractionInterface for KafkaStore {
- async fn insert_hyperswitch_ai_interaction(
- &self,
- hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
- ) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> {
- self.diesel_store
- .insert_hyperswitch_ai_interaction(hyperswitch_ai_interaction)
- .await
- }
-
- async fn list_hyperswitch_ai_interactions(
- &self,
- merchant_id: Option<id_type::MerchantId>,
- limit: i64,
- offset: i64,
- ) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> {
- self.diesel_store
- .list_hyperswitch_ai_interactions(merchant_id, limit, offset)
- .await
- }
-}
-
#[async_trait::async_trait]
impl ThemeInterface for KafkaStore {
async fn insert_theme(
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index de214a473f..e2bb29bf83 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -321,8 +321,7 @@ pub fn mk_app(
.service(routes::User::server(state.clone()))
.service(routes::ApiKeys::server(state.clone()))
.service(routes::Routing::server(state.clone()))
- .service(routes::UnifiedConnectorService::server(state.clone()))
- .service(routes::Chat::server(state.clone()));
+ .service(routes::UnifiedConnectorService::server(state.clone()));
#[cfg(all(feature = "olap", any(feature = "v1", feature = "v2")))]
{
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 1c8096d811..9c32269ff6 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -85,8 +85,6 @@ pub mod process_tracker;
#[cfg(feature = "v2")]
pub mod proxy;
-pub mod chat;
-
#[cfg(feature = "dummy_connector")]
pub use self::app::DummyConnector;
#[cfg(feature = "v2")]
@@ -95,12 +93,12 @@ pub use self::app::PaymentMethodSession;
pub use self::app::Proxy;
pub use self::app::{
ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, CardIssuers, Cards,
- Chat, Configs, ConnectorOnboarding, Customers, Disputes, Embedded, EphemeralKey,
- ExternalService, FeatureMatrix, Files, Forex, Gsm, Health, Hypersense, Mandates,
- MerchantAccount, MerchantConnectorAccount, OfferEngine, Oidc, PaymentLink, PaymentMethods,
- Payments, Poll, ProcessTracker, ProcessTrackerDeprecated, Profile, ProfileAcquirer, ProfileNew,
- Refunds, Relay, RelayWebhooks, SdkConfig, SessionState, SuperpositionProxy,
- ThreeDsDecisionRule, User, UserDeprecated, Webhooks,
+ Configs, ConnectorOnboarding, Customers, Disputes, Embedded, EphemeralKey, ExternalService,
+ FeatureMatrix, Files, Forex, Gsm, Health, Hypersense, Mandates, MerchantAccount,
+ MerchantConnectorAccount, OfferEngine, Oidc, PaymentLink, PaymentMethods, Payments, Poll,
+ ProcessTracker, ProcessTrackerDeprecated, Profile, ProfileAcquirer, ProfileNew, Refunds, Relay,
+ RelayWebhooks, SdkConfig, SessionState, SuperpositionProxy, ThreeDsDecisionRule, User,
+ UserDeprecated, Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 48b5070b59..6fc2f5aded 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -69,7 +69,7 @@ use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_ve
#[cfg(feature = "oltp")]
use super::webhooks::*;
use super::{
- admin, api_keys, cache::*, card_issuer, chat, connector_onboarding, disputes,
+ admin, api_keys, cache::*, card_issuer, connector_onboarding, disputes,
external_service_auth as external_service_auth_routes, files, gsm, health::*, offer_engine,
oidc, profiles, relay, user, user_role,
};
@@ -2751,27 +2751,7 @@ impl Gsm {
.service(web::resource("/delete").route(web::post().to(gsm::delete_gsm_rule)))
}
}
-pub struct Chat;
-#[cfg(feature = "olap")]
-impl Chat {
- pub fn server(state: AppState) -> Scope {
- let mut route = web::scope("/chat").app_data(web::Data::new(state.clone()));
- if state.conf.chat.get_inner().enabled {
- route = route.service(
- web::scope("/ai")
- .service(
- web::resource("/data")
- .route(web::post().to(chat::get_data_from_hyperswitch_ai_workflow)),
- )
- .service(
- web::resource("/list").route(web::get().to(chat::get_all_conversations)),
- ),
- );
- }
- route
- }
-}
pub struct ThreeDsDecisionRule;
#[cfg(feature = "oltp")]
diff --git a/crates/router/src/routes/chat.rs b/crates/router/src/routes/chat.rs
deleted file mode 100644
index efb8f082d6..0000000000
--- a/crates/router/src/routes/chat.rs
+++ /dev/null
@@ -1,73 +0,0 @@
-use actix_web::{web, HttpRequest, HttpResponse};
-#[cfg(feature = "olap")]
-use api_models::chat as chat_api;
-use router_env::{instrument, tracing, Flow};
-
-use super::AppState;
-use crate::{
- core::{api_locking, chat as chat_core},
- routes::metrics,
- services::{
- api,
- authentication::{self as auth},
- authorization::permissions::Permission,
- },
-};
-
-#[instrument(skip_all)]
-pub async fn get_data_from_hyperswitch_ai_workflow(
- state: web::Data<AppState>,
- http_req: HttpRequest,
- payload: web::Json<chat_api::ChatRequest>,
-) -> HttpResponse {
- let flow = Flow::GetDataFromHyperswitchAiFlow;
- let session_id = http_req
- .headers()
- .get(common_utils::consts::X_CHAT_SESSION_ID)
- .and_then(|header_value| header_value.to_str().ok());
- Box::pin(api::server_wrap(
- flow.clone(),
- state,
- &http_req,
- payload.into_inner(),
- |state, user: auth::UserFromToken, payload, _| {
- metrics::CHAT_REQUEST_COUNT.add(
- 1,
- router_env::metric_attributes!(("merchant_id", user.merchant_id.clone())),
- );
- chat_core::get_data_from_hyperswitch_ai_workflow(state, user, payload, session_id)
- },
- // At present, the AI service retrieves data scoped to the merchant level
- &auth::JWTAuth {
- permission: Permission::MerchantPaymentRead,
- allow_connected: false,
- allow_platform: false,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
-#[instrument(skip_all)]
-pub async fn get_all_conversations(
- state: web::Data<AppState>,
- http_req: HttpRequest,
- payload: web::Query<chat_api::ChatListRequest>,
-) -> HttpResponse {
- let flow = Flow::ListAllChatInteractions;
- Box::pin(api::server_wrap(
- flow.clone(),
- state,
- &http_req,
- payload.into_inner(),
- |state, user: auth::UserFromToken, payload, _| {
- chat_core::list_chat_conversations(state, user, payload)
- },
- &auth::DashboardNoPermissionAuth {
- allow_connected: false,
- allow_platform: false,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 48a46d8b9d..624501d2f2 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -36,7 +36,6 @@ pub enum ApiIdentifier {
User,
UserRole,
ConnectorOnboarding,
- AiWorkflow,
Poll,
ApplePayCertificatesMigration,
Relay,
@@ -347,8 +346,6 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListMembersForEntity
| Flow::LaunchSage => Self::User,
- Flow::GetDataFromHyperswitchAiFlow | Flow::ListAllChatInteractions => Self::AiWorkflow,
-
Flow::ListRolesV2
| Flow::ListInvitableRolesAtEntityLevel
| Flow::ListUpdatableRolesAtEntityLevel
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index e40c27ca1b..40ab427a66 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -269,9 +269,6 @@ histogram_metric_f64!(FETCH_ALTID_TIME, GLOBAL_METER);
// A counter to indicate allowed payment method types mismatch
counter_metric!(PAYMENT_METHOD_TYPES_MISCONFIGURATION_METRIC, GLOBAL_METER);
-// AI chat metric to track number of chat request
-counter_metric!(CHAT_REQUEST_COUNT, GLOBAL_METER);
-
// Merchant advice code config lookup metrics
counter_metric!(MERCHANT_ADVICE_CODE_CONFIG_MISS, GLOBAL_METER);
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 95793fc83f..5dc6cb6806 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -23,7 +23,6 @@ pub mod file;
pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
-pub mod hyperswitch_ai_interaction;
#[cfg(feature = "kv_store")]
pub mod kv;
pub mod locker_mock_up;
@@ -75,9 +74,9 @@ pub use self::{
blocklist::*, blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*,
callback_mapper::*, capture::*, card_issuer::*, cards_info::*, configs::*, customers::*,
dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*,
- file::*, fraud_check::*, generic_link::*, gsm::*, hyperswitch_ai_interaction::*,
- locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*,
- merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*,
- reverse_lookup::*, role::*, routing_algorithm::*, unified_translations::*, user::*,
- user_authentication_method::*, user_role::*,
+ file::*, fraud_check::*, generic_link::*, gsm::*, locker_mock_up::*, mandate::*,
+ merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,
+ payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,
+ routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*,
+ user_role::*,
};
diff --git a/crates/router/src/types/storage/hyperswitch_ai_interaction.rs b/crates/router/src/types/storage/hyperswitch_ai_interaction.rs
deleted file mode 100644
index 30ba3efb49..0000000000
--- a/crates/router/src/types/storage/hyperswitch_ai_interaction.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub use diesel_models::hyperswitch_ai_interaction::*;
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index bb31555b5f..e27972b6ec 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -1,4 +1,3 @@
-pub mod chat;
#[cfg(feature = "olap")]
pub mod connector_onboarding;
pub mod currency;
diff --git a/crates/router/src/utils/chat.rs b/crates/router/src/utils/chat.rs
deleted file mode 100644
index 6efa8c19f4..0000000000
--- a/crates/router/src/utils/chat.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-use api_models::chat as chat_api;
-use common_utils::{
- crypto::{EncodeMessage, GcmAes256},
- encryption::Encryption,
-};
-use diesel_models::hyperswitch_ai_interaction::HyperswitchAiInteractionNew;
-use error_stack::ResultExt;
-use hyperswitch_masking::ExposeInterface;
-
-use crate::{
- core::errors::{self, CustomResult},
- routes::SessionState,
- services::authentication as auth,
-};
-
-pub async fn construct_hyperswitch_ai_interaction(
- state: &SessionState,
- user_from_token: &auth::UserFromToken,
- req: &chat_api::ChatRequest,
- response: &chat_api::ChatResponse,
- request_id: &str,
-) -> CustomResult<HyperswitchAiInteractionNew, errors::ApiErrorResponse> {
- let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose();
- let key = match hex::decode(&encryption_key) {
- Ok(key) => key,
- Err(e) => {
- router_env::logger::error!("Failed to decode encryption key: {}", e);
- // Fallback to using the string as bytes, which was the previous behavior
- encryption_key.as_bytes().to_vec()
- }
- };
- let encrypted_user_query_bytes = GcmAes256
- .encode_message(&key, &req.message.clone().expose().into_bytes())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to encrypt user query")?;
-
- let encrypted_response_bytes = serde_json::to_vec(&response.response.clone())
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to serialize response for encryption")
- .and_then(|bytes| {
- GcmAes256
- .encode_message(&key, &bytes)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- })
- .attach_printable("Failed to encrypt response")?;
-
- Ok(HyperswitchAiInteractionNew {
- id: request_id.to_owned(),
- session_id: Some(request_id.to_string()),
- user_id: Some(user_from_token.user_id.clone()),
- merchant_id: Some(user_from_token.merchant_id.get_string_repr().to_string()),
- profile_id: Some(user_from_token.profile_id.get_string_repr().to_string()),
- org_id: Some(user_from_token.org_id.get_string_repr().to_string()),
- role_id: Some(user_from_token.role_id.clone()),
- user_query: Some(Encryption::new(encrypted_user_query_bytes.into())),
- response: Some(Encryption::new(encrypted_response_bytes.into())),
- database_query: response.query_executed.clone().map(|q| q.expose()),
- interaction_status: Some(response.status.clone()),
- created_at: common_utils::date_time::now(),
- })
-}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index a6b6c8ca15..7bbff5cff2 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -427,10 +427,6 @@ pub enum Flow {
ApplePayCertificatesMigration,
/// Gsm Rule Delete flow
GsmRuleDelete,
- /// Get data from embedded flow
- GetDataFromHyperswitchAiFlow,
- // List all chat interactions
- ListAllChatInteractions,
/// Mint a sage session for the dashboard user.
LaunchSage,
/// User Sign Up
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index b259c07b0b..68cc782b7d 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -65,8 +65,6 @@ pub struct MockDb {
pub user_authentication_methods:
Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>,
pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>,
- pub hyperswitch_ai_interactions:
- Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>,
pub card_issuers: Arc<Mutex<Vec<store::card_issuer::CardIssuer>>>,
pub blocklists: Arc<Mutex<Vec<store::blocklist::Blocklist>>>,
pub batch_blocklist_jobs: Arc<Mutex<Vec<store::batch_blocklist_job::BatchBlocklistJob>>>,
@@ -127,7 +125,6 @@ impl MockDb {
user_key_store: Default::default(),
user_authentication_methods: Default::default(),
themes: Default::default(),
- hyperswitch_ai_interactions: Default::default(),
card_issuers: Default::default(),
blocklists: Default::default(),
batch_blocklist_jobs: Default::default(),
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index c6212fa878..f403fce5e8 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -969,10 +969,6 @@ billing_connectors_which_requires_invoice_sync_call = "recurly"
[billing_connectors_dispute_record_back]
billing_connectors_which_requires_dispute_record_back_call = "chargebee"
-[chat]
-enabled = false
-hyperswitch_ai_host = "http://0.0.0.0:8000"
-encryption_key = ""
[revenue_recovery.card_config.amex]
max_retries_per_day = 20
diff --git a/migrations/2026-09-02-115631-0000_drop_hyperswitch_ai_interactions/down.sql b/migrations/2026-09-02-115631-0000_drop_hyperswitch_ai_interactions/down.sql
new file mode 100644
index 0000000000..96ef0c11b9
--- /dev/null
+++ b/migrations/2026-09-02-115631-0000_drop_hyperswitch_ai_interactions/down.sql
@@ -0,0 +1,21 @@
+-- Recreates the table as originally created in
+-- 2025-07-21-120614_add_table_for_hyperswitch_ai_interactions.
+CREATE TABLE hyperswitch_ai_interaction (
+ id VARCHAR(64) NOT NULL,
+ session_id VARCHAR(64),
+ user_id VARCHAR(64),
+ merchant_id VARCHAR(64),
+ profile_id VARCHAR(64),
+ org_id VARCHAR(64),
+ role_id VARCHAR(64),
+ user_query BYTEA,
+ response BYTEA,
+ database_query TEXT,
+ interaction_status VARCHAR(64),
+ created_at TIMESTAMP NOT NULL,
+ PRIMARY KEY (id, created_at)
+) PARTITION BY RANGE (created_at);
+
+-- Create a default partition
+CREATE TABLE hyperswitch_ai_interaction_default
+ PARTITION OF hyperswitch_ai_interaction DEFAULT;
diff --git a/migrations/2026-09-02-115631-0000_drop_hyperswitch_ai_interactions/up.sql b/migrations/2026-09-02-115631-0000_drop_hyperswitch_ai_interactions/up.sql
new file mode 100644
index 0000000000..4243607c83
--- /dev/null
+++ b/migrations/2026-09-02-115631-0000_drop_hyperswitch_ai_interactions/up.sql
@@ -0,0 +1,4 @@
+-- The hyperswitch_ai_interaction table was part of the experimental AI chat feature.
+-- The feature was never enabled in production, so the table and its partitions are dropped.
+-- CASCADE drops all child partitions, including any manually created quarterly partitions.
+DROP TABLE IF EXISTS hyperswitch_ai_interaction CASCADE;