-
Notifications
You must be signed in to change notification settings - Fork 24
/
AnthropicCreateMessageWithPdf.scala
60 lines (51 loc) · 2.2 KB
/
AnthropicCreateMessageWithPdf.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package io.cequence.openaiscala.examples.nonopenai
import io.cequence.openaiscala.anthropic.domain.Content.ContentBlock.{MediaBlock, TextBlock}
import io.cequence.openaiscala.anthropic.domain.Content.ContentBlockBase
import io.cequence.openaiscala.anthropic.domain.Message
import io.cequence.openaiscala.anthropic.domain.Message.{SystemMessage, UserMessageContent}
import io.cequence.openaiscala.anthropic.domain.response.CreateMessageResponse
import io.cequence.openaiscala.anthropic.domain.settings.AnthropicCreateMessageSettings
import io.cequence.openaiscala.anthropic.service.{AnthropicService, AnthropicServiceFactory}
import io.cequence.openaiscala.domain.NonOpenAIModelId
import io.cequence.openaiscala.examples.ExampleBase
import java.io.File
import java.nio.file.Files
import java.util.Base64
import scala.concurrent.Future
// requires `openai-scala-anthropic-client` as a dependency
object AnthropicCreateMessageWithPdf extends ExampleBase[AnthropicService] {
private val localImagePath = sys.env("EXAMPLE_PDF_PATH")
private val pdfBase64Source =
Base64.getEncoder.encodeToString(readPdfToBytes(localImagePath))
override protected val service: AnthropicService = AnthropicServiceFactory(withPdf = true)
private val messages: Seq[Message] = Seq(
SystemMessage("Talk in pirate speech. Reply to this prompt as a real pirate!"),
UserMessageContent(
Seq(
ContentBlockBase(TextBlock("Describe to me what is this PDF about!")),
MediaBlock.pdf(data = pdfBase64Source)
)
)
)
override protected def run: Future[_] =
service
.createMessage(
messages,
settings = AnthropicCreateMessageSettings(
model =
NonOpenAIModelId.claude_3_5_sonnet_20241022, // claude-3-5-sonnet-20241022 supports PDF (beta)
max_tokens = 8192
)
)
.map(printMessageContent)
def readPdfToBytes(filePath: String): Array[Byte] = {
val pdfFile = new File(filePath)
Files.readAllBytes(pdfFile.toPath)
}
private def printMessageContent(response: CreateMessageResponse) = {
val text =
response.content.blocks.collect { case ContentBlockBase(TextBlock(text), _) => text }
.mkString(" ")
println(text)
}
}