hit anthropic API for ai question

This commit is contained in:
talksik
2025-07-26 21:34:11 -07:00
parent 966050a7b4
commit 1e4211052e
+74
View File
@@ -123,6 +123,74 @@ char* transcribe(FILE* audio_file) {
return transcript;
}
char* find_ai_response(char* json_response) {
printf("Parsing response: %s \n", json_response);
char* start = strstr(json_response, "\"text\":\"");
if (!start) return NULL;
start += 8; // Skip past "text":"
char* end = strchr(start, '"');
if (!end) return NULL;
size_t len = end - start;
char* result = malloc(len + 1);
strncpy(result, start, len);
result[len] = '\0';
return result;
}
char *ask_ai(char *question) {
CURL *curl;
CURLcode res;
struct curl_slist *headers = NULL;
// Initialize response buffer
struct response_data response = {0};
response.data = malloc(1);
response.size = 0;
// Create JSON payload
char json_payload[2048];
snprintf(json_payload, sizeof(json_payload),
"{"
"\"model\":\"claude-3-5-sonnet-20241022\","
"\"max_tokens\":1024,"
"\"messages\":[{\"role\":\"user\",\"content\":\"%s\"}]"
"}", question);
curl = curl_easy_init();
if (curl) {
// Set headers for Anthropic API
headers = curl_slist_append(headers, "content-Type: application/json");
headers = curl_slist_append(headers, "anthropic-version: 2023-06-01");
curl_easy_setopt(curl, CURLOPT_URL, "https://api.anthropic.com/v1/messages");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_payload);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl failed: %s\n", curl_easy_strerror(res));
free(response.data);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return NULL;
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
// Parse AI response from complete response
char* answer = find_ai_response(response.data);
free(response.data);
return answer;
}
int main() {
snd_pcm_t *pcm_handle = NULL;
@@ -239,6 +307,12 @@ int main() {
char* transcript = transcribe(file);
if (transcript) {
printf("Transcript: %s\n", transcript);
char *ai_answer = ask_ai(transcript);
if (ai_answer) {
printf("AI answer: %s\n", ai_answer);
free(ai_answer);
}
free(transcript);
} else {
fprintf(stderr, "unable to get transcript");