MCPcopy Create free account
hub / github.com/InfinitiBit/graphbit / parse_response

Method parse_response

core/src/llm/ai21.rs:118–182  ·  view source on GitHub ↗

Parse the AI21 response into your internal `LlmResponse`

(&self, resp: Ai21Response)

Source from the content-addressed store, hash-verified

116
117 /// Parse the AI21 response into your internal `LlmResponse`
118 fn parse_response(&self, resp: Ai21Response) -> GraphBitResult<LlmResponse> {
119 let choice = resp
120 .choices
121 .into_iter()
122 .next()
123 .ok_or_else(|| GraphBitError::llm_provider("ai21", "No choices in response"))?;
124
125 let mut content = choice.message.content;
126 // If content is empty but tool_calls are present, we may set default content text
127 if content.trim().is_empty()
128 && !choice
129 .message
130 .tool_calls
131 .as_ref()
132 .unwrap_or(&vec![])
133 .is_empty()
134 {
135 content = "Calling tool to fulfill request.".to_string();
136 }
137
138 let tool_calls = choice
139 .message
140 .tool_calls
141 .unwrap_or_default()
142 .into_iter()
143 .map(|tc| {
144 let params = if tc.function.arguments.trim().is_empty() {
145 serde_json::Value::Object(serde_json::Map::new())
146 } else {
147 match serde_json::from_str(&tc.function.arguments) {
148 Ok(v) => v,
149 Err(e) => {
150 tracing::warn!(
151 "Failed to parse AI21 tool arguments {}: {}",
152 tc.function.name,
153 e
154 );
155 serde_json::json!({ "raw_arguments": tc.function.arguments })
156 }
157 }
158 };
159 LlmToolCall {
160 id: tc.id,
161 name: tc.function.name,
162 parameters: params,
163 }
164 })
165 .collect();
166
167 let finish_reason = match choice.finish_reason.as_deref() {
168 Some("stop") => FinishReason::Stop,
169 Some("length") => FinishReason::Length,
170 Some("tool_calls") => FinishReason::ToolCalls,
171 Some(other) => FinishReason::Other(other.to_string()),
172 None => FinishReason::Stop,
173 };
174
175 let usage = LlmUsage::new(resp.usage.prompt_tokens, resp.usage.completion_tokens);

Callers 1

completeMethod · 0.45

Calls 6

to_stringMethod · 0.80
is_emptyMethod · 0.45
with_idMethod · 0.45
with_finish_reasonMethod · 0.45
with_usageMethod · 0.45
with_tool_callsMethod · 0.45

Tested by

no test coverage detected