Skip to content
Draft
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
1 change: 1 addition & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
['name' => 'chattyLLM#deleteSession', 'url' => '/chat/delete_session', 'verb' => 'DELETE'],
['name' => 'chattyLLM#deleteSessions', 'url' => '/chat/delete_sessions', 'verb' => 'DELETE'],
['name' => 'chattyLLM#getSessions', 'url' => '/chat/sessions', 'verb' => 'GET'],
['name' => 'chattyLLM#searchMessages', 'url' => '/chat/search', 'verb' => 'GET'],
['name' => 'chattyLLM#newMessage', 'url' => '/chat/new_message', 'verb' => 'PUT'],
['name' => 'chattyLLM#deleteMessage', 'url' => '/chat/delete_message', 'verb' => 'DELETE'],
['name' => 'chattyLLM#getMessages', 'url' => '/chat/messages', 'verb' => 'GET'],
Expand Down
31 changes: 31 additions & 0 deletions lib/Controller/ChattyLLMController.php
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,37 @@ public function getSessions(?bool $isAssignment = false): JSONResponse {
}
}

/**
* Search chat messages
*
* Get the messages of the current user's chat sessions matching the search query, most recent first
*
* @param string $query Text to search for in the message contents (case-insensitive)
* @param bool|null $isAssignment Whether to search only the sessions for assignments (true) or not (false) defaults to false
* @return JSONResponse<Http::STATUS_OK, list<AssistantChatMessage>, array{}>|JSONResponse<Http::STATUS_INTERNAL_SERVER_ERROR|Http::STATUS_UNAUTHORIZED|Http::STATUS_BAD_REQUEST, array{error: string}, array{}>
*
* 200: The matching messages have been obtained successfully
* 400: The search query is empty
* 401: Not logged in
*/
#[NoAdminRequired]
#[OpenAPI(scope: OpenAPI::SCOPE_DEFAULT, tags: ['chat_api'])]
public function searchMessages(string $query, ?bool $isAssignment = false): JSONResponse {
try {
$messages = $this->chatService->searchMessages($this->userId, $query, $isAssignment);
return new JSONResponse(array_map(static function (Message $message) {
return $message->jsonSerialize();
}, $messages));
} catch (BadRequestException $e) {
return new JSONResponse(['error' => $e->getMessage()], Http::STATUS_BAD_REQUEST);
} catch (InternalException $e) {
$this->logger->warning('Failed to search chat messages', ['exception' => $e]);
return new JSONResponse(['error' => $this->l10n->t('Failed to search chat messages')], Http::STATUS_INTERNAL_SERVER_ERROR);
} catch (\OCA\Assistant\Service\UnauthorizedException $e) {
return new JSONResponse(['error' => $this->l10n->t('User not logged in')], Http::STATUS_UNAUTHORIZED);
}
}

/**
* Add a message
*
Expand Down
30 changes: 30 additions & 0 deletions lib/Db/ChattyLLM/MessageMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,36 @@ public function getMessages(int $sessionId, int $cursor, int $limit, string $fil
return array_reverse($messages);
}

/**
* Find the messages of a user's sessions whose content contains the query (case-insensitive), most recent first
*
* @param string $userId
* @param string $query
* @param bool $isAssignment Whether to search in the sessions for assignments (true) or not (false)
* @param int $limit
* @return list<Message>
* @throws \OCP\DB\Exception
*/
public function searchUserMessages(string $userId, string $query, bool $isAssignment, int $limit): array {
$qb = $this->db->getQueryBuilder();
$qb->select(array_map(static fn (string $column) => 'm.' . $column, Message::$columns))
->from($this->getTableName(), 'm')
->innerJoin('m', 'assistant_chat_sns', 's', $qb->expr()->eq('m.session_id', 's.id'))
->where($qb->expr()->eq('s.user_id', $qb->createPositionalParameter($userId, IQueryBuilder::PARAM_STR)))
->andWhere($qb->expr()->iLike('m.content', $qb->createPositionalParameter('%' . $this->db->escapeLikeParameter($query) . '%', IQueryBuilder::PARAM_STR)))
->orderBy('m.timestamp', 'DESC')
->addOrderBy('m.id', 'DESC')
->setMaxResults($limit);

if ($isAssignment) {
$qb->andWhere($qb->expr()->isNotNull('s.assignment_id'));
} else {
$qb->andWhere($qb->expr()->isNull('s.assignment_id'));
}

return $this->findEntities($qb);
}

/**
* @param int $sessionId
* @param int $maxTimestamp
Expand Down
24 changes: 24 additions & 0 deletions lib/Service/ChatService.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

class ChatService {
public const EMPTY_CONVERSATION_TOKEN = '{}';
public const SEARCH_MESSAGE_LIMIT = 200;

public function __construct(
private readonly IUserManager $userManager,
Expand Down Expand Up @@ -226,6 +227,29 @@ public function getSessionsForUser(?string $userId, bool $isAssignment): array {
}
}

/**
* Find the user's messages matching the query, the SEARCH_MESSAGE_LIMIT most recent ones first
*
* @return list<Message>
* @throws BadRequestException
* @throws InternalException
* @throws UnauthorizedException
*/
public function searchMessages(?string $userId, string $query, bool $isAssignment): array {
if ($userId === null) {
throw new UnauthorizedException($this->l10n->t('Unauthorized'));
}
$query = trim($query);
if ($query === '') {
throw new BadRequestException($this->l10n->t('The search query is empty'));
}
try {
return $this->messageMapper->searchUserMessages($userId, $query, $isAssignment, self::SEARCH_MESSAGE_LIMIT);
} catch (Exception $e) {
throw new InternalException(previous: $e);
}
}

/**
* @throws BadRequestException
* @throws InternalException
Expand Down
143 changes: 143 additions & 0 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -4878,6 +4878,149 @@
}
}
},
"/ocs/v2.php/apps/assistant/chat/search": {
"get": {
"operationId": "chattyllm-search-messages",
"summary": "Search chat messages",
"description": "Get the messages of the current user's chat sessions matching the search query, most recent first",
"tags": [
"chat_api"
],
"security": [
{
"bearer_auth": []
},
{
"basic_auth": []
}
],
"parameters": [
{
"name": "query",
"in": "query",
"description": "Text to search for in the message contents (case-insensitive)",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "isAssignment",
"in": "query",
"description": "Whether to search only the sessions for assignments (true) or not (false) defaults to false",
"schema": {
"type": "boolean",
"nullable": true,
"default": false
}
},
{
"name": "OCS-APIRequest",
"in": "header",
"description": "Required to be true for the API request to pass",
"required": true,
"schema": {
"type": "boolean",
"default": true
}
}
],
"responses": {
"200": {
"description": "The matching messages have been obtained successfully",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/ChatMessage"
}
}
}
}
},
"500": {
"description": "",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "string"
}
}
}
}
}
},
"401": {
"description": "Not logged in",
"content": {
"application/json": {
"schema": {
"anyOf": [
{
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "string"
}
}
},
{
"type": "object",
"required": [
"ocs"
],
"properties": {
"ocs": {
"type": "object",
"required": [
"meta",
"data"
],
"properties": {
"meta": {
"$ref": "#/components/schemas/OCSMeta"
},
"data": {}
}
}
}
}
]
}
}
}
},
"400": {
"description": "The search query is empty",
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "string"
}
}
}
}
}
}
}
}
},
"/ocs/v2.php/apps/assistant/chat/new_message": {
"put": {
"operationId": "chattyllm-new-message",
Expand Down
Loading
Loading