How to analyze document with Claude API
Quick answer
Use the
anthropic Python SDK to send your document text to the claude-3-5-sonnet-20241022 model via the client.messages.create() method with a clear system prompt. The API returns analyzed insights in response.content[0].text for easy extraction.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the anthropic Python SDK and set your API key as an environment variable for secure access.
pip install anthropic>=0.20 Step by step
Use the following Python code to analyze a document's content with Claude. Replace YOUR_DOCUMENT_TEXT with your actual text. The system prompt guides Claude to analyze the document and provide insights.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
document_text = """YOUR_DOCUMENT_TEXT"""
system_prompt = "You are an expert document analyst. Provide a detailed analysis of the following text."
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
system=system_prompt,
messages=[{"role": "user", "content": document_text}]
)
analysis = response.content[0].text
print("Document analysis:\n", analysis) output
Document analysis: <Claude's detailed analysis of the document text>
Common variations
- Use different Claude models like
claude-3-opus-20240229for faster responses. - Implement async calls with
asyncioandclient.messages.acreate()for non-blocking analysis. - Adjust
max_tokensto control response length.
import asyncio
import os
import anthropic
async def analyze_document_async(text: str):
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are an expert document analyst. Provide a detailed analysis of the following text."
response = await client.messages.acreate(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
system=system_prompt,
messages=[{"role": "user", "content": text}]
)
return response.content[0].text
async def main():
document_text = """YOUR_DOCUMENT_TEXT"""
analysis = await analyze_document_async(document_text)
print("Async document analysis:\n", analysis)
asyncio.run(main()) output
Async document analysis: <Claude's detailed analysis of the document text>
Troubleshooting
- If you get authentication errors, verify your
ANTHROPIC_API_KEYenvironment variable is set correctly. - If responses are cut off, increase
max_tokens. - For unexpected output, refine the
systemprompt to be more specific about the analysis required.
Key Takeaways
- Use the
anthropicSDK withclaude-3-5-sonnet-20241022for document analysis. - Set a clear
systemprompt to guide Claude's analysis output. - Adjust
max_tokensto control the detail level of the analysis. - Async calls improve performance for large or multiple documents.
- Always secure your API key via environment variables.