forgeant docs-test-0
Build LLM-powered agents in C++
Loading...
Searching...
No Matches
structured.hpp
Go to the documentation of this file.
1#ifndef FORGEANT_STRUCTURED_STRUCTURED_HPP
2#define FORGEANT_STRUCTURED_STRUCTURED_HPP
3
4#include <exception>
12#include <string>
13#include <utility>
14
15namespace forgeant {
16
18
19template <typename T>
21 StructuredConfig config = {}) {
22 auto schema = ParamSchema<T>::schema();
23 Usage accumulated;
24 std::string last_finish_reason;
25 std::string last_error;
26
27 for (int attempt = 0; attempt <= config.max_retries; ++attempt) {
28 ChatRequest request;
29 request.output_schema = schema;
30
31 LlmResponse response;
32 try {
33 response = provider.chat(working, request);
34 } catch (const std::exception& e) {
35 throw AgentRunError(AgentRunError::Kind::provider_error, e.what(), std::move(working),
36 accumulated, attempt + 1, "error");
37 }
38
39 accumulated.input_tokens += response.usage.input_tokens;
40 accumulated.output_tokens += response.usage.output_tokens;
41 last_finish_reason = response.finish_reason;
42 working.add(response.message);
43
44 try {
45 auto json = extract_json_from_response(response);
46 AgentResult<T> result;
47 result.output = json.template get<T>();
48 result.conversation = std::move(working);
49 result.total_usage = accumulated;
50 result.iterations = attempt + 1;
51 result.finish_reason = std::move(last_finish_reason);
52 return result;
53 } catch (const std::exception& e) {
54 last_error = e.what();
55 if (attempt < config.max_retries) {
56 working.add(Message(
57 Role::user, "Your response did not match the required schema: " + last_error +
58 ". Please respond with valid JSON matching the schema."));
59 }
60 }
61 }
62
63 throw AgentRunError(AgentRunError::Kind::structured_parse,
64 "structured output failed after " + std::to_string(config.max_retries + 1) +
65 " attempts: " + last_error,
66 std::move(working), accumulated, config.max_retries + 1,
67 std::move(last_finish_reason));
68}
69
70} // namespace forgeant
71
72#endif // FORGEANT_STRUCTURED_STRUCTURED_HPP
Definition conversation.hpp:12
void add(Message message)
Definition conversation.hpp:20
Definition json.hpp:27
Definition provider.hpp:10
virtual LlmResponse chat(const Conversation &conversation, const ChatRequest &request={})=0
Definition agent.hpp:25
Json extract_json_from_response(const LlmResponse &response)
AgentResult< T > structured(LlmProvider &provider, Conversation working, StructuredConfig config={})
Definition structured.hpp:20
Definition result.hpp:11
Definition response.hpp:14
Definition config.hpp:6