-
-
Notifications
You must be signed in to change notification settings - Fork 150
add api route for llm query #488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
4ca029a
add api route for llm query
aldrinjenson fdfd1d2
Refactor endpoiint and add env option
trueleo 63e1cfe
rust format check fix
aldrinjenson b26b019
make the llm query in backend itself
aldrinjenson 756f8cb
Refactor
trueleo 52627a6
Fix
trueleo 08e8e01
Add authorization with base64 string
aldrinjenson 9ea0e57
formatting
aldrinjenson a49221f
add route to check if llm api key is set
aldrinjenson 89e82b3
formatting
aldrinjenson f8bdc84
Clippy fix
trueleo bc8fd49
Fix type
trueleo f81d10d
Refactor
trueleo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,176 @@ | ||
/* | ||
* Parseable Server (C) 2022 - 2023 Parseable, Inc. | ||
* | ||
* This program is free software: you can redistribute it and/or modify | ||
* it under the terms of the GNU Affero General Public License as | ||
* published by the Free Software Foundation, either version 3 of the | ||
* License, or (at your option) any later version. | ||
* | ||
* This program is distributed in the hope that it will be useful, | ||
* but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
* GNU Affero General Public License for more details. | ||
* | ||
* You should have received a copy of the GNU Affero General Public License | ||
* along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
* | ||
*/ | ||
|
||
use actix_web::{http::header::ContentType, web, HttpResponse, Result}; | ||
use http::{header, StatusCode}; | ||
use itertools::Itertools; | ||
use reqwest; | ||
use serde_json::{json, Value}; | ||
|
||
use crate::{ | ||
metadata::{error::stream_info::MetadataError, STREAM_INFO}, | ||
option::CONFIG, | ||
}; | ||
|
||
const OPEN_AI_URL: &str = "https://api.openai.com/v1/chat/completions"; | ||
|
||
// Deserialize types for OpenAI Response | ||
#[derive(serde::Deserialize, Debug)] | ||
struct ResponseData { | ||
choices: Vec<Choice>, | ||
} | ||
|
||
#[derive(serde::Deserialize, Debug)] | ||
struct Choice { | ||
message: Message, | ||
} | ||
|
||
#[derive(serde::Deserialize, Debug)] | ||
struct Message { | ||
content: String, | ||
} | ||
|
||
// Request body | ||
#[derive(serde::Deserialize, Debug)] | ||
pub struct AiPrompt { | ||
prompt: String, | ||
stream: String, | ||
} | ||
|
||
// Temperory type | ||
#[derive(Debug, serde::Serialize)] | ||
struct Field { | ||
name: String, | ||
data_type: String, | ||
} | ||
|
||
impl From<&arrow_schema::Field> for Field { | ||
fn from(field: &arrow_schema::Field) -> Self { | ||
Self { | ||
name: field.name().clone(), | ||
data_type: field.data_type().to_string(), | ||
} | ||
} | ||
} | ||
|
||
fn build_prompt(stream: &str, prompt: &str, schema_json: &str) -> String { | ||
format!( | ||
r#"I have a table called {}. | ||
It has the columns:\n{} | ||
Based on this, generate valid SQL for the query: "{}" | ||
Generate only SQL as output. Also add comments in SQL syntax to explain your actions. | ||
Don't output anything else. | ||
If it is not possible to generate valid SQL, output an SQL comment saying so."#, | ||
stream, schema_json, prompt | ||
) | ||
} | ||
|
||
fn build_request_body(ai_prompt: String) -> impl serde::Serialize { | ||
json!({ | ||
"model": "gpt-3.5-turbo", | ||
"messages": [{ "role": "user", "content": ai_prompt}], | ||
"temperature": 0.6, | ||
}) | ||
} | ||
|
||
pub async fn make_llm_request(body: web::Json<AiPrompt>) -> Result<HttpResponse, LLMError> { | ||
let api_key = match &CONFIG.parseable.open_ai_key { | ||
Some(api_key) if api_key.len() > 3 => api_key, | ||
_ => return Err(LLMError::InvalidAPIKey), | ||
}; | ||
|
||
let stream_name = &body.stream; | ||
let schema = STREAM_INFO.schema(stream_name)?; | ||
let filtered_schema = schema | ||
.all_fields() | ||
.into_iter() | ||
.map(Field::from) | ||
.collect_vec(); | ||
|
||
let schema_json = | ||
serde_json::to_string(&filtered_schema).expect("always converted to valid json"); | ||
|
||
let prompt = build_prompt(stream_name, &body.prompt, &schema_json); | ||
let body = build_request_body(prompt); | ||
|
||
let client = reqwest::Client::new(); | ||
let response = client | ||
.post(OPEN_AI_URL) | ||
.header(header::CONTENT_TYPE, "application/json") | ||
.bearer_auth(api_key) | ||
.json(&body) | ||
.send() | ||
.await?; | ||
|
||
if response.status().is_success() { | ||
let body: ResponseData = response | ||
.json() | ||
.await | ||
.expect("OpenAI response is always the same"); | ||
Ok(HttpResponse::Ok() | ||
.content_type("application/json") | ||
.json(&body.choices[0].message.content)) | ||
} else { | ||
let body: Value = response.json().await?; | ||
let message = body | ||
.as_object() | ||
.and_then(|body| body.get("error")) | ||
.and_then(|error| error.as_object()) | ||
.and_then(|error| error.get("message")) | ||
.map(|message| message.to_string()) | ||
.unwrap_or_else(|| "Error from OpenAI".to_string()); | ||
|
||
Err(LLMError::APIError(message)) | ||
} | ||
} | ||
|
||
pub async fn is_llm_active(_body: web::Json<AiPrompt>) -> HttpResponse { | ||
let is_active = matches!(&CONFIG.parseable.open_ai_key, Some(api_key) if api_key.len() > 3); | ||
HttpResponse::Ok() | ||
.content_type("application/json") | ||
.json(json!({"is_active": is_active})) | ||
} | ||
|
||
#[derive(Debug, thiserror::Error)] | ||
pub enum LLMError { | ||
#[error("Either OpenAI key was not provided or was invalid")] | ||
InvalidAPIKey, | ||
#[error("Failed to call OpenAI endpoint: {0}")] | ||
FailedRequest(#[from] reqwest::Error), | ||
#[error("{0}")] | ||
APIError(String), | ||
#[error("{0}")] | ||
StreamDoesNotExist(#[from] MetadataError), | ||
} | ||
|
||
impl actix_web::ResponseError for LLMError { | ||
fn status_code(&self) -> http::StatusCode { | ||
match self { | ||
Self::InvalidAPIKey => StatusCode::INTERNAL_SERVER_ERROR, | ||
Self::FailedRequest(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
Self::APIError(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
Self::StreamDoesNotExist(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
} | ||
} | ||
|
||
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> { | ||
actix_web::HttpResponse::build(self.status_code()) | ||
.insert_header(ContentType::plaintext()) | ||
.body(self.to_string()) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.