clean question parsin in json

This commit is contained in:
Santiago Lema 2025-05-07 03:31:59 -03:00
parent 47b1cbaf04
commit efbe679a6b
8 changed files with 328 additions and 317 deletions

52
App.cpp
View file

@ -3,7 +3,6 @@
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include "App.h"
#include "MainWindow.h"
@ -13,42 +12,29 @@
#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Application"
const char* kApplicationSignature = "application/x-vnd.SLema-DumBer";
const char *kApplicationSignature = "application/x-vnd.SLema-DumBer";
App::App()
:
BApplication(kApplicationSignature)
{
MainWindow* mainWindow = new MainWindow();
mainWindow->Show();
App::App() : BApplication(kApplicationSignature) {
MainWindow *mainWindow = new MainWindow();
mainWindow->Show();
}
App::~App() {}
App::~App()
{
void App::AboutRequested() {
BAboutWindow *about = new BAboutWindow(B_TRANSLATE_SYSTEM_NAME("DumBer"),
kApplicationSignature);
about->AddDescription(B_TRANSLATE("about_body"));
about->AddCopyright(2024, "Santiago Lema");
about->AddText("e-mail me at haiku@lema.org");
about->AddText("or ping me on the fediverse on @santi@go.lema.org");
about->Show();
}
void
App::AboutRequested()
{
BAboutWindow* about
= new BAboutWindow(B_TRANSLATE_SYSTEM_NAME("DumBer"), kApplicationSignature);
about->AddDescription(B_TRANSLATE("about_body"));
about->AddCopyright(2024, "Santiago Lema");
about->AddText("e-mail me at haiku@lema.org");
about->AddText("or ping me on the fediverse on @santi@go.lema.org");
about->Show();
}
int
main()
{
App* app = new App();
app->Run();
delete app;
return 0;
int main() {
App *app = new App();
app->Run();
delete app;
return 0;
}

54
BUILD.bazel Normal file
View file

@ -0,0 +1,54 @@
cc_library(
name = "json",
hdrs = [
"include/nlohmann/adl_serializer.hpp",
"include/nlohmann/byte_container_with_subtype.hpp",
"include/nlohmann/detail/abi_macros.hpp",
"include/nlohmann/detail/conversions/from_json.hpp",
"include/nlohmann/detail/conversions/to_chars.hpp",
"include/nlohmann/detail/conversions/to_json.hpp",
"include/nlohmann/detail/exceptions.hpp",
"include/nlohmann/detail/hash.hpp",
"include/nlohmann/detail/input/binary_reader.hpp",
"include/nlohmann/detail/input/input_adapters.hpp",
"include/nlohmann/detail/input/json_sax.hpp",
"include/nlohmann/detail/input/lexer.hpp",
"include/nlohmann/detail/input/parser.hpp",
"include/nlohmann/detail/input/position_t.hpp",
"include/nlohmann/detail/iterators/internal_iterator.hpp",
"include/nlohmann/detail/iterators/iter_impl.hpp",
"include/nlohmann/detail/iterators/iteration_proxy.hpp",
"include/nlohmann/detail/iterators/iterator_traits.hpp",
"include/nlohmann/detail/iterators/json_reverse_iterator.hpp",
"include/nlohmann/detail/iterators/primitive_iterator.hpp",
"include/nlohmann/detail/json_custom_base_class.hpp",
"include/nlohmann/detail/json_pointer.hpp",
"include/nlohmann/detail/json_ref.hpp",
"include/nlohmann/detail/macro_scope.hpp",
"include/nlohmann/detail/macro_unscope.hpp",
"include/nlohmann/detail/meta/call_std/begin.hpp",
"include/nlohmann/detail/meta/call_std/end.hpp",
"include/nlohmann/detail/meta/cpp_future.hpp",
"include/nlohmann/detail/meta/detected.hpp",
"include/nlohmann/detail/meta/identity_tag.hpp",
"include/nlohmann/detail/meta/is_sax.hpp",
"include/nlohmann/detail/meta/std_fs.hpp",
"include/nlohmann/detail/meta/type_traits.hpp",
"include/nlohmann/detail/meta/void_t.hpp",
"include/nlohmann/detail/output/binary_writer.hpp",
"include/nlohmann/detail/output/output_adapters.hpp",
"include/nlohmann/detail/output/serializer.hpp",
"include/nlohmann/detail/string_concat.hpp",
"include/nlohmann/detail/string_escape.hpp",
"include/nlohmann/detail/string_utils.hpp",
"include/nlohmann/detail/value_t.hpp",
"include/nlohmann/json.hpp",
"include/nlohmann/json_fwd.hpp",
"include/nlohmann/ordered_map.hpp",
"include/nlohmann/thirdparty/hedley/hedley.hpp",
"include/nlohmann/thirdparty/hedley/hedley_undef.hpp",
],
includes = ["include"],
visibility = ["//visibility:public"],
alwayslink = True,
)

BIN
DumBer

Binary file not shown.

21
LICENSE.MIT Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013-2025 Niels Lohmann
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -15,27 +15,25 @@
#include <LayoutBuilder.h>
#include <Menu.h>
#include <MenuBar.h>
#include <MimeType.h>
#include <ScrollView.h>
#include <StringView.h>
#include <MimeType.h>
#include <memory.h>
#include <View.h>
#include <Path.h>
#include <FindDirectory.h>
#include <File.h>
#include <FindDirectory.h>
#include <Path.h>
#include <String.h>
#include <iostream>
#include <algorithm>
#include "json.hpp"
// #include <iostream>
#include <algorithm>
#include <cstdio>
#include "include/json.hpp"
using json = nlohmann::json;
using namespace BPrivate::Network;
#undef B_TRANSLATION_CONTEXT
@ -59,7 +57,6 @@ MainWindow::MainWindow()
_inputField = new BTextControl("", "What is the matrix ?",
new BMessage(kQuestionChanged));
_progress = new BStatusBar("prog");
_progress->SetMaxValue(100);
_progress->SetTo(0);
@ -87,9 +84,8 @@ MainWindow::MainWindow()
_inputField->SetExplicitMinSize(BSize(B_SIZE_UNSET, askH));
_inputField->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, askH * 6));
_apiKey = ReadOpenAIKey();
printf("key is: %s", _apiKey.String());
_apiKey = ReadOpenAIKey();
printf("key is: %s", _apiKey.String());
BButton *sendButton =
new BButton("send", B_TRANSLATE("Send"), new BMessage(kSendPrompt),
@ -99,9 +95,10 @@ MainWindow::MainWindow()
_answerView->MakeEditable(false); // Disable editing
_answerView->MakeSelectable(true); // Enable text selection
_answerView->SetWordWrap(true);
BScrollView *scrollView =
new BScrollView("scroll_view", _answerView, B_FOLLOW_ALL | B_WILL_DRAW ,0 , false, true); // horizontal and vertical scrollbars
new BScrollView("scroll_view", _answerView, B_FOLLOW_ALL | B_WILL_DRAW, 0,
false, true); // horizontal and vertical scrollbars
BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
@ -198,7 +195,16 @@ void MainWindow::MessageReceived(BMessage *message) {
// that the request is done.
BHttpBody body = _lastResult->Body();
if (body.text.has_value())
_answerView->SetText(body.text.value());
{
json parsed = json::parse(body.text.value().String());
std::string content = parsed["choices"][0]["message"]["content"];
_answerView->SetText(content.c_str());
// _answerView->SetText(body.text.value());
}
else
_answerView->SetText("nuthin'");
}
@ -263,56 +269,31 @@ void MainWindow::sendQuery() {
BHttpRequest request = BHttpRequest(url);
request.SetMethod(BHttpMethod::Post);
// if the API key file contains a new line bhttpfields will crash with invalid content
// .end() requires include algorithm
// if the API key file contains a new line bhttpfields will crash with invalid
// content .end() requires include algorithm
std::string key = _apiKey.String();
key.erase(std::remove(key.begin(), key.end(), '\n'), key.end());
key.erase(std::remove(key.begin(), key.end(), '\r'), key.end());
std::string bearer = std::string("Bearer ")+std::string(key);
std::string bearer = std::string("Bearer ") + std::string(key);
BHttpFields fields = BHttpFields();
fields.AddField("Authorization", bearer );
// fields.AddField("Content-Type", "application/json"); //NO, this will crash, we set it in request
fields.AddField("Authorization", bearer);
// fields.AddField("Content-Type", "application/json"); //NO, this will
// crash, we set it in request
request.SetFields(fields);
json bodyJson = {
{"model", "gpt-3.5-turbo"},
{"messages", {{{"role", "user"}, {"content", _inputField->Text()}}}}};
nlohmann::json bodyJson = {
{ "model", "gpt-3.5-turbo" },
{ "messages", {
{
{ "role", "user" },
{ "content", "What is the capital of France?" }
}
}}
};
std::string body = bodyJson.dump();
BString mime = BString("application/json");
//request.SetRequestBody(body.c_str(),mime);
// 2. Wrap it in BMemoryIO
auto memoryIO = std::make_unique<BMemoryIO>(
body.c_str(), // pointer to data
body.size() // size of data
);
// 3. Set the request body with mime type
request.SetRequestBody(std::move(memoryIO), "application/json", body.size());
//curl https://api.openai.com/v1/chat/completions \
// -H "Authorization: Bearer YOUR_API_KEY" \
// -H "Content-Type: application/json" \
// -d '{
// "model": "gpt-3.5-turbo",
// "messages": [{"role": "user", "content": "What is the capital of France?"}]
// }'
std::string body = bodyJson.dump();
BString mime = BString("application/json");
// request.SetRequestBody(body.c_str(),mime);
auto memoryIO = std::make_unique<BMemoryIO>(body.c_str(), body.size());
request.SetRequestBody(std::move(memoryIO), "application/json", body.size());
printf("Sending Prompt to server: %s\n", url.UrlString().String());
_lastResult = _sharedSession.Execute(std::move(request), nullptr, this);
@ -360,33 +341,32 @@ BMenuBar *MainWindow::_BuildMenu() {
}
BString MainWindow::ReadOpenAIKey() {
// /boot/home/config/openai_key
// or ~/.config/openai_key on linux
BPath configPath;
if (find_directory(B_USER_SETTINGS_DIRECTORY, &configPath) != B_OK)
return "error: couldn't find config directory";
// /boot/home/config/openai_key
// or ~/.config/openai_key on linux
configPath.Append("openai_key");
BPath configPath;
if (find_directory(B_USER_SETTINGS_DIRECTORY, &configPath) != B_OK)
return "error: couldn't find config directory";
BFile file(configPath.Path(), B_READ_ONLY);
printf("full path:%s\n",configPath.Path());
if (file.InitCheck() != B_OK)
return "error: couldn't open key file ";
configPath.Append("openai_key");
off_t size;
file.GetSize(&size);
char* buffer = new char[size + 1];
file.Read(buffer, size);
buffer[size] = '\0'; // null-terminate
BFile file(configPath.Path(), B_READ_ONLY);
BString result(buffer);
delete[] buffer;
printf("full path:%s\n", configPath.Path());
if (file.InitCheck() != B_OK)
return "error: couldn't open key file ";
return result;
off_t size;
file.GetSize(&size);
char *buffer = new char[size + 1];
file.Read(buffer, size);
buffer[size] = '\0'; // null-terminate
BString result(buffer);
delete[] buffer;
return result;
}

View file

@ -71,7 +71,7 @@ LIBPATHS =
# "#include <header>". Directories that contain the files in SRCS are
# NOT auto-included here.
#SYSTEM_INCLUDE_PATHS = $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/interface) $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/netservices2)
SYSTEM_INCLUDE_PATHS = $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/interface) $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/netservices2)
SYSTEM_INCLUDE_PATHS = $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/interface) $(shell findpaths -e B_FIND_PATH_HEADERS_DIRECTORY private/netservices2) ./include
# Additional paths paths to look for local headers. These use the form
# #include "header". Directories that contain the files in SRCS are

File diff suppressed because it is too large Load diff

24
meson.build Normal file
View file

@ -0,0 +1,24 @@
project('nlohmann_json',
'cpp',
version : '3.12.0',
license : 'MIT',
)
nlohmann_json_dep = declare_dependency(
include_directories: include_directories('single_include')
)
nlohmann_json_multiple_headers = declare_dependency(
include_directories: include_directories('include')
)
if not meson.is_subproject()
install_headers('single_include/nlohmann/json.hpp', subdir: 'nlohmann')
install_headers('single_include/nlohmann/json_fwd.hpp', subdir: 'nlohmann')
pkgc = import('pkgconfig')
pkgc.generate(name: 'nlohmann_json',
version: meson.project_version(),
description: 'JSON for Modern C++'
)
endif