nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
storyteller.cc
Go to the documentation of this file.
2
3#include <httplib.h>
4
5#include <string>
6#include <utility>
7
8#include "absl/strings/str_cat.h"
9#include "asio/post.hpp"
10#include "nlohmann/json.hpp"
11
12namespace nanommo {
13
14namespace {
15
16// The storyteller writes the stories that wait at the same time together, up
17// to sixteen, and each of these threads waits for one story, so with fewer, it
18// would write fewer at once.
19constexpr int kThreads = 16;
20
21// A story of a hundred tokens is a few lines of chat.
22constexpr int kMaxTokens = 100;
23
24// A story takes a second or two, and longer while the storyteller is busy.
25// After ten, the player has stopped waiting.
26constexpr int kTimeoutSeconds = 10;
27
28} // namespace
29
30Storyteller::Storyteller(asio::io_context& io, std::string host)
31 : io_(io), host_(std::move(host)), threads_(kThreads) {}
32
33void Storyteller::Tell(std::string prompt, Told told) {
34 asio::post(threads_, [this, prompt = std::move(prompt),
35 told = std::move(told)]() mutable {
36 absl::StatusOr<std::string> story = Complete(prompt);
37 asio::post(io_, [told = std::move(told), story = std::move(story)] {
38 told(story);
39 });
40 });
41}
42
43absl::StatusOr<std::string> Storyteller::Complete(
44 const std::string& prompt) const {
45 httplib::Client http(host_, kPort);
46 http.set_connection_timeout(1);
47 http.set_read_timeout(kTimeoutSeconds);
48 const nlohmann::json request = {{"prompt", prompt},
49 {"max_tokens", kMaxTokens}};
50 const httplib::Result result =
51 http.Post("/v1/completions", request.dump(), "application/json");
52 if (!result) {
53 return absl::UnavailableError(
54 absl::StrCat("couldn't reach the storyteller: ",
55 httplib::to_string(result.error())));
56 }
57 if (result->status != 200) {
58 return absl::InternalError(absl::StrCat(
59 "the storyteller answered ", result->status, ": ", result->body));
60 }
61 const nlohmann::json reply =
62 nlohmann::json::parse(result->body, nullptr, false);
63 const nlohmann::json::json_pointer text("/choices/0/text");
64 if (!reply.is_object() || !reply.contains(text) ||
65 !reply.at(text).is_string()) {
66 return absl::DataLossError("the storyteller's answer has no story in it");
67 }
68 return reply.at(text).get<std::string>();
69}
70
71} // namespace nanommo
std::function< void(absl::StatusOr< std::string >)> Told
Gets the story, or why there isn't one.
Definition storyteller.h:21
Storyteller(asio::io_context &io, std::string host)
void Tell(std::string prompt, Told told)
static constexpr uint16_t kPort
Definition storyteller.h:18
Definition chat.cc:9