Skip to content

Commit

Permalink
doc(assistant-ai): swagger API documentation and readme update (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianmusial committed Mar 12, 2024
1 parent 6ab1042 commit 4efea45
Show file tree
Hide file tree
Showing 47 changed files with 671 additions and 494 deletions.
3 changes: 3 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
# OpenAI API Key
OPENAI_API_KEY=

# Assistant ID - leave it empty if you don't have an assistant yet
ASSISTANT_ID=
136 changes: 111 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,119 @@
<p align="center">
<a href="https://boldare.com/" target="blank">
<img src="https://szukampracy.pl/uploads/download_5baaafea22d41.png" width="160" alt="Boldare" />
</a>
</p>

# AI Assistant

Install the dependencies:
Introducing the NestJS library, designed to harness the power of OpenAI's Assistant, enabling developers to create highly efficient, scalable, and rapid AI assistants and chatbots. This library is tailored for seamless integration into the NestJS ecosystem, offering an intuitive API, WebSockets, and tools that streamline the development of AI-driven interactions. Whether you're building a customer service bot, a virtual assistant, or an interactive chatbot for engaging user experiences, our library empowers you to leverage cutting-edge AI capabilities with minimal effort.

## First steps

### Prerequiring

Before you start, you will need to have an account on the OpenAI platform and an API key. You can create an account [here](https://platform.openai.com/).

Open or create your NestJS application where you would like to integrate the AI Assistant. If you don't have a NestJS application yet, you can create one using the following command:

```bash
$ nest new project-name
```

### Step 1: Installation

Install the library using npm:

```bash
$ npm i @boldare/ai-assistant --save
```

### Step 2: Env variables

Set up your environment variables, create environment variables in the `.env` file in the root directory of the project, and populate it with the necessary secrets. You will need to add the OpenAI API Key and the Assistant ID. The Assistant ID is optional, and you can leave it empty if you don't have an assistant yet.

Create a `.env` file in the root directory of your project and populate it with the necessary secrets:

```bash
$ touch .env
```

Add the following content to the `.env` file:

```dotenv
# OpenAI API Key
OPENAI_API_KEY=
# Assistant ID - leave it empty if you don't have an assistant yet
ASSISTANT_ID=
```

### Step 3: Configuration

Configure the settings for your assistant. For more information about assistant parameters, you can refer to the [OpenAI documentation](https://platform.openai.com/docs/assistants/how-it-works/creating-assistants). A sample configuration can be found in ([chat.config.ts](apps%2Fapi%2Fsrc%2Fapp%2Fchat%2Fchat.config.ts)).

```js
// chat.config.ts file

// Default OpenAI configuration
export const assistantParams: AssistantCreateParams = {
name: 'Your assistant name',
instructions: `You are a chatbot assistant. Speak briefly and clearly.`,
tools: [
{ type: 'code_interpreter' },
{ type: 'retrieval' },
// (...) function calling - functions are configured by extended services
],
model: 'gpt-4-1106-preview',
metadata: {},
};

// Additional configuration for our assistant
export const assistantConfig: AssistantConfigParams = {
id: process.env['ASSISTANT_ID'], // OpenAI API Key
params: assistantParams, // AssistantCreateParams
filesDir: './apps/api/src/app/knowledge', // Path to the directory with files (the final path is "fileDir" + "single file")
files: [], // List of file names (or paths if you didn't fill in the above parameter)
};
```

Import the AI Assistant module with your configuration into the module file where you intend to use it:

```js
@Module({
imports: [AssistantModule.forRoot(assistantConfig)],
})
export class ChatbotModule {}
```

# Repository

The repository includes a library with an AI assistant as well as other useful parts:

| Name | Type | Description |
| ----------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `@boldare/ai-assistant` | `library` | A NestJS library based on the OpenAI Assistant for building efficient, scalable, and quick solutions for AI assistants/chatbots |
| `@boldare/ai-embedded` | `library` | The code enables embedding the chatbot on various websites through JavaScript scripts. |
| `api` | `application` | Example usage of the `@boldare/ai-assistant` library. |
| `spa` | `application` | Example client application (SPA) with a chatbot. |

## Getting started

### Step 1: Install dependencies

```bash
$ npm install
```

Project takes advantage of the `envfile` dependency to manage secrets. Assuming so, you need to copy `.env.dist` to `.env` file in the root directory of the project and fill it with the relevant secrets.
### Step 2: Env variables

Set up your environment variables, copy the `.env.dist` file to `.env` file in the root directory of the project, and populate it with the necessary secrets.

```bash
$ cp .env.dist .env
```

---
### Step 3: Run applications

```bash
# Start the app (api and spa)
Expand All @@ -25,27 +126,12 @@ $ npm run start:api
$ npm run start:spa
```

Open your browser and navigate to:

- http://localhost:4200/ - spa
- http://localhost:3000/api/ - api

Happy coding!

## Ready to deploy?

Just merge your code to the `main` branch.

## Set up CI!

Nx comes with local caching already built-in (check your `nx.json`). On CI you might want to go a step further.

- [Set up remote caching](https://nx.dev/core-features/share-your-cache)
- [Set up task distribution across multiple machines](https://nx.dev/nx-cloud/features/distribute-task-execution)
- [Learn more how to setup CI](https://nx.dev/recipes/ci)
Now you can open your browser and navigate to:

## Connect with us!
| URL | Description |
| ------------------------------ | --------------------------- |
| http://localhost:4200/ | Client application (SPA) |
| http://localhost:3000/api/ | API application |
| http://localhost:3000/api/docs | API documentation (swagger) |

- [Join the community](https://nx.dev/community)
- [Subscribe to the Nx Youtube Channel](https://www.youtube.com/@nxdevtools)
- [Follow us on Twitter](https://twitter.com/nxdevtools)
### 🎉 Happy coding 🎉
18 changes: 0 additions & 18 deletions apps/api-e2e/.eslintrc.json

This file was deleted.

19 changes: 0 additions & 19 deletions apps/api-e2e/jest.config.ts

This file was deleted.

20 changes: 0 additions & 20 deletions apps/api-e2e/project.json

This file was deleted.

10 changes: 0 additions & 10 deletions apps/api-e2e/src/ai-restaurants-api/ai-restaurants-api.spec.ts

This file was deleted.

10 changes: 0 additions & 10 deletions apps/api-e2e/src/support/global-setup.ts

This file was deleted.

7 changes: 0 additions & 7 deletions apps/api-e2e/src/support/global-teardown.ts

This file was deleted.

10 changes: 0 additions & 10 deletions apps/api-e2e/src/support/test-setup.ts

This file was deleted.

13 changes: 0 additions & 13 deletions apps/api-e2e/tsconfig.json

This file was deleted.

9 changes: 0 additions & 9 deletions apps/api-e2e/tsconfig.spec.json

This file was deleted.

5 changes: 4 additions & 1 deletion apps/api/src/app/chat/agents/agents.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Module } from '@nestjs/common';
import { GetAnimalAgent } from './get-animal.agent';
import { AgentModule } from '@boldare/ai-assistant';

@Module({
imports: [],
imports: [AgentModule],
providers: [GetAnimalAgent],
})
export class AgentsModule {}
50 changes: 50 additions & 0 deletions apps/api/src/app/chat/agents/get-animal.agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Injectable } from '@nestjs/common';
import { AssistantCreateParams } from 'openai/resources/beta';
import { AgentBase, AgentData, AgentService } from '@boldare/ai-assistant';

@Injectable()
export class GetAnimalAgent extends AgentBase {
definition: AssistantCreateParams.AssistantToolsFunction = {
type: 'function',
function: {
name: this.constructor.name,
description: `Display name od the animal`,
parameters: {
type: 'object',
properties: {
animal: {
type: 'string',
description: `Type of the animal`,
},
},
required: ['animal'],
},
},
};

constructor(protected readonly agentService: AgentService) {
super(agentService);
}

async output(data: AgentData): Promise<string> {
try {
const params = JSON.parse(data.params);
const animal = params?.animal;
const animals = [
{ id: 1, animal: 'dog', name: 'Rex' },
{ id: 2, animal: 'cat', name: 'Mittens' },
{ id: 3, animal: 'bird', name: 'Tweety' },
{ id: 4, animal: 'fish', name: 'Goldie' },
{ id: 5, animal: 'rabbit', name: 'Bugs' },
];

if (!animal) {
return 'No animal provided';
}

return animals.find(a => a.animal === animal)?.name || 'No such animal';
} catch (errors) {
return `Invalid data: ${JSON.stringify(errors)}`;
}
}
}
3 changes: 2 additions & 1 deletion apps/api/src/app/chat/chat.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Module } from '@nestjs/common';
import { AssistantModule } from '@boldare/ai-assistant';
import { assistantConfig } from './chat.config';
import { AgentsModule } from './agents/agents.module';

@Module({
imports: [AssistantModule.forRoot(assistantConfig)],
imports: [AssistantModule.forRoot(assistantConfig), AgentsModule],
})
export class ChatModule {}
12 changes: 11 additions & 1 deletion apps/api/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

import { AppModule } from './app/app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
const globalPrefix = 'api';
const config = new DocumentBuilder()
.setTitle('@boldare/ai-assistant')
.setVersion('0.1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);

app.setGlobalPrefix(globalPrefix);
app.enableCors({
origin: '*',
credentials: true,
});

const port = process.env.PORT || 3000;
await app.listen(port);

Logger.log(
`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`
`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`,
);
}

Expand Down
Loading

0 comments on commit 4efea45

Please sign in to comment.