कोर्स
Anthropic ने हाल ही में अपडेटेड Claude Sonnet 4.5, Claude Agents SDK, और Imagine with Claude लॉन्च किया है।
Claude Sonnet 4 के रिलीज़ के साथ, डेवलपर्स को अब शक्तिशाली नई क्षमताएँ मिली हैं—जिनमें नैटिव कोड निष्पादन, लचीला Files API, और डायनामिक टूल उपयोग शामिल हैं। ये फीचर केवल टेक्स्ट इंटरैक्शन से आगे बढ़कर AI-संचालित अनुप्रयोग बनाने के रोमांचक अवसर खोलते हैं।
इस ट्यूटोरियल में, मैं आपको इन नए फीचर्स के माध्यम से ले जाऊँगा—एक Python-आधारित एजेंट बनाकर जो सीधे आपके टर्मिनल से उन्नत गणितीय समस्याएँ हल कर सकता है। आप the नए पेश किए गए नैटिव कोड निष्पादन टूल और Files API का उपयोग करना सीखेंगे।
अंत तक, आपके पास Claude Sonnet 4 द्वारा संचालित एक कार्यशील एजेंट होगा जो समस्याओं का विश्लेषण कर सकता है, Python कोड लिख और चला सकता है, और नीचे दिए गए जैसे विज़ुअल भी बना सकता है।

the इस प्रोजेक्ट का GitHub रिपॉज़िटरी देखें ताकि आप एप्लिकेशन बनाने के लिए पूरा कोड देख सकें।
यदि आप Claude जैसे LLMs के साथ बिल्डिंग की यात्रा अभी शुरू कर रहे हैं, तो यह AI डेवलपर रोडमैप essenशियल टूल्स, कौशल और सीखने के रास्तों की रूपरेखा प्रस्तुत करता है।
Anthropic API में क्या नया है
ट्यूटोरियल में जाने से पहले, आइए Anthropic API के जरिए उपलब्ध हाल ही में जारी सभी नए फीचर्स पर नज़र डालें। यदि आप पहले से इनके बारे में जानते हैं, तो आगे बढ़ने के लिए स्वतंत्र हैं।
मेरा मानना है कि पूरा Claude 4 घोषणा इस एक छवि में सारांशित की जा सकती है:

Claude 4 मॉडल (Opus और Sonnet 4) सत्यापित सॉफ्टवेयर इंजीनियरिंग कार्यों में प्रतिस्पर्धियों को बड़े अंतर से पीछे छोड़ते हैं। Anthropic ने मॉडल के व्यवहार में कुछ महत्वपूर्ण बदलाव करके यह उपलब्धि हासिल की है:
- लंबे रनटाइम: दोनों मॉडल हजारों चरणों वाली समस्याओं को हल करने के लिए कई घंटों के सतत टास्क निष्पादन का समर्थन करते हैं।
- टूल उपयोग के साथ विस्तारित चिंतन: अब दोनों मॉडल विस्तारित सोच के दौरान वेब सर्च जैसे टूल्स का इस्तेमाल कर सकते हैं, जिससे Claude तर्क और टूल उपयोग के बीच बारी-बारी से काम करके जवाबों में सुधार कर सके।
- समानांतर टूल निष्पादन: अब मॉडल टूल्स को क्रमिक रूप से नहीं, बल्कि एक साथ समानांतर रूप से चला सकते हैं।
- निर्देशों का अधिक सटीक पालन: उन्नत steerability उपयोगकर्ताओं को कार्यान्वयन और इस पर अधिक नियंत्रण देती है कि Claude निर्देशों पर कैसे प्रतिक्रिया देता है।
- बेहतर मेमोरी क्षमताएँ: स्थानीय फ़ाइलों तक पहुँच मिलने पर, मॉडल समय के साथ निरंतरता बनाए रखने और अंतर्निहित ज्ञान बनाने के लिए प्रमुख तथ्यों को निकाल और सहेज सकते हैं।
- शॉर्टकट व्यवहार में कमी: पिछले संस्करणों की तुलना में, दोनों मॉडल कार्य पूरे करने के लिए शॉर्टकट्स या loopholes का उपयोग करने की संभावना 65% कम दिखाते हैं (अधिक विवरण के लिए पूर्ण घोषणा पोस्ट देखें)।
इसके अलावा, Claude 4 मॉडल परिवार की घोषणा के हिस्से के रूप में, Anthropic ने चार नए फीचर जोड़े हैं—कोड निष्पादन टूल, Files API, MCP कनेक्टर, और विस्तारित प्रॉम्प्ट कैशिंग। ये टूल डेवलपर्स के लिए AI एप्लिकेशन बनाने के तरीकों को बदलते हैं।
कोड निष्पादन टूल: Python कोड को सुरक्षित रूप से चलाएँ
The कोड निष्पादन टूल Claude को एक सुरक्षित सैंडबॉक्स परिवेश में Python कोड चलाने देता है। केवल कोड सुझाव लिखने के बजाय, अब Claude कोड निष्पादित कर सकता है, परिणामों का विश्लेषण कर सकता है और समाधानों पर पुनरावृत्ति कर सकता है।
कोड निष्पादन टूल का उपयोग करने के लिए, इसे अपने tools ऐरे में जोड़ें और आवश्यक बीटा हेडर शामिल करें:
from anthropic import Anthropic
# Initialize client with the code execution beta header
client = Anthropic(
default_headers={
"anthropic-beta": "code-execution-2025-05-22"
}
)
# Send a request that triggers code execution
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
messages=[{
"role": "user",
"content": "Solve the quadratic equation 2x² + 5x - 3 = 0 and plot the parabola"
}],
tools=[{
"type": "code_execution_20250522",
"name": "code_execution"
}]
)
जब Claude कोड चलाता है, तो प्रतिक्रिया में जनरेट किया गया कोड और उसका निष्पादन परिणाम दोनों होते हैं। यहाँ विभिन्न घटकों को पार्स करने का तरीका है:
# Parse the response to extract code and results
for item in response.content:
if item.type == "server_tool_use":
# This contains the actual Python code Claude wrote
print(f"Code executed:\n{item.input['code']}")
elif item.type == "code_execution_tool_result":
# This contains the output from running the code
print(f"Output:\n{item.content['stdout']}")
if item.content.get('stderr'):
print(f"Errors:\n{item.content['stderr']}")
सैंडबॉक्स सीमाएँ: कोड निष्पादन परिवेश में कई इनबिल्ट सुरक्षा प्रतिबंध हैं। Claude एक अलग-थलग कंटेनर में चलता है, जिसमें इंटरनेट एक्सेस नहीं होता, सीमित कंप्यूट संसाधन (1 GB RAM, 5 GB डिस्क स्पेस, और 1 CPU) होते हैं, और यह आपके लोकल फ़ाइल सिस्टम तक पहुँच नहीं कर सकता। वातावरण में पहले से numpy, pandas, matplotlib, और scipy जैसी लोकप्रिय लाइब्रेरीज़ इंस्टॉल होती हैं, लेकिन आप निष्पादन के दौरान अतिरिक्त पैकेज इंस्टॉल नहीं कर सकते।
Files API: जटिल कार्यों के लिए स्थायी फ़ाइल संदर्भ
The Files API आपको दस्तावेज़ एक बार अपलोड करने और उन्हें कई वार्तालापों में संदर्भित करने की अनुमति देता है। इससे हर API अनुरोध में बड़े दस्तावेज़ शामिल करने की आवश्यकता समाप्त हो जाती है।
सबसे पहले, अपनी फ़ाइल Anthropic के सर्वरों पर अपलोड करें:
# Upload a file once - this stores it on Anthropic's servers
uploaded_file = client.beta.files.upload(
file=open("sales_data.csv", "rb"),
purpose="user_upload"
)
# The uploaded_file.id can now be referenced in multiple conversations
अपलोड होने के बाद, container_upload कंटेंट टाइप का उपयोग करते हुए अपनी API कॉल्स में फ़ाइल का संदर्भ दें:
# Reference the uploaded file in a conversation
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=4096,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Create a quarterly sales report from this data"},
{"type": "container_upload", "file_id": uploaded_file.id}
]
}],
tools=[{
"type": "code_execution_20250522",
"name": "code_execution"
}]
)
जब Claude कोड निष्पादन के दौरान फ़ाइलें बनाता है (जैसे प्लॉट्स या प्रोसेस्ड डेटा), तो आप उन्हें निकाल और डाउनलोड कर सकते हैं:
# Extract file IDs of any files Claude created during execution
def extract_created_files(response):
file_ids = []
for item in response.content:
if item.type == 'code_execution_tool_result':
content = item.content
if content.get('type') == 'code_execution_result':
# Look for file objects in the execution results
for file_obj in content.get('content', []):
if 'file_id' in file_obj:
file_ids.append(file_obj['file_id'])
return file_ids
# Download any files Claude created
created_files = extract_created_files(response)
for file_id in created_files:
file_content = client.beta.files.download(file_id)
file_content.write_to_file(f"output_{file_id}.png")
MCP कनेक्टर: Claude को किसी भी वर्कफ़्लो में प्लग करें
MCP कनेक्टर Model Context Protocol सपोर्ट सीधे API में लाता है। MCPs Claude को डेटाबेस, APIs, और उत्पादकता टूल्स जैसी बाहरी सेवाओं से बिना कस्टम इंटीग्रेशन कोड के कनेक्ट होने देते हैं।
पहले, MCP सर्वरों से कनेक्ट करने के लिए क्लाइंट इंफ्रास्ट्रक्चर बनाना पड़ता था। अब, आप बस अपनी API रिक्वेस्ट में एक रिमोट MCP सर्वर URL प्रदान करें, और Claude अपने आप उपलब्ध टूल्स को खोज लेता है, कनेक्शन मैनेज करता है, और ऑथेंटिकेशन संभालता है।
यह Zapier और Asana जैसी कंपनियों के MCP सर्वरों के बढ़ते इकोसिस्टम तक पहुँच खोलता है, जिससे आप ऐसे एजेंट बना सकते हैं जो आपके कैलेंडर को पढ़ें, प्रोजेक्ट मैनेजमेंट टूल्स को अपडेट करें, या सैकड़ों अन्य सेवाओं के साथ इंटीग्रेट करें।
Claude Sonnet 4 के साथ शुरुआत: प्रोजेक्ट ओवरव्यू और सेटअप
अब जबकि हम नए API फीचर्स समझ चुके हैं, आइए अपना इंटरैक्टिव गणित समस्या समाधानकर्ता बनाते हैं। यह Claude की कोड निष्पादन क्षमताओं को फ़ाइल हैंडलिंग के साथ जोड़कर एक संपूर्ण गणितीय सहायक बनाएगा।
हमारा एप्लिकेशन प्राकृतिक भाषा में गणित के प्रश्न स्वीकार करेगा, उन्हें हल करने के लिए Python कोड निष्पादित करेगा, विज़ुअलाइज़ेशन जेनरेट करेगा, और व्यापक रिपोर्ट्स सहेजेगा।
ऐसे प्रोजेक्ट्स को संरचित तरीके से बनाने के लिए, Developing AI Applications ट्रैक देखें।
> नोट: चूँकि हम लंबे कोड ब्लॉक्स को व्याख्याओं के साथ तोड़ेंगे, स्निपेट्स में इंडेंटेशन पूरी तरह सटीक न भी हो सकता है। इसी कारण, हम अनुशंसा करते हैं कि आप साथ चलते हुए इस प्रोजेक्ट के GitHub रिपो को अलग टैब में खोलें।
चरण 0: अपना Claude Sonnet 4 प्रोजेक्ट पर्यावरण सेट करें
कोई भी कोड लिखने से पहले, अपना डेवलपमेंट एन्वायरनमेंट और डिपेंडेंसीज़ सेट करें।
अपने प्रोजेक्ट के लिए एक नया डायरेक्टरी बनाएँ और आवश्यक फ़ाइलें सेट करें:
mkdir math-solver
cd math-solver
touch math_solver.py demo_problems.py requirements.txt README.md
requirements.txt फ़ाइल बनाएँ और आवश्यक डिपेंडेंसी जोड़ें:
anthropic>=0.42.0
डिपेंडेंसी इंस्टॉल करें:
pip install -r requirements.txt
अपनी Anthropic API कुंजी को environment variable के रूप में सेट करें:
export ANTHROPIC_API_KEY="your-api-key-here"
चरण 1: एप्लिकेशन संरचना डिज़ाइन करें
आइए अपनी MathSolver क्लास की बुनियादी संरचना बनाकर शुरू करें। यह क्लास मुख्य कार्यों को संभालेगी: API संचार, फ़ाइल प्रबंधन, और उपयोगकर्ता इंटरैक्शन।
सबसे पहले, इम्पोर्ट्स और बेसिक स्ट्रक्चर सेट करें:
#!/usr/bin/env python3
"""
Interactive Math Problem Solver using Claude 4 Code Execution Tool
This application allows users to ask math questions in natural language,
gets solutions using Claude's code execution capabilities, and saves
both visualizations and detailed markdown reports.
"""
import os
import json
import datetime
from pathlib import Path
from typing import List, Dict, Any
from anthropic import Anthropic
अब अपनी मुख्य क्लास संरचना परिभाषित करें:
class MathSolver:
def __init__(self, api_key: str = None):
"""Initialize the Math Solver with Anthropic client."""
# API setup and directory creation will go here
pass
def solve_problem(self, question: str) -> Dict[str, Any]:
"""Send a math question to Claude and get solution with code execution."""
pass
Here are the methods for file and report handling:
def extract_files_from_response(self, response) -> List[str]:
"""Extract file IDs from Claude's response."""
pass
def download_files(self, file_ids: List[str]) -> List[str]:
"""Download files created by code execution to local storage."""
pass
def extract_code_blocks(self, response) -> List[str]:
"""Extract all code blocks from the response."""
Pass
अंत में, सेशन प्रबंधन और एंट्री पॉइंट जोड़ें:
def generate_markdown_report(self, result: Dict[str, Any], downloaded_files: List[str]) -> str:
"""Generate a comprehensive markdown report of the solution."""
pass
def run_interactive_session(self):
"""Run the main interactive session loop."""
pass
def main():
"""Main entry point for the application."""
pass
यह संरचना हमें एक स्पष्ट रोडमैप देती है: इनिशियलाइज़ेशन, समस्या समाधान, फ़ाइल हैंडलिंग, रिपोर्ट जेनरेशन, और उपयोगकर्ता इंटरैक्शन। पाइपलाइन में हर मेथड की एक विशिष्ट ज़िम्मेदारी है।
Claude Sonnet 4 कोड निष्पादन के साथ एक Math Solver बनाना
अब, आइए Claude के कोड निष्पादन टूल और स्ट्रीमिंग प्रतिक्रियाओं का उपयोग करके मुख्य कार्यक्षमता लागू करें।
चरण 2: सुरक्षित API हेडर्स के साथ Claude को इनिशियलाइज़ करें
आइए __init__() मेथड लागू करें ताकि API क्लाइंट सेटअप और डायरेक्टरी क्रिएशन संभाला जा सके।
पहले, API कुंजी प्रबंधन संभालते हैं:
def __init__(self, api_key: str = None):
"""Initialize the Math Solver with Anthropic client."""
if not api_key:
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
raise ValueError(
"Please set ANTHROPIC_API_KEY environment variable or provide api_key"
)
इसके बाद, आवश्यक बीटा हेडर्स के साथ Anthropic क्लाइंट सेट करें:
# Initialize client with both code execution and files API headers
self.client = Anthropic(
api_key=api_key,
default_headers={
"anthropic-beta": "code-execution-2025-05-22,files-api-2025-04-14"
},
)
अंत में, आउटपुट डायरेक्टरी संरचना बनाएँ:
# Create organized output directories
self.output_dir = Path("math_solver_output")
self.images_dir = self.output_dir / "images"
self.reports_dir = self.output_dir / "reports"
self.output_dir.mkdir(exist_ok=True)
self.images_dir.mkdir(exist_ok=True)
self.reports_dir.mkdir(exist_ok=True)
print(f"📁 Output directories created:")
print(f" • Images: {self.images_dir}")
print(f" • Reports: {self.reports_dir}")
यह इनिशियलाइज़ेशन तीन महत्वपूर्ण काम करता है:
- API कुंजी प्रबंधन: पहले environment variables में कुंजी जाँचता है, फिर पैरामीटर पर फ़ॉलबैक करता है।
- क्लाइंट सेटअप: कोड निष्पादन और Files API दोनों के लिए बीटा हेडर्स के साथ Anthropic क्लाइंट बनाता है।
- डायरेक्टरी संरचना: इमेज और रिपोर्ट्स सहेजने के लिए व्यवस्थित फ़ोल्डर बनाता है।
चरण 3: कोर सॉल्वर फ़ंक्शन लिखें
solve_problem() मेथड हमारे एप्लिकेशन का हृदय है। यह स्ट्रीमिंग सपोर्ट के साथ Claude को रिक्वेस्ट भेजता है।
फ़ंक्शन सिग्नेचर और प्रारंभिक सेटअप से शुरू करते हैं:
def solve_problem(self, question: str) -> Dict[str, Any]:
"""
Send a math question to Claude and get solution with code execution.
"""
print(f"\n🤔 Thinking about: {question}")
try:
# Use streaming to show real-time progress
with self.client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=4096,
Now we configure the message and tool specification:
messages=[
{
"role": "user",
"content": f"""Solve this math problem using code execution:
Problem: {question}
Please:
1. Solve the problem with actual Python code
2. Create visualizations using matplotlib if helpful
3. Save any plots as PNG files using plt.savefig()
4. Show your calculations step by step
5. Use descriptive filenames for saved plots
Execute Python code to solve this problem.""",
}
],
tools=[{"type": "code_execution_20250522", "name": "code_execution"}],
) as stream:
The streaming event processing handles real-time updates:
print("\n💭 Claude is working...")
# Process streaming events and show progress
for event in stream:
if event.type == "content_block_start":
if hasattr(event.content_block, "type"):
if event.content_block.type == "text":
print("\n📝 Response:", end=" ", flush=True)
elif event.content_block.type == "server_tool_use":
print(f"\n🔧 Using tool: {event.content_block.name}")
हम विभिन्न प्रकार के स्ट्रीमिंग ईवेंट्स को संभालते हैं:
elif event.type == "content_block_delta":
if hasattr(event.delta, "text"):
print(event.delta.text, end="", flush=True)
elif event.type == "content_block_stop":
print("", flush=True) # New line
elif event.type == "message_delta":
if hasattr(event.delta, "stop_reason"):
print(f"\n✅ Completed: {event.delta.stop_reason}")
अंत में, हम परिणाम लौटाते हैं या त्रुटियों को संभालते हैं:
# Get the final message
final_message = stream.get_final_message()
return {
"response": final_message,
"question": question,
"timestamp": datetime.datetime.now().isoformat(),
}
except Exception as e:
print(f"❌ Error solving problem: {e}")
return None
यह फ़ंक्शन कई महत्वपूर्ण अवधारणाओं को दर्शाता है:
- स्ट्रीमिंग सपोर्ट: हम
client.messages.stream()का उपयोग करते हैं,client.messages.create()के बजाय, ताकि Claude के काम करते समय वास्तविक-समय फीडबैक मिले। - ईवेंट हैंडलिंग: स्ट्रीमिंग API अलग-अलग प्रकार के ईवेंट भेजता है:
content_block_start: जब Claude टेक्स्ट लिखना शुरू करता है या कोई टूल उपयोग करता हैcontent_block_delta: जब कंटेंट जनरेट हो रहा होता हैcontent_block_stop: जब कोई कंटेंट ब्लॉक पूरा हो जाता हैmessage_delta: जब पूरा संदेश तैयार हो जाता है- टूल स्पेसिफिकेशन: हम
toolsऐरे में कोड निष्पादन टूल को सटीक टाइप"code_execution_20250522"के साथ शामिल करते हैं। - संरचित प्रॉम्प्टिंग: हमारा प्रॉम्प्ट स्पष्ट रूप से Claude को कोड निष्पादन का उपयोग करने और किसी भी विज़ुअलाइज़ेशन को सहेजने के लिए निर्देश देता है।
चरण 4: स्ट्रीमिंग कोड निष्पादन के साथ गणित समस्याएँ हल करें
जब Claude कोड निष्पादन के दौरान फ़ाइलें बनाता है (जैसे matplotlib प्लॉट्स), हमें उनके फ़ाइल IDs निकालकर उन्हें लोकल डाउनलोड करना होगा।
फ़ाइल एक्सट्रैक्शन मेथड प्रतिक्रिया संरचना के माध्यम से नेविगेट करता है:
def extract_files_from_response(self, response) -> List[str]:
"""Extract file IDs from Claude's response."""
file_ids = []
for item in response.content:
if item.type == "code_execution_tool_result":
content_item = item.content
if isinstance(content_item, dict):
if content_item.get("type") == "code_execution_result":
content_list = content_item.get("content", [])
फिर हम कंटेंट में फ़ाइल IDs खोजते हैं:
for file_item in content_list:
if isinstance(file_item, dict) and "file_id" in file_item:
file_ids.append(file_item["file_id"])
return file_ids
डाउनलोड प्रक्रिया फ़ाइलें प्राप्त करती है और उन्हें लोकल रूप से सहेजती है:
def download_files(self, file_ids: List[str]) -> List[str]:
"""Download files created by code execution to local storage."""
downloaded_files = []
for file_id in file_ids:
try:
# Get file metadata and download content
file_metadata = self.client.beta.files.retrieve_metadata(file_id)
filename = file_metadata.filename
file_content = self.client.beta.files.download(file_id)
local_path = self.images_dir / filename
file_content.write_to_file(str(local_path))
हम डाउनलोड की गई फ़ाइलों को ट्रैक करते हैं और त्रुटियों को संभालते हैं:
downloaded_files.append(str(local_path))
print(f"✅ Downloaded: {filename}")
except Exception as e:
print(f"❌ Error downloading file {file_id}: {e}")
return downloaded_files
- फ़ाइल एक्सट्रैक्शन लॉजिक:
extract_files_from_response()मेथड प्रतिक्रिया संरचना में नेविगेट करके फ़ाइल IDs ढूंढता है। कोड निष्पादन परिणाम एक विशेष फ़ॉर्मैट में नेस्टेड होते हैं जहाँ फ़ाइलेंcontentऐरे में दिखाई देती हैं। - फ़ाइल डाउनलोड प्रक्रिया:
download_files()मेथड: - हर फ़ाइल का मेटाडेटा (मूल फ़ाइलनाम सहित) प्राप्त करता है
- Files API का उपयोग करके फ़ाइल कंटेंट डाउनलोड करता है
- फ़ाइलों को हमारी व्यवस्थित डायरेक्टरी संरचना में सहेजता है
- बाद में उपयोग के लिए लोकल फ़ाइल पथों की सूची लौटाता है
Claude Sonnet 4 से परिणाम निकालना: कोड, विज़ुअल, और रिपोर्ट्स
अब, आइए Claude द्वारा जनरेट किए गए कोड और आउटपुट को पुन: उपयोग करें और जाँचें।
चरण 5: Claude की प्रतिक्रियाओं से विज़ुअल आउटपुट डाउनलोड करें
अपनी मार्कडाउन रिपोर्ट्स के लिए, हम वह वास्तविक Python कोड शामिल करना चाहते हैं जिसे Claude ने निष्पादित किया:
def extract_code_blocks(self, response) -> List[str]:
"""Extract all code blocks from the response."""
code_blocks = []
for item in response.content:
if item.type == "server_tool_use" and item.name == "code_execution":
if (
hasattr(item, "input")
and isinstance(item.input, dict)
and "code" in item.input
):
code_blocks.append(item.input["code"])
return code_blocks
यह मेथड server_tool_use आइटम्स को ढूँढता है जिनका नाम "code_execution" होता है और input फ़ील्ड से Python कोड निकालता है। इससे हमें वही वास्तविक कोड मिलता है जो Claude ने लिखा और चलाया।
चरण 6: पुन: उपयोग और ऑडिटिंग के लिए Claude का कोड निकालें
हमारा रिपोर्ट जेनरेटर हर समाधान का व्यापक प्रलेखन बनाता है।
पहले, हम कंटेंट निकालते हैं और रिपोर्ट संरचना सेट करते हैं:
def generate_markdown_report(self, result: Dict[str, Any], downloaded_files: List[str]) -> str:
"""Generate a comprehensive markdown report of the solution."""
response = result["response"]
question = result["question"]
timestamp = result["timestamp"]
# Extract text content and code blocks
text_content = []
code_blocks = self.extract_code_blocks(response)
for item in response.content:
if item.type == "text":
text_content.append(item.text)
इसके बाद, हम टाइमस्टैम्प के साथ एक सुरक्षित फ़ाइलनाम जनरेट करते हैं:
# Generate filename with timestamp
safe_question = "".join(
c for c in question[:50] if c.isalnum() or c in (" ", "-", "_")
).strip()
filename = f"{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{safe_question.replace(' ', '_')}.md"
filepath = self.reports_dir / filename
हम हैडर और समस्या विवरण के साथ मार्कडाउन कंटेंट बनाते हैं:
# Create markdown content
markdown_content = f"""# Math Problem Solution Report
**Generated:** {timestamp}
**Question:** {question}
---
## Problem Statement
{question}
---
## Solution
"""
Add the solution explanation and code blocks:
# Add the main explanation
for text in text_content:
markdown_content += f"{text}\n\n"
# Add code sections
if code_blocks:
markdown_content += "---\n\n## Code Used\n\n"
for i, code in enumerate(code_blocks, 1):
markdown_content += f"### Code Block {i}\n\n```python\n{code}\n```\n\n"
किसी भी जनरेटेड विज़ुअलाइज़ेशन को शामिल करें:
# Add images section
if downloaded_files:
markdown_content += "---\n\n## Generated Visualizations\n\n"
for file_path in downloaded_files:
filename = Path(file_path).name
relative_path = f"../images/{filename}"
markdown_content += f"\n\n"
Finally, add metadata and save the report:
# Add footer
markdown_content += f"""---
## Report Details
- **Generated by:** Claude 4 Math Solver
- **Model:** claude-sonnet-4-20250514
- **Timestamp:** {timestamp}
- **Files created:** {len(downloaded_files)} visualization(s)
---
*This report was automatically generated using Claude's code execution capabilities.*
"""
# Save the report
with open(filepath, "w", encoding="utf-8") as f:
f.write(markdown_content)
return str(filepath)
यह रिपोर्ट जेनरेटर एक संरचित मार्कडाउन दस्तावेज़ बनाता है, जिसमें शामिल हैं:
- समस्या विवरण और मेटाडेटा
- Claude की टेक्स्ट प्रतिक्रियाओं से समाधान व्याख्या
- वह कोड ब्लॉक जो वास्तविक Python कोड दिखाते हैं जिसे निष्पादित किया गया
- रिलेटिव पाथ्स के साथ एंबेडेड विज़ुअलाइज़ेशन
- ट्रैकिंग और संदर्भ के लिए रिपोर्ट मेटाडेटा
फ़ाइलनाम जेनरेशन सुरक्षित, टाइमस्टैम्प्ड फ़ाइलनाम बनाता है जो मौजूदा फ़ाइलों से टकराएँगे नहीं।
Math Solver को इंटरैक्टिव रूप से चलाना
अगला, आइए उपयोगकर्ता इंटरैक्शन लूप, डेमो टूल्स और टेस्टिंग पर ध्यान दें।
चरण 7: इंटरैक्टिव सेशन प्रबंधित करें
इंटरैक्टिव सेशन लूप उपयोगकर्ता इनपुट संभालता है और हमारे सभी घटकों का समन्वय करता है।
हम सेशन सेटअप और वेलकम संदेश से शुरू करते हैं:
def run_interactive_session(self):
"""Run the main interactive session loop."""
print("🧮 Interactive Math Problem Solver with Claude 4")
print("=" * 60)
print("Ask me any math question and I'll solve it step by step!")
print("I can handle algebra, calculus, statistics, geometry, and more.")
print("Type 'quit', 'exit', or 'q' to end the session.")
print("=" * 60)
session_count = 0
मुख्य लूप उपयोगकर्ता इनपुट और एग्ज़िट कंडीशन्स संभालता है:
while True:
try:
# Get user input
question = input(f"\n📝 Question #{session_count + 1}: ").strip()
if question.lower() in ["quit", "exit", "q"]:
print("\n👋 Thanks for using the Math Solver! Goodbye!")
break
if not question:
print("Please enter a question.")
continue
session_count += 1
प्रत्येक मान्य प्रश्न के लिए, हम पूर्ण वर्कफ़्लो प्रोसेस करते हैं:
# Solve the problem
result = self.solve_problem(question)
if not result:
continue
# Extract and download any files created
file_ids = self.extract_files_from_response(result["response"])
downloaded_files = []
if file_ids:
print(f"📥 Downloading {len(file_ids)} file(s)...")
downloaded_files = self.download_files(file_ids)
हम रिपोर्ट जेनरेशन और उपयोगकर्ता फीडबैक के साथ समाप्त करते हैं:
# Generate markdown report
print(f"📝 Generating report...")
report_path = self.generate_markdown_report(result, downloaded_files)
print(f"\n✅ Solution complete!")
print(f"📄 Report saved: {report_path}")
if downloaded_files:
print(f"🖼️ Visualizations: {len(downloaded_files)} file(s) saved")
except KeyboardInterrupt:
print("\n\n👋 Session interrupted. Goodbye!")
break
except Exception as e:
print(f"❌ An error occurred: {e}")
print("Please try again with a different question.")
यह लूप एक पूर्ण वर्कफ़्लो दर्शाता है:
- उपयोगकर्ता इंटरैक्शन: प्रश्नों के लिए प्रॉम्प्ट और एग्ज़िट कमांड्स को संभालना
- समस्या समाधान: हमारे
solve_problem()मेथड को कॉल करना - फ़ाइल प्रोसेसिंग: किसी भी जनरेट की गई फ़ाइलों को निकालना और डाउनलोड करना
- रिपोर्ट जेनरेशन: एक व्यापक मार्कडाउन रिपोर्ट बनाना
- त्रुटि हैंडलिंग: इंटरप्शन और त्रुटियों को शालीनता से संभालना
चरण 8: एप्लिकेशन एंट्री पॉइंट लिखें
अंततः, हमें अपना एप्लिकेशन इनिशियलाइज़ और शुरू करने के लिए एक main() फ़ंक्शन चाहिए:
def main():
"""Main entry point for the application."""
try:
solver = MathSolver()
solver.run_interactive_session()
except Exception as e:
print(f"❌ Failed to initialize Math Solver: {e}")
print("Make sure you have set the ANTHROPIC_API_KEY environment variable.")
return 1
return 0
if __name__ == "__main__":
exit(main())
यह सरल एंट्री पॉइंट इनिशियलाइज़ेशन त्रुटियों (जैसे गायब API कुंजी) को संभालता है और सहायक त्रुटि संदेश प्रदान करता है।
चरण 9: एक डेमो समस्या जेनरेटर जोड़ें
उपयोगकर्ताओं को शुरुआत करने में मदद करने के लिए, आइए उदाहरण समस्याओं के साथ एक अलग स्क्रिप्ट बनाते हैं। demo_problems.py बनाएँ।
सबसे पहले, हम अपनी समस्या श्रेणियाँ परिभाषित करते हैं:
# demo_problems.py
#!/usr/bin/env python3
"""
Demo problems for the Interactive Math Problem Solver
"""
# Sample problems organized by difficulty and topic
DEMO_PROBLEMS = {
"Beginner": [
"What is 15% of 240?",
"Solve for x: 3x + 7 = 22",
"Find the area of a circle with radius 5",
"Convert 45 degrees to radians",
"Calculate the hypotenuse of a right triangle with legs 3 and 4",
],
इंटरमीडिएट और एडवांस्ड समस्या सेट जोड़ें:
"Intermediate": [
"Solve the quadratic equation: 2x^2 + 5x - 3 = 0",
"Graph y = x^2 - 4x + 3 and find its vertex",
"Calculate mean, median, and standard deviation of [12, 15, 18, 22, 25, 28]",
"Find where f(x) = x^3 - 3x^2 + 2 crosses the x-axis",
"Solve the system of equations: 2x + 3y = 7, x - y = 1",
],
"Advanced": [
"Find the derivative of sin(x) * e^x and plot both functions",
"Calculate the integral of x^2 from 0 to 5",
"Use Newton's method to find the root of x^3 - 2x - 5 = 0",
"Perform linear regression on data points and plot the results",
"Solve the differential equation dy/dx = x*y with initial condition y(0) = 1",
],
}
रैंडम चयन और डिस्प्ले के लिए हेल्पर फ़ंक्शंस बनाएँ:
def get_random_problem(category=None):
"""Get a random problem from a specific category or all categories."""
import random
if category and category in DEMO_PROBLEMS:
return random.choice(DEMO_PROBLEMS[category])
else:
# Pick from all problems
all_problems = []
for problems in DEMO_PROBLEMS.values():
all_problems.extend(problems)
return random.choice(all_problems)
सभी उपलब्ध समस्याएँ दिखाने के लिए एक फ़ंक्शन जोड़ें:
def print_demo_problems():
"""Print all demo problems organized by category."""
print("🧮 Demo Problems for Interactive Math Solver")
print("=" * 60)
print("Here are example problems you can try, organized by difficulty:\n")
for category, problems in DEMO_PROBLEMS.items():
print(f"### {category}")
print("-" * (len(category) + 4))
for i, problem in enumerate(problems, 1):
print(f"{i:2d}. {problem}")
print()
print("💡 Tips:")
print(" • Copy and paste any question into the math solver")
print(" • All visualizations and reports will be saved automatically")
print("\n🚀 Start the solver with: python math_solver.py")
if __name__ == "__main__":
print_demo_problems()
यह डेमो स्क्रिप्ट प्रदान करती है:
- श्रेणीबद्ध समस्याएँ—बिगिनर से एडवांस्ड तक
- रैंडम समस्या चयन—टेस्टिंग के लिए
- उपयोग दिशानिर्देश—नए उपयोगकर्ताओं के लिए
चरण 10: एप्लिकेशन चलाएँ और टेस्ट करें
अब आइए अपने पूर्ण एप्लिकेशन का परीक्षण करें! मैथ सॉल्वर चलाएँ:
python math_solver.py
कुछ उदाहरण प्रश्न आज़माएँ:
- बेसिक कैलकुलेशन: “What is 15% of 240?”
- बीजगणित: “Solve for x: 3x + 7 = 22”
- विज़ुअलाइज़ेशन: “Graph y = x² — 4x + 3 and find its vertex”
- एडवांस्ड गणित: “Find the derivative of sin(x) * e^x and plot both functions”
हर प्रश्न:
- जैसे-जैसे Claude काम करता है, वास्तविक-समय स्ट्रीमिंग आउटपुट दिखाएगा
- जरूरी विज़ुअलाइज़ेशन जनरेट करेगा
- एक व्यापक मार्कडाउन रिपोर्ट सहेजेगा
- आपकी images डायरेक्टरी में प्लॉट फ़ाइलें डाउनलोड करेगा
आप सभी उपलब्ध उदाहरण देखने के लिए डेमो समस्याएँ स्क्रिप्ट भी चला सकते हैं:
python demo_problems.py
हमने Claude Sonnet 4 के साथ क्या बनाया है
हमारा मैथ प्रॉब्लम सॉल्वर Claude 4 और नए API की कई शक्तिशाली विशेषताएँ दर्शाता है:
- कोड निष्पादन: Claude गणितीय समस्याएँ हल करने, समाधानों पर पुनरावृत्ति करने और जटिल गणनाएँ संभालने के लिए Python कोड लिख और चला सकता है।
- फ़ाइल जेनरेशन और प्रबंधन: एप्लिकेशन Files API का उपयोग करके फ़ाइल निर्माण, डाउनलोड और संगठन को स्वचालित रूप से संभालता है।
- स्ट्रीमिंग इंटरैक्शन: वास्तविक-समय फीडबैक अनुभव को अधिक उत्तरदायी और आकर्षक बनाता है।
- व्यापक प्रलेखन: हर समाधान विस्तृत मार्कडाउन रिपोर्ट्स में कोड और विज़ुअलाइज़ेशन सहित संरक्षित रहता है।
- उपयोगकर्ता-अनुकूल इंटरफ़ेस: टर्मिनल-आधारित इंटरफ़ेस गणितीय समस्या समाधान के लिए सरल लेकिन प्रभावी है।
यह प्रोजेक्ट दिखाता है कि Claude 4 की नई क्षमताओं को एक साथ मिलाकर कैसे साधारण चैट इंटरैक्शन से परे उन्नत एप्लिकेशन बनाए जा सकते हैं। कोड निष्पादन टूल, उचित फ़ाइल हैंडलिंग और स्ट्रीमिंग के साथ मिलकर, गणितीय अन्वेषण और विश्लेषण के लिए एक शक्तिशाली प्लेटफ़ॉर्म बनाता है।
आप Developing AI Systems with the OpenAI API कोर्स करके अन्य प्लेटफ़ॉर्म्स का उपयोग कर समान एजेंट बनाना भी सीख सकते हैं।
निष्कर्ष और आगे के कदम
इस मैथ प्रॉब्लम सॉल्वर को बनाकर यह प्रदर्शित हुआ कि Claude 4 की नई क्षमताएँ AI एप्लिकेशनों के साथ क्या-क्या संभव बनाती हैं।
हमारा एप्लिकेशन बेसिक कैलकुलेशन्स से लेकर जटिल गणितीय विज़ुअलाइज़ेशन तक सबकुछ संभालता है, यह दिखाते हुए कि ये API फीचर्स मिलकर कैसे बेहतरीन उपयोगकर्ता अनुभव बनाते हैं। विशेष रूप से, कोड निष्पादन टूल एक गेम-चेंजर साबित होता है, जो Claude को समाधानों पर पुनरावृत्ति करने और ऐसे विज़ुअल आउटपुट जनरेट करने देता है जिनके लिए पहले अलग टूल्स और जटिल इंटीग्रेशन की ज़रूरत पड़ती।
यहाँ से, आप इस मैथ सॉल्वर को वेब इंटरफेस के साथ बढ़ा सकते हैं, MCPs के माध्यम से बाहरी डेटा स्रोतों के साथ इंटीग्रेट कर सकते हैं, या समान पैटर्न्स को अन्य क्षेत्रों—जैसे डेटा विश्लेषण, वैज्ञानिक कंप्यूटिंग, या शैक्षिक टूल्स—में डोमेन-विशिष्ट असिस्टेंट बनाने के लिए लागू कर सकते हैं।
- यदि आप एक डेवलपर हैं जो अपनी AI इंजीनियरिंग कौशल को प्रमाणित करना चाहते हैं, तो consider डेवलपर्स के लिए Associate AI Engineer ट्रैक पर विचार करें, जो ऐसे ही प्रोडक्शन-लेवल इम्प्लीमेंटेशन्स पर ज़ोर देता है।
- LLMs को ऑपरेशनलाइज़ करने में रुचि रखने वाले डेटा वैज्ञानिक डेटा साइंटिस्ट्स के लिए Associate AI Engineer ट्रैक फॉलो कर सकते हैं, जो विश्लेषण और AI डिप्लॉयमेंट के बीच सेतु बनाता है।
FAQs
Claude 4 को पिछले संस्करणों से अलग क्या बनाता है?
Claude 4 नैटिव कोड निष्पादन, टूल उपयोग के साथ विस्तारित सोच, समानांतर टूल निष्पादन, बेहतर मेमोरी क्षमताएँ, और कई घंटों के सतत टास्क निष्पादन का समर्थन प्रस्तुत करता है। ये फीचर्स इसे सॉफ्टवेयर इंजीनियरिंग कार्यों में विशेष रूप से मजबूत बनाते हैं।
क्या Claude 4 बातचीत के दौरान वास्तव में Python कोड चला सकता है?
हाँ, Claude 4 नए कोड निष्पादन टूल का उपयोग करके एक सुरक्षित सैंडबॉक्स में Python कोड चला सकता है। यह गणनाएँ कर सकता है, matplotlib के साथ विज़ुअलाइज़ेशन जनरेट कर सकता है, और निष्पादन परिणामों के आधार पर समाधानों पर पुनरावृत्ति कर सकता है।
Claude के कोड निष्पादन परिवेश की सीमाएँ क्या हैं?
सैंडबॉक्स में इंटरनेट एक्सेस नहीं है, सीमित कंप्यूट संसाधन हैं, और यह आपके लोकल फ़ाइल सिस्टम तक पहुँच नहीं कर सकता। इसमें numpy, pandas, और matplotlib जैसी लोकप्रिय लाइब्रेरीज़ पहले से इंस्टॉल हैं, लेकिन आप अतिरिक्त पैकेज इंस्टॉल नहीं कर सकते।
कोड निष्पादन के साथ नया Files API कैसे काम करता है?
Files API आपको दस्तावेज़ एक बार अपलोड करने और उन्हें वार्तालापों में संदर्भित करने देता है। जब Claude कोड निष्पादन के दौरान फ़ाइलें बनाता है (जैसे प्लॉट्स), तो आप उनके फ़ाइल IDs निकालकर API का उपयोग करके उन्हें लोकल डाउनलोड कर सकते हैं।
क्या Claude 4 की कोड निष्पादन क्षमताओं के लिए विशेष API एक्सेस चाहिए?
आपको अपनी API रिक्वेस्ट्स में बीटा हेडर "anthropic-beta": "code-execution-2025-05-22" शामिल करना होगा और claude-sonnet-4-20250514 मॉडल का उपयोग करना होगा। कोड निष्पादन टूल को आपके tools ऐरे में "code_execution_20250522" के रूप में निर्दिष्ट किया जाता है।
मैं 2 से अधिक वर्षों के अनुभव वाला डेटा साइंस कंटेंट क्रिएटर हूँ और Medium पर सबसे बड़े फॉलोइंग्स में से एक रखता हूँ। मुझे एआई और एमएल पर विस्तार से लेख लिखना पसंद है, जिसमें हल्का-सा व्यंग्यात्मक अंदाज रहता है—क्योंकि कुछ तो करना पड़ता है ताकि वे कम उबाऊ लगें। मैंने 130 से अधिक लेख और एक DataCamp कोर्स तैयार किया है, और एक और बन रहा है। मेरा कंटेंट 50 लाख से अधिक लोगों ने देखा है, जिनमें से 20 हज़ार लोग Medium और LinkedIn पर फॉलोअर्स बन गए।
