File size: 1,973 Bytes
12377a0
 
 
 
 
 
 
 
3b3c5b4
12377a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
import gradio as gr
import anthropic
from anthropic.types import ContentBlock

from time import time
client = anthropic.Anthropic()

# Read file content into a string
with open("some-long-text.txt", "r") as file:
    text = file.read()

def claude_conversation(message, history):
    # Prepare the conversation history
    messages = []
    for human, assistant in history:
        if human.strip():  # Only add non-empty human messages
            messages.append({"role": "user", "content": human})
        if assistant.strip():  # Only add non-empty assistant messages
            messages.append({"role": "assistant", "content": assistant})
    
    # Add the new message if it's not empty
    if message.strip():
        messages.append({"role": "user", "content": message})
    else:
        return "Please enter a non-empty message."

    try:
        # Make the API call

        start = time ()
        response = client.beta.prompt_caching.messages.create(
            model="claude-3-5-sonnet-20240620",
            max_tokens=1024,
            system=[
                {
                    "type": "text",
                    "text": "You are an AI assistant tasked with analyzing legal documents."
                },
                {
                    "type": "text",
                    "text": text,
                    "cache_control": {"type": "ephemeral"}
                }
            ],
            messages=messages
        )

        # Extract and return Claude's response

        print (response)

        end = time ()
        print(f"Elapsed time: {end - start} seconds")

        return response.content[0].text
    except anthropic.APIError as e:
        return f"An error occurred: {str(e)}"

# Create the Gradio interface
demo = gr.ChatInterface(
    fn=claude_conversation,
    title="Claude Legal Document Analyzer",
    description="Ask questions about the legal document loaded from 'mainarbeit.txt'."
)

# Launch the app
demo.launch()