From f63496d47f6808a246732f5ddee9b9136e23eca7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nuno=20G=C3=B3is?= Date: Mon, 14 Oct 2024 13:29:29 +0100 Subject: [PATCH] chore: Unleash AI API hook (#8441) https://linear.app/unleash/issue/2-2791/create-a-useaiapi-react-hook Implements a basic Unleash AI API React hook that fits our initial needs for interacting with this API through our frontend. Also adds a new nice-to-have script to run the frontend set to the `demo` base path, which matches our Cloud defaults. This way you can run the latest local cloud with the latest local frontend in an easy way. --- .../hooks/api/actions/useAIApi/useAIApi.ts | 36 +++++++++++++++++++ package.json | 1 + 2 files changed, 37 insertions(+) create mode 100644 frontend/src/hooks/api/actions/useAIApi/useAIApi.ts diff --git a/frontend/src/hooks/api/actions/useAIApi/useAIApi.ts b/frontend/src/hooks/api/actions/useAIApi/useAIApi.ts new file mode 100644 index 0000000000..0d0d5fc3f1 --- /dev/null +++ b/frontend/src/hooks/api/actions/useAIApi/useAIApi.ts @@ -0,0 +1,36 @@ +import useAPI from '../useApi/useApi'; + +const ENDPOINT = 'api/admin/ai'; + +export type ChatMessage = { + role: 'system' | 'user' | 'assistant'; + content: string; +}; + +export const useAIApi = () => { + const { makeRequest, createRequest, errors, loading } = useAPI({ + propagateErrors: true, + }); + + const chat = async (messages: ChatMessage[]): Promise => { + const requestId = 'chat'; + + const req = createRequest(`${ENDPOINT}/chat`, { + method: 'POST', + body: JSON.stringify({ + messages, + }), + requestId, + }); + + const response = await makeRequest(req.caller, req.id); + const { messages: newMessages } = await response.json(); + return newMessages; + }; + + return { + chat, + errors, + loading, + }; +}; diff --git a/package.json b/package.json index eae82aa62d..c86836658e 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "build": "yarn run clean && concurrently \"yarn:copy-templates\" \"yarn:build:frontend\" \"yarn:build:backend\"", "dev:backend": "TZ=UTC NODE_ENV=development tsc-watch --strictNullChecks false --onSuccess \"node dist/server-dev.js\"", "dev:frontend": "wait-on tcp:4242 && yarn --cwd ./frontend run dev", + "dev:frontend:cloud": "UNLEASH_BASE_PATH=/demo/ yarn run dev:frontend", "dev": "concurrently \"yarn:dev:backend\" \"yarn:dev:frontend\"", "prepare:backend": "concurrently \"yarn:copy-templates\" \"yarn:build:backend\"", "start:dev": "yarn run clean && TZ=UTC NODE_ENV=development tsc-watch --strictNullChecks false --onSuccess \"node dist/server-dev.js\"",