Hey Julianners,
Yesterday I stucked with the HTTP streaming functionality very well and just cannot figure out how to solve it. I suppose the problem is with the body in the POST message. Also I cannot do write(response, body)
due to it also gives back error in the end. Also tried the response_stream
io=IOBuffer();
HTTP.post(url, headers, JSON.json(body); response_stream=io)
but in this case I also get all the response at once instead of one by one.
The example code is here:
using HTTP
using JSON
url = "https://api.anthropic.com/v1/messages"
body = Dict(
"messages" => [
Dict("content" => "Hi, tell me a very short story", "role" => "user"),
],
"model" => "claude-3-5-sonnet-20240620",
"max_tokens" => 256,
"stream" => true, # Set to true for streaming
)
headers = Dict(
"content-type" => "application/json",
"x-api-key" => ENV["ANTHROPIC_API_KEY"],
"anthropic-version" => "2023-06-01",
)
function stream_response(url, headers, body)
HTTP.open("POST", url, headers, body=body) do response
@show response
for line in eachline(response)
@show line
if startswith(line, "data: ")
data = JSON.parse(line[6:end])
if data["type"] == "content_block_delta" && data["delta"]["type"] == "text_delta"
println(data["delta"]["text"])
flush(stdout)
end
end
end
end
end
stream_response(url, headers, JSON.json(body))
It must be working as a curl command does just right:
curl https://api.anthropic.com/v1/messages \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--data \
'{
"model": "claude-3-5-sonnet-20240620",
"messages": [{"role": "user", "content": "Hello, tell me a very short story"}],
"max_tokens": 256,
"stream": true
}'
Any idea how to manage it then?