|
| 1 | +import dev.langchain4j.data.message.PdfFileContent; |
| 2 | +import dev.langchain4j.data.message.TextContent; |
| 3 | +import dev.langchain4j.data.message.UserMessage; |
| 4 | +import dev.langchain4j.model.anthropic.AnthropicChatModel; |
| 5 | +import dev.langchain4j.model.chat.ChatModel; |
| 6 | +import dev.langchain4j.model.chat.response.ChatResponse; |
| 7 | +import org.junit.jupiter.api.Test; |
| 8 | + |
| 9 | +import java.net.URI; |
| 10 | +import java.util.Base64; |
| 11 | + |
| 12 | +import static dev.langchain4j.internal.Utils.readBytes; |
| 13 | +import static org.assertj.core.api.Assertions.assertThat; |
| 14 | + |
| 15 | +class AnthropicPdfExample { |
| 16 | + |
| 17 | + ChatModel model = AnthropicChatModel.builder() |
| 18 | + // API key can be created here: https://console.anthropic.com/settings/keys |
| 19 | + .apiKey(System.getenv("ANTHROPIC_API_KEY")) |
| 20 | + .modelName("claude-sonnet-4-5-20250514") |
| 21 | + .logRequests(true) |
| 22 | + .logResponses(true) |
| 23 | + .build(); |
| 24 | + |
| 25 | + @Test |
| 26 | + void AnthropicChatModel_with_PDF_via_URL_Example() { |
| 27 | + |
| 28 | + UserMessage userMessage = UserMessage.from( |
| 29 | + PdfFileContent.from(URI.create("https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf")), |
| 30 | + TextContent.from("What are the key findings in this document?") |
| 31 | + ); |
| 32 | + |
| 33 | + ChatResponse chatResponse = model.chat(userMessage); |
| 34 | + |
| 35 | + assertThat(chatResponse.aiMessage().text()).isNotBlank(); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + void AnthropicChatModel_with_PDF_via_Base64_Example() { |
| 40 | + |
| 41 | + byte[] pdfBytes = readBytes("https://assets.anthropic.com/m/1cd9d098ac3e6467/original/Claude-3-Model-Card-October-Addendum.pdf"); |
| 42 | + String base64EncodedPdf = Base64.getEncoder().encodeToString(pdfBytes); |
| 43 | + |
| 44 | + UserMessage userMessage = UserMessage.from( |
| 45 | + PdfFileContent.from(base64EncodedPdf, "application/pdf"), |
| 46 | + TextContent.from("Summarize this document.") |
| 47 | + ); |
| 48 | + |
| 49 | + ChatResponse chatResponse = model.chat(userMessage); |
| 50 | + |
| 51 | + assertThat(chatResponse.aiMessage().text()).isNotBlank(); |
| 52 | + } |
| 53 | +} |
0 commit comments