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
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,12 @@ public static WebAISendChatMessageInfo submitPrompt(
+ "(schema, table and column names) to the AI assistant. Send the message again and allow it when asked.")
.formatted(conversation.getDataSource() == null ? "" : conversation.getDataSource().getName()));
}
if (StackblazeAI.isEnabled()
&& StackblazeAI.billingConnection(webSession, conversation.getDataSource()) == null) {
// Refuse here, not in the background job: an error event that beats this
// mutation's reply leaves the chat spinner on (the reply sets it back on).
throw new DBWebException(StackblazeAI.NO_CONNECTION_MESSAGE);
}
StackblazeAI.ensureDefaultProfile();
AIChatMessage promptMessage;
AIChatMessage result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.cloudbeaver.DBWebException;
import io.cloudbeaver.WebSessionGlobalProjectImpl;
import io.cloudbeaver.model.WebConnectionInfo;
import io.cloudbeaver.model.session.WebSession;
import io.cloudbeaver.service.ai.WebAIFeatureProvider;
import io.cloudbeaver.utils.ServletAppUtils;
Expand All @@ -26,6 +28,8 @@
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;

/**
* Stackblaze mode: on when {@code STACKBLAZE_LLM_URL} and {@code STACKBLAZE_LLM_SECRET}
Expand All @@ -47,6 +51,11 @@
public static final String PROFILE_ID = "stackblaze";
public static final String PROFILE_NAME = "Stackblaze";

/** Shown when a turn has no connection to charge. */
public static final String NO_CONNECTION_MESSAGE =
"Pick a database in the connection list above. AI usage is charged to the workspace that owns it.";
private static final String DUCKDB_NAME_SUFFIX = " \u00b7 SQL (DuckDB)";

Check warning on line 57 in server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/stackblaze/StackblazeAI.java

View workflow job for this annotation

GitHub Actions / Server / Lint

[checkstyle] reported by reviewdog 🐶 Unicode escape(s) usage should be avoided. Raw Output: /github/workspace/./server/bundles/io.cloudbeaver.service.ai/src/io/cloudbeaver/service/ai/stackblaze/StackblazeAI.java:57:54: warning: Unicode escape(s) usage should be avoided. (com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck)

private static final int DEFAULT_CONTEXT_WINDOW = 128_000;
private static final long CATALOG_RETRY_MS = 60_000L;

Expand Down Expand Up @@ -120,8 +129,9 @@
@Nullable DBPDataSourceContainer dataSource,
@NotNull String sessionId
) throws DBWebException {
dataSource = billingConnection(webSession, dataSource);
if (dataSource == null) {
throw new DBWebException("Open the AI chat from a database connection.");
throw new DBWebException(NO_CONNECTION_MESSAGE);
}
String secret = secret();
if (secret == null) {
Expand All @@ -147,6 +157,47 @@
return profile;
}

/**
* The connection whose workspace pays for a turn: the chat's own connection,
* or, for a chat with "No connection", any shared connection the user can see
* when they all belong to one Stackblaze project ({@code <project>/<env>/<db>}).
* Null when there is nothing to charge or the choice would be a guess.
*/
@Nullable
public static DBPDataSourceContainer billingConnection(
@NotNull WebSession webSession,
@Nullable DBPDataSourceContainer chosen
) {
if (chosen != null) {
return chosen;
}
WebSessionGlobalProjectImpl shared = webSession.getGlobalProject();
if (shared == null) {
return null;
}
DBPDataSourceContainer first = null;
Set<String> projects = new HashSet<>();
for (WebConnectionInfo info : shared.getConnections()) {
DBPDataSourceContainer container = info.getDataSourceContainer();
if (!shared.isDataSourceAccessible(container)) {
continue;
}
String name = container.getName() == null ? "" : container.getName();
if (name.endsWith(DUCKDB_NAME_SUFFIX)) {
name = name.substring(0, name.length() - DUCKDB_NAME_SUFFIX.length());
}
String[] parts = name.split("/", -1);
if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) {
continue;
}
projects.add(parts[0]);
if (first == null) {
first = container;
}
}
return projects.size() == 1 ? first : null;
}

@Nullable
static String model(@Nullable String token) {
String fromEnv = env("STACKBLAZE_LLM_MODEL");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* you may not use this file except in compliance with the License.
*/

import type { ReactElement } from 'react';
import { useEffect, type ReactElement } from 'react';
import { observer } from 'mobx-react-lite';

import { isNotNullDefined } from '@dbeaver/js-helpers';
Expand Down Expand Up @@ -63,14 +63,38 @@ export const AIChatContextManager = observer<Props>(function AIChatContextManage

const value = aiChatContextService.currentContext?.connectionKey.connectionId ?? NO_CONTEXT_ID;

// Stackblaze: with no SQL editor open the chat starts on "No connection" and its
// tools have no database to read. Use the user's only connected connection (or
// their only connection), unless they picked "No connection" themselves.
const connected = connections.filter(c => c.connected);
let onlyConnection = connected.length === 1 ? connected[0] : undefined;

if (connected.length === 0 && connections.length === 1) {
onlyConnection = connections[0];
}

const canAutoPick = !aiChatContextService.currentContext && !aiChatContextService.isNoContextChosen;
const autoPickId = canAutoPick ? onlyConnection?.id : undefined;

useEffect(() => {
if (!autoPickId) {
return;
}
const connection = connectionInfoResource.data.find(c => c?.id === autoPickId);

if (connection) {
aiChatContextService.setContext({ connectionKey: createConnectionParam(connection) });
}
}, [autoPickId, aiChatContextService, connectionInfoResource]);

function changeContext(contextId: string): void {
if (contextId === NO_CONTEXT_ID) {
aiChatContextService.setContext(null);
aiChatContextService.chooseContext(null);
} else {
const connection = connectionInfoResource.data.find(c => c?.id === contextId);

if (connection) {
aiChatContextService.setContext({ connectionKey: createConnectionParam(connection) });
aiChatContextService.chooseContext({ connectionKey: createConnectionParam(connection) });
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export class AIChatContextService extends Bootstrap {
}

private context: IAIChatContextInfo | null = null;
/** Stackblaze: the user picked "No connection" themselves; don't pick one for them. */
private noContextChosen = false;
private reactionDisposer: IReactionDisposer | null;

constructor(
Expand All @@ -50,6 +52,7 @@ export class AIChatContextService extends Bootstrap {
this.reactionDisposer = null;

userInfoResource.onUserChange.addHandler(() => {
this.noContextChosen = false;
this.setContext(null);
});

Expand All @@ -63,11 +66,22 @@ export class AIChatContextService extends Bootstrap {
}
});

makeObservable<this, 'context'>(this, {
makeObservable<this, 'context' | 'noContextChosen'>(this, {
context: observable,
noContextChosen: observable,
});
}

get isNoContextChosen(): boolean {
return this.noContextChosen;
}

/** A choice made in the chat's connection list ("No connection" is null). */
chooseContext(context: IAIChatContextInfo | null): void {
this.noContextChosen = context === null;
this.setContext(context);
}

setContext(context: IAIChatContextInfo | null): void {
this.context = context;
this.onContextChange.execute(this.context);
Expand Down
Loading