AnthropicChatModel
A ChatModel that calls Claude through the Messages API of Anthropic. It is built on Ktor, so it runs on every Kotlin target.
val client = HttpClient()
val model = AnthropicChatModel(client, apiKey = System.getenv("ANTHROPIC_API_KEY"), model = "claude-opus-5-5")
val agent = toolAgent(model, tools = listOf(forecast))HttpClient() uses the Ktor engine among your dependencies, for example ktor-client-okhttp on Android, ktor-client-darwin on iOS or ktor-client-js in a browser. The client is yours: share one between models, and close it when your app is done with it.
A call may take five minutes, whatever limits the client and its engine have: the CIO engine, for one, ends a request after 15 seconds. Change the limit with timeout.
chat returns when Claude has finished, and stream delivers the text while Claude writes it. A toolAgent uses stream when its run is collected with stream. Claude's thinking and other content that the API wants back unchanged travels in ChatMessage.Assistant.providerContent.
In a browser the API only accepts a request with the header anthropic-dangerous-direct-browser-access: true; pass it in headers. That is acceptable when each user enters a key of their own. Never ship an app that contains a key of yours.
Parameters
the Ktor client that sends the requests.
the Anthropic API key.
the id of the model, for example claude-opus-5-5.
the most tokens the model may write in one answer. An answer that reaches the limit comes back with ChatMessage.Assistant.truncated set.
more fields for the body of every request, such as temperature, thinking or tool_choice. A field given here replaces the one this class would send.
more headers for every request, such as anthropic-beta.
where the API lives. Change it to go through a proxy or a gateway.
how long one call may take, from the request to the end of the answer, and how long it may wait for the next piece of the answer. It replaces the limits of client and of its engine for the requests of this model. null leaves those limits in place.
Throws
if timeout is not positive.
Functions
Sends request to the Messages API and returns Claude's answer.