Skip to content

Commit ab1a30c

Browse files
doc: add personality to api_doc.md
1 parent 6a26d8d commit ab1a30c

19 files changed

+2471
-33
lines changed

backend/core/doc/api_doc.md

+276
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
# Introduction
2+
3+
## Overview
4+
5+
This part outlines the key points and usage instructions for interacting with the API backend. Please follow the guidelines below to use the backend services effectively.
6+
7+
## FastAPI
8+
9+
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. FastAPI is a class-based API framework that is built on top of Starlette and Pydantic. FastAPI is a great choice for building APIs because it is easy to use, fast, and has a lot of great features.
10+
11+
We decided to choose FastAPI because it is a modern, fast, and easy-to-use API framework. FastAPI is also very well documented and has a lot of great features that make it easy to build APIs. FastAPI is also very well supported by the community and has a lot of great features that make it easy to build APIs.
12+
13+
## Authentication
14+
15+
The API uses API keys for authentication. You can generate an API key by signing in to the frontend application and navigating to the `/config` page. The API key will be required to authenticate your requests to the backend.
16+
17+
When making requests to the backend API, include the following header:
18+
19+
```http
20+
Authorization: Bearer {api_key}
21+
```
22+
23+
Replace `{api_key}` with the generated API key obtained from the frontend
24+
25+
You can find more information in the [Authentication](/docs/backend/api/getting_started) section of the documentation.
26+
27+
28+
29+
# How to use the API
30+
31+
## Overview
32+
33+
This part outlines the key points and usage instructions for interacting with the API backend. Please follow the guidelines below to use the backend services effectively.
34+
35+
## Usage Instructions
36+
37+
1. Standalone Backend
38+
39+
- The backend can now be used independently without the frontend application.
40+
- Users can interact with the API endpoints directly using API testing tools like Postman.
41+
42+
2. Generating API Key
43+
44+
- To access the backend services, you need to sign in to the frontend application.
45+
- Once signed in, navigate to the `/user` page to generate a new API key.
46+
- The API key will be required to authenticate your requests to the backend.
47+
48+
3. Authenticating Requests
49+
50+
- When making requests to the backend API, include the following header:
51+
- `Authorization: Bearer {api_key}`
52+
- Replace `{api_key}` with the generated API key obtained from the frontend.
53+
54+
# Error Handling
55+
## Overview
56+
57+
This part provides information about common error codes, their descriptions, and examples of scenarios where these errors may occur.
58+
59+
| Error Code | Description |
60+
| ---------- | --------------------------------------------------------------------------- |
61+
| 401 | Unauthorized: The request lacks valid authentication credentials. |
62+
| 403 | Forbidden: The requested operation is not allowed. |
63+
| 422 | Unprocessable Entity: The request is well-formed but contains invalid data. |
64+
| 500 | Internal Server Error: An unexpected error occurred on the server. |
65+
66+
## Error Code: 401
67+
68+
**Description**: The request lacks valid authentication credentials or the provided token/api key is invalid.
69+
70+
Example Scenarios:
71+
72+
- Missing or invalid authentication token/api key.
73+
- Expired authentication token.
74+
75+
## Error Code: 403
76+
77+
**Description**: The requested operation is forbidden due to insufficient privileges or credentials missing.
78+
79+
Example Scenarios:
80+
81+
- Attempting to access a resource without proper authorization.
82+
- Insufficient permissions to perform a specific action.
83+
84+
## Error Code: 422
85+
86+
**Description**: The request is well-formed, but contains invalid data or parameters.
87+
88+
Example Scenarios:
89+
90+
- Invalid input data format.
91+
- Required fields are missing or have incorrect values.
92+
93+
## Error Code: 500
94+
95+
**Description**: An unexpected error occurred on the server.
96+
97+
Example Scenarios:
98+
99+
- Internal server error due to a server-side issue.
100+
- Unhandled exceptions or errors during request processing.
101+
102+
103+
# Chat system
104+
105+
## Brain
106+
1. **Create new brain**
107+
- HTTP method: POST
108+
- Endpoint: `/brains/`
109+
- Description: This endpoint create new brain
110+
```json
111+
headers = {
112+
"Authorization": "Bearer {token}",
113+
"Content-Type": "application/json",
114+
}
115+
requestbody = {
116+
"description": string,
117+
"name": string,
118+
"model": string,
119+
"max_tokens": int,
120+
"openai_api_key": string,
121+
"temperature": string,
122+
"prompt_id": UUID,
123+
"extraversion": int,
124+
"neuroticism": int,
125+
"conscientiousness": int
126+
}
127+
```
128+
2. **Upload documents to an expert to train him**
129+
130+
- HTTP method: POST
131+
- Endpoint: `/upload`
132+
- Description: This endpoint upload a document for training the brain.
133+
```json
134+
headers = {
135+
"Authorization": "Bearer {token}",
136+
"Content-Type": "application/json"
137+
}
138+
params = {
139+
"brain_id": UUID
140+
}
141+
files = {
142+
"uploadFile": binary
143+
}
144+
```
145+
3. **Add URL for brain to train that**
146+
147+
- HTTP method: POST
148+
- Endpoint: `/crawl`
149+
- Description: This endpoint upload a document for training the brain.
150+
```json
151+
headers = {
152+
"Authorization": "Bearer {token}",
153+
}
154+
params = {
155+
"brain_id": UUID
156+
}
157+
requestbody = {
158+
"depth": integer,
159+
"js": boolean,
160+
"max_pages": integer,
161+
"max_time": integer,
162+
"url": string
163+
}
164+
```
165+
## Chat
166+
1. **Chat with brain**
167+
- HTTP method: POST
168+
- Endpoint: `/chat/{chat_id}/question/stream`
169+
- Description: Ask a question to brain in specific chat room.
170+
```json
171+
headers = {
172+
"Authorization": "Bearer {token}",
173+
"Content-Type": "application/json"
174+
}
175+
chat_id = UUID
176+
params = {
177+
"brain_id": UUID
178+
}
179+
requestbody = {
180+
"question": string
181+
}
182+
```
183+
184+
2. **Retrieve history of questions for a given expert**
185+
- HTTP method: GET
186+
- Endpoint: `/chat/{brain_id}/brain_history`
187+
- Description: Ask a question to brain in specific chat room.
188+
```json
189+
headers = {
190+
"Authorization": "Bearer {token}",
191+
"Content-Type": "application/json"
192+
}
193+
brain_id: UUID
194+
```
195+
196+
3. **Retrieve all chats for the current user:**
197+
198+
- HTTP method: GET
199+
- Endpoint: `/chat`
200+
- Description: This endpoint retrieves all the chats associated with the current authenticated user. It returns a list of chat objects containing the chat ID and chat name for each chat.
201+
202+
4. **Delete a specific chat by chat ID:**
203+
204+
- HTTP method: DELETE
205+
- Endpoint: `/chat/{chat_id}`
206+
- Description: This endpoint allows deleting a specific chat identified by its chat ID.
207+
208+
5. **Update chat attributes:**
209+
210+
- HTTP method: PUT
211+
- Endpoint: `/chat/{chat_id}/metadata`
212+
- Description: This endpoint is used to update the attributes of a chat, such as the chat name.
213+
214+
6. **Create a new chat with initial chat messages:**
215+
216+
- HTTP method: POST
217+
- Endpoint: `/chat`
218+
- Description: This endpoint creates a new chat with initial chat messages. It expects the chat name in the request payload.
219+
220+
7. **Add a new question to a chat:**
221+
222+
- HTTP method: POST
223+
- Endpoint: `/chat/{chat_id}/question`
224+
- Description: This endpoint allows adding a new question to a chat. It generates an answer for the question using different models based on the provided model type.
225+
226+
227+
8. **Get the chat history:**
228+
- HTTP method: GET
229+
- Endpoint: `/chat/{chat_id}/history`
230+
- Description: This endpoint retrieves the chat history for a specific chat identified by its chat ID.
231+
232+
## Personality
233+
1. **Get personality test questions**
234+
- HTTP method: GET
235+
- Endpoint: `/personality/question`
236+
- Description: This endpoint generate questions for personality test.
237+
```json
238+
headers = {
239+
"Authorization": "Bearer {token}",
240+
"Content-Type": "application/json"
241+
}
242+
params = {
243+
"question_number": int
244+
}
245+
```
246+
247+
2. **Get personality from test result**
248+
- HTTP method: POST
249+
- Endpoint: `/personality`
250+
- Description: This endpoint return personality from personality test result.
251+
```json
252+
headers = {
253+
"Authorization": "Bearer {token}",
254+
"Content-Type": "application/json"
255+
}
256+
requestbody = {
257+
"result": [string]
258+
}
259+
260+
Following is example of result:
261+
[
262+
{
263+
"trait": "Extraversion",
264+
"positive": true,
265+
"question": "Do you frequently enjoy social activities?",
266+
"answer": 4
267+
},
268+
{
269+
"trait": "Extraversion",
270+
"positive": true,
271+
"question": "Do you prefer to work in teams?",
272+
"answer": 3
273+
},
274+
...
275+
]
276+
```

backend/core/llm/base.py

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from langchain.llms.base import LLM
77
from logger import get_logger
88
from models.settings import BrainSettings # Importing settings related to the 'brain'
9+
from models.brains import Personality
910
from pydantic import BaseModel # For data validation and settings management
1011

1112
logger = get_logger(__name__)
@@ -27,6 +28,7 @@ class BaseBrainPicking(BaseModel):
2728
brain_id: str = None # pyright: ignore reportPrivateUsage=none
2829
max_tokens: int = 256
2930
user_openai_api_key: str = None # pyright: ignore reportPrivateUsage=none
31+
personality: Personality = None
3032
streaming: bool = False
3133

3234
openai_api_key: str = None # pyright: ignore reportPrivateUsage=none

backend/core/llm/openai.py

+3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from langchain.embeddings.openai import OpenAIEmbeddings
33
from langchain.llms.base import BaseLLM
44
from llm.qa_base import QABaseBrainPicking
5+
from models.brains import Personality
56
from logger import get_logger
67

78
logger = get_logger(__name__)
@@ -24,6 +25,7 @@ def __init__(
2425
chat_id: str,
2526
max_tokens: int,
2627
user_openai_api_key: str,
28+
personality: Personality = None,
2729
streaming: bool = False,
2830
) -> "OpenAIBrainPicking": # pyright: ignore reportPrivateUsage=none
2931
"""
@@ -37,6 +39,7 @@ def __init__(
3739
max_tokens=max_tokens,
3840
temperature=temperature,
3941
user_openai_api_key=user_openai_api_key,
42+
personality=personality,
4043
streaming=streaming,
4144
)
4245

+28-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,37 @@
11
from langchain.prompts.prompt import PromptTemplate
2+
from models.brains import Personality
3+
from llm.prompts.personality_description_list import personality_description_list
24

3-
prompt_template = """Your name is Quivr. You are a second brain. A person will ask you a question and you will provide a helpful answer. Write the answer in the same language as the question. If you don't know the answer, just say that you don't know. Don't try to make up an answer. Use the following context to answer the question:
5+
default_prompt_template = """Your name is Quivr. You are a second brain. A person will ask you a question and you will provide a helpful answer. Write the answer in the same language as the question. If you don't know the answer, just say that you don't know. Don't try to make up an answer. Use the following context to answer the question:
46
57
68
{context}
79
810
Question: {question}
911
Helpful Answer:"""
10-
QA_PROMPT = PromptTemplate(
11-
template=prompt_template, input_variables=["context", "question"]
12+
DEFAULT_QA_PROMPT = PromptTemplate(
13+
template=default_prompt_template, input_variables=["context", "question"]
1214
)
15+
16+
17+
prompt_templete = """You are an AI agent, You are: {description}. Your answer should match your personality. Use the following pieces of context to answer the question at the end. If context is empyt, ignore context.
18+
19+
20+
{context}
21+
22+
Question: {question}
23+
Your Answer:
24+
"""
25+
26+
def qa_prompt(personality:Personality = None):
27+
28+
if personality:
29+
description = personality_description_list[personality.extraversion * 16 + personality.neuroticism * 4 + personality.conscientiousness]
30+
31+
personal_prompt_template = prompt_templete.replace("{description}", description)
32+
prompt = PromptTemplate(
33+
template=personal_prompt_template, input_variables=["context", "question"]
34+
)
35+
return prompt
36+
else:
37+
return DEFAULT_QA_PROMPT

0 commit comments

Comments
 (0)