पाठ 3 / 27
कच्ची HTTP Call: SDK आपके लिए क्या करता है
समझने को एक बार request हाथ से बनाएँ।
यह सिर्फ़ HTTP और JSON है
कोई भी भाषा जो HTTPS भेज और JSON parse कर सके, इन APIs को बुला सकती है। एक बार हाथ से करना रहस्य हटा देता है: JSON body बनाएँ, headers जोड़ें (API key header, content type, और Anthropic के लिए anthropic-version header), POST भेजें, status code जाँचें और JSON parse करें। SDKs ऊपर से असली मूल्य जोड़ते हैं: typed request और response ऑब्जेक्ट्स, स्वचालित backoff के साथ retries, timeouts, streaming सहायक, error classes और pagination। Applications में SDK उपयोग करें; debugging, असामान्य भाषाओं या सटीक नियंत्रण चाहिए तब कच्चा HTTP।
urllib से कच्ची call, चलाकर
मैंने यह Python virtual environment में anthropic 1.11.0 और openai 3.22.1 SDKs के साथ छोटे स्थानीय stand-in server (testing विषय में दिखाया, mock.py नाम से सहेजा) के विरुद्ध चलाया। Server तैयार उत्तर लौटाता है, इसलिए कोई key, network या असली मॉडल शामिल नहीं: यह साबित करता है कि SDK requests कैसे बनाता और उत्तर कैसे सँभालता है, यह नहीं कि असली मॉडल क्या कहता। कोड सिर्फ़ urllib से Messages-शैली का अनुरोध स्थानीय stand-in server को भेजता है। वह status, पाठ, usage और server को वास्तव में क्या मिला (key header और तीन आवश्यक body fields) छापता है।
import json, urllib.request, mock
srv = mock.start(); base = f"http://127.0.0.1:{srv.server_address[1]}"
req = urllib.request.Request(base + "/v1/messages", method="POST",
data=json.dumps({"model": "demo-model", "max_tokens": 100,
"messages": [{"role": "user", "content": "Capital of France?"}]}).encode(),
headers={"x-api-key": "sk-test-123", "anthropic-version": "2023-06-01", "content-type": "application/json"})
with urllib.request.urlopen(req) as r:
reply = json.load(r)
print("status OK, stop_reason:", reply["stop_reason"])
print("text:", reply["content"][0]["text"])
print("usage:", reply["usage"])
seen = mock.STATE["log"][-1]
print("server saw header x-api-key:", seen["headers"]["x-api-key"])
print("server saw body keys:", sorted(seen["body"]))
Output:
status OK, stop_reason: end_turn
text: Paris is the capital of France.
usage: {'input_tokens': 14, 'output_tokens': 8}
server saw header x-api-key: sk-test-123
server saw body keys: ['max_tokens', 'messages', 'model']त्वरित जाँच: कच्चे HTTP के ऊपर SDKs क्या जोड़ते हैं?
- key की ज़रूरत नहीं
- अलग मॉडल
- मुफ़्त tokens
- Typed objects, retries, timeouts और streaming सहायक
Answer
Typed objects, retries, timeouts और streaming सहायक — SDKs उसी HTTP API को सुविधा और भरोसेमंदी सुविधाओं के साथ लपेटते हैं।