application.yml
ai:
gateway:
base-url: https://api.thistoken.ai/v1
api-key: ${THISTOKEN_API_KEY} # 从环境变量读取,别硬编码
model: gpt-4o-mini
Wrap the call in a simple Service:
@Service
public class ChatService {
private final RestClient restClient;
public ChatService(@Value("${ai.gateway.base-url}") String baseUrl,
@Value("${ai.gateway.api-key}") String apiKey) {
this.restClient = RestClient.builder()
.baseUrl(baseUrl)
.defaultHeader("Authorization", "Bearer " + apiKey)
.defaultHeader("Content-Type", "application/json")
.build();
}
public String chat(String userMessage) {
Map<String, Object> body = Map.of(
"model", "gpt-4o-mini",
"messages", List.of(
Map.of("role", "user", "content", userMessage)
)
);
Map<?, ?> resp = restClient.post()
.uri("/chat/completions")
.body(body)
.retrieve()
.body(Map.class);
List<?> choices = (List<?>) resp.get("choices");
Map<?, ?> message = (Map<?, ?>) ((Map<?, ?>) choices.get(0)).get("message");
return (String) message.get("content");
}
}
Because the gateway is OpenAI-compatible, the request and response structure of `/chat/completions` matches the official API exactly, so any parsing logic, retry logic, or streaming handling you've written before can be reused directly. The key is injected via environment variables to avoid leaking it through your code repository—this is the step indie developers most often overlook, and a single incident can cost far more than the time saved during integration.
## A Few Practical Tips
- **Get it working before optimizing**: Don't obsess over streaming output and concurrency in the first version—get the main pipeline working end-to-end first.
- **Set timeouts and fallbacks**: No matter how stable the gateway is, it's still an external dependency. Configure a 30-second timeout for your HTTP client and prepare a fallback message.
- **Track token usage**: Log the usage field from each response to help you evaluate costs (billing is based on the official pricing page).
- **Make models pluggable**: Put the model name in your configuration file too, so A/B comparisons later only require a config change and restart.
## Final Thoughts
For indie developers and small teams, the barrier to integrating large language models is no longer the technology itself, but the process: register first, get the key, verify with a minimal script, then move into the main project—every step verifiable and reversible. At this pace, you can give your Spring Boot project conversational capabilities in one afternoon, and spend the time you save on your product and your prompts.
Register an account and get started now: https://api.thistoken.ai/register
---
Ready to try it yourself? Sign up at https://api.thistoken.ai/register to get your API key and start building.Ready to try Token.AI?
Create a project-level API Key, enable channels in the console, and configure routing, budgets, and audit logs.
注册 ThisToken.AI 并获取 API Key