Other Language Examples
Java
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
public class AIClient {
private final String apiKey;
private final String baseUrl;
private final HttpClient httpClient;
private final Gson gson;
public AIClient(String apiKey, String baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.httpClient = HttpClient.newHttpClient();
this.gson = new Gson();
}
public String chat(String prompt, String model) throws Exception {
// Build request body
JsonObject requestBody = new JsonObject();
requestBody.addProperty("model", model);
JsonArray messages = new JsonArray();
JsonObject message = new JsonObject();
message.addProperty("role", "user");
message.addProperty("content", prompt);
messages.add(message);
requestBody.add("messages", messages);
requestBody.addProperty("max_tokens", 1000);
// Send request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/v1/chat/completions"))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(gson.toJson(requestBody)))
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
JsonObject responseJson = gson.fromJson(response.body(), JsonObject.class);
return responseJson.getAsJsonArray("choices")
.get(0).getAsJsonObject()
.getAsJsonObject("message")
.get("content").getAsString();
} else {
throw new RuntimeException("API call failed: " + response.statusCode() +
" - " + response.body());
}
}
// Usage example
public static void main(String[] args) throws Exception {
AIClient client = new AIClient("your-api-key",
"https://ai.machinefi.com");
String response = client.chat("Write a singleton pattern in Java", "gpt-3.5-turbo");
System.out.println(response);
}
}Go
PHP
Framework Integration
LangChain Integration
Note: Full code examples for Java, Go, and PHP are available in the complete documentation. Each includes proper error handling, request building, and response parsing.
Last updated

