fromslm_builderimportSLMBuilderbuilder=SLMBuilder(project_name="api-qa",base_model="google/flan-t5-small")# Load from public API
builder.load_from_api(endpoint="https://api.example.com/qa-data",method="GET")builder.train(epochs=3,method="lora")
Authenticated API
Load data from an API that requires authentication.
Bearer Token
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fromslm_builderimportSLMBuilderbuilder=SLMBuilder(project_name="auth-api",base_model="google/flan-t5-small")# API with Bearer token
builder.load_from_api(endpoint="https://api.example.com/training-data",headers={"Authorization":"Bearer YOUR_ACCESS_TOKEN","Content-Type":"application/json"})builder.train(epochs=3,method="lora")
API Key
1
2
3
4
5
6
7
# API with API key
builder.load_from_api(endpoint="https://api.example.com/data",headers={"X-API-Key":"your-api-key-here"})
Basic Auth
1
2
3
4
5
6
7
8
importrequestsfromrequests.authimportHTTPBasicAuth# API with basic authentication
builder.load_from_api(endpoint="https://api.example.com/data",auth=HTTPBasicAuth("username","password"))
fromslm_builderimportSLMBuilderbuilder=SLMBuilder(project_name="paginated-api")page=0page_size=100total_loaded=0whileTrue:response=builder.load_from_api(endpoint=f"https://api.example.com/data?page={page}&size={page_size}",headers={"Authorization":"Bearer TOKEN"},append=True# Append to existing data
)iflen(response)==0:breaktotal_loaded+=len(response)page+=1print(f"Loaded {total_loaded} samples...")print(f"✅ Total samples loaded: {total_loaded}")builder.train(epochs=3,method="lora")
cursor=Nonetotal_loaded=0whileTrue:url=f"https://api.example.com/data"ifcursor:url+=f"?cursor={cursor}"response=builder.load_from_api(endpoint=url,headers={"Authorization":"Bearer TOKEN"},append=True)# Extract next cursor from response
cursor=response.get('metadata',{}).get('next_cursor')ifnotcursor:breaktotal_loaded+=len(response.get('data',[]))print(f"Loaded {total_loaded} samples...")
fromslm_builderimportSLMBuilderimportjsonbuilder=SLMBuilder(project_name="post-api")# POST request with JSON payload
payload={"query":{"category":"technology","verified":True},"limit":5000}builder.load_from_api(endpoint="https://api.example.com/query",method="POST",headers={"Authorization":"Bearer TOKEN","Content-Type":"application/json"},data=json.dumps(payload))builder.train(epochs=3,method="lora")
fromflaskimportFlask,requestfromslm_builderimportSLMBuilderimportjsonapp=Flask(__name__)builder=SLMBuilder(project_name="webhook-training",base_model="google/flan-t5-small")@app.route('/webhook',methods=['POST'])defhandle_webhook():"""Receive and process webhook data."""data=request.json# Extract QA pairs from webhook
qa_pairs=[]foritemindata.get('items',[]):qa_pairs.append({'question':item['question'],'answer':item['answer']})# Add to training data
builder.add_training_samples(qa_pairs)# Trigger training if threshold reached
ifbuilder.dataset_size>=1000:builder.train(epochs=2,method="lora")builder.save_model("./webhook-model")builder.clear_dataset()# Reset for next batch
return{"status":"success","samples_added":len(qa_pairs)}if__name__=='__main__':app.run(port=5000)
fromslm_builderimportSLMBuilderbuilder=SLMBuilder(project_name="multi-api",base_model="google/flan-t5-base")# API 1: Internal knowledge base
builder.load_from_api(endpoint="https://internal-api.company.com/kb",headers={"Authorization":"Bearer INTERNAL_TOKEN"})# API 2: External data provider
builder.load_from_api(endpoint="https://external-api.com/qa-data",headers={"X-API-Key":"EXTERNAL_KEY"},append=True)# API 3: Third-party service
builder.load_from_api(endpoint="https://service.com/training-data",auth=("username","password"),append=True)print(f"Total samples from all APIs: {builder.dataset_size}")builder.train(epochs=5,method="lora")
fromslm_builderimportSLMBuilderimportrequestsimportjsonbuilder=SLMBuilder(project_name="streaming-api")url="https://api.example.com/stream"headers={"Authorization":"Bearer TOKEN"}# Stream large datasets
withrequests.get(url,headers=headers,stream=True)asresponse:response.raise_for_status()batch=[]batch_size=100forlineinresponse.iter_lines():ifline:item=json.loads(line)batch.append({'question':item['question'],'answer':item['answer']})# Process in batches
iflen(batch)>=batch_size:builder.add_training_samples(batch)batch=[]print(f"Processed {builder.dataset_size} samples...")# Add remaining samples
ifbatch:builder.add_training_samples(batch)print(f"✅ Total samples: {builder.dataset_size}")builder.train(epochs=3,method="lora")
fromslm_builderimportSLMBuilderimportrequestsimportjsonimporthashlibfrompathlibimportPathdefload_with_cache(endpoint,headers,cache_dir="./api_cache"):"""Load from API with disk caching."""# Create cache key
cache_key=hashlib.md5(f"{endpoint}{json.dumps(headers)}".encode()).hexdigest()cache_file=Path(cache_dir)/f"{cache_key}.json"cache_file.parent.mkdir(exist_ok=True)# Check cache
ifcache_file.exists():print("✅ Loading from cache...")withopen(cache_file)asf:returnjson.load(f)# Fetch from API
print("📡 Fetching from API...")response=requests.get(endpoint,headers=headers)response.raise_for_status()data=response.json()# Save to cache
withopen(cache_file,'w')asf:json.dump(data,f)returndata# Usage
builder=SLMBuilder(project_name="cached-api")data=load_with_cache(endpoint="https://api.example.com/training-data",headers={"Authorization":"Bearer TOKEN"})builder.load_data(data)builder.train(epochs=3,method="lora")