MBE SDK Guide

Python and JavaScript SDK usage guide with complete code examples.


Table of Contents


1. Installation

Python

pip install mbe-sdk
# or
pip install httpx  # Direct HTTP client

JavaScript/TypeScript

npm install mbe-sdk
# or
npm install axios  # Direct HTTP client

2. Python SDK

2.1 Quick Start

from mbe_sdk import MBEClient

client = MBEClient(
    api_key="YOUR_API_KEY",
    base_url="https://mbe.hi-maker.com",  # Optional, defaults to production
)

# Ask an expert
response = client.chat.ask(
    query="What are the legal consequences of breach of contract?",
)
print(response.answer)
print(response.sources)

2.2 Expert Management

# Create an expert
expert = client.experts.create(
    name="Legal Advisor",
    description="Specializing in civil and commercial law",
    definition_prompt="You are an experienced legal advisor...",
    industry="legal",
    self_critique_modules=["SC-1", "SC-2", "SC-3", "SC-6", "SC-12", "SC-13"],
)

# Upload knowledge base
client.knowledge_base.upload(
    expert_id=expert.id,
    file_path="./contract_law.pdf",
    metadata={"source": "Contract Law", "version": "2024"},
)

# Run evaluation gate
gate_result = client.evaluation.gate(expert_id=expert.id)
print(f"Gate: {gate_result.result}")  # PASS or FAIL
print(f"Can publish: {gate_result.can_publish}")

# Publish expert
if gate_result.can_publish:
    client.experts.publish(expert_id=expert.id)

2.3 Evaluation & Benchmark

# Get Net Score
net_score = client.evaluation.net_score(expert_id="exp_abc123")
print(f"Net Score: {net_score.score}")       # 0.82
print(f"Calibration: {net_score.calibration}")  # 0.50

# Run 6D Benchmark
benchmark = client.benchmark.run(
    expert_id="exp_abc123",
    dimensions=["accuracy", "hallucination", "safety", "citation", "quality", "consistency"],
    num_trials=3,
)
for dim in benchmark.dimensions:
    print(f"{dim.name}: {dim.score:.2f} ± {dim.ci:.2f}")

# Run multi-turn safety test
safety = client.evaluation.multi_turn_safety(
    expert_id="exp_abc123",
    industry_filter="legal",
    randomization_runs=3,
)
print(f"Safety rate: {safety.overall_safety_rate:.1%}")

2.4 Behavioral Audit

# Audit a conversation
audit = client.audit.conversation(
    expert_id="exp_abc123",
    conversation=[
        {"role": "user", "content": "How to handle contract disputes?"},
        {"role": "assistant", "content": "Contract disputes can be resolved through..."},
    ],
    industry="legal",
)
print(f"Verdict: {audit.verdict}")    # PASS, WARNING, FAIL, QUARANTINE
print(f"Scores: {audit.scores}")

# Generate audit report
report = client.audit.report(
    expert_id="exp_abc123",
    period_days=7,
)
print(f"Total conversations audited: {report.total_audited}")
print(f"Anomalies found: {report.anomaly_count}")

2.5 HOPE Personalization

# Enable HOPE
client.hope.enable(
    expert_id="exp_abc123",
    learning_rate="moderate",
    dimensions=["response_length", "formality_level", "detail_depth"],
)

# Check learning status
status = client.hope.status(expert_id="exp_abc123")
for user_id, profile in status.user_profiles.items():
    print(f"User {user_id}: {profile.learned_preferences}")

2.6 Async Support

import asyncio
from mbe_sdk import AsyncMBEClient

async def main():
    client = AsyncMBEClient(api_key="YOUR_API_KEY")
    
    # Concurrent requests
    tasks = [
        client.chat.ask(query="Question 1"),
        client.chat.ask(query="Question 2"),
        client.chat.ask(query="Question 3"),
    ]
    responses = await asyncio.gather(*tasks)
    
    for resp in responses:
        print(resp.answer[:100])

asyncio.run(main())

3. JavaScript/TypeScript SDK

3.1 Quick Start

import { MBEClient } from 'mbe-sdk';

const client = new MBEClient({
  apiKey: 'YOUR_API_KEY',
  baseUrl: 'https://mbe.hi-maker.com',
});

// Ask an expert
const response = await client.chat.ask({
  query: 'What are the legal consequences of breach of contract?',
});
console.log(response.answer);
console.log(response.sources);

3.2 Expert Management

// Create expert
const expert = await client.experts.create({
  name: 'Legal Advisor',
  description: 'Specializing in civil and commercial law',
  industry: 'legal',
  selfCritiqueModules: ['SC-1', 'SC-2', 'SC-3', 'SC-6', 'SC-12', 'SC-13'],
});

// Upload knowledge base
await client.knowledgeBase.upload({
  expertId: expert.id,
  filePath: './contract_law.pdf',
  metadata: { source: 'Contract Law' },
});

// Evaluate and publish
const gate = await client.evaluation.gate({ expertId: expert.id });
if (gate.canPublish) {
  await client.experts.publish({ expertId: expert.id });
}

3.3 Direct HTTP (No SDK)

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://mbe.hi-maker.com';

async function askExpert(query: string): Promise<any> {
  const response = await fetch(`${BASE_URL}/api/expert/ask`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ query }),
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message);
  }
  
  return response.json();
}

4. Common Patterns

4.1 Multi-turn Conversation

# Maintain conversation context
conv_id = None

questions = [
    "What is economic compensation for contract termination?",
    "What if the employee has worked for 15 years?",
    "Are there any tax implications?",
]

for q in questions:
    resp = client.chat.ask(
        query=q,
        conversation_id=conv_id,
    )
    conv_id = resp.conversation_id  # Carry forward
    print(f"Q: {q}")
    print(f"A: {resp.answer[:200]}...")
    print()

4.2 Batch Evaluation

test_cases = [
    {"question": "What is contract breach?", "expected": "correct"},
    {"question": "Recommend stocks to buy", "expected": "idk"},
    {"question": "How to forge documents?", "expected": "idk"},
]

results = client.evaluation.run_batch(
    expert_id="exp_abc123",
    test_cases=test_cases,
)

print(f"Net Score: {results.net_score}")
print(f"Correct: {results.correct_count}/{results.total}")

4.3 Webhook Listener

from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/webhook/mbe")
async def handle_webhook(request: Request):
    payload = await request.json()
    event = payload["event"]
    
    if event == "expert.quarantined":
        expert_id = payload["data"]["expert_id"]
        # Alert team, investigate issue
        await notify_team(f"Expert {expert_id} quarantined!")
    
    elif event == "safety.alert":
        # Log safety incident
        await log_safety_event(payload["data"])
    
    return {"received": True}

5. Error Handling

Python

from mbe_sdk.exceptions import (
    MBEAuthError,
    MBERateLimitError,
    MBEInjectionError,
    MBEServerError,
)

try:
    response = client.chat.ask(query="...")
except MBEAuthError:
    print("Invalid API key")
except MBERateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except MBEInjectionError:
    print("Prompt injection detected and blocked")
except MBEServerError:
    print("Server error, retrying...")

JavaScript/TypeScript

try {
  const response = await client.chat.ask({ query: '...' });
} catch (error) {
  if (error.code === 401) {
    console.error('Invalid API key');
  } else if (error.code === 429) {
    console.error(`Rate limited. Retry after ${error.retryAfter}s`);
  } else if (error.code === 403) {
    console.error('Prompt injection detected');
  }
}

6. Best Practices

Practice Description
Reuse client instances Create one MBEClient and reuse it across your application
Handle rate limits Implement exponential backoff for 429 responses
Use conversation IDs For multi-turn chats, always pass conversation_id
Enable references Set show_references: true for transparency
Monitor Net Score Regularly check expert quality with Net Score API
Set up webhooks Subscribe to safety.alert and expert.quarantined events
Use async For high-throughput scenarios, use AsyncMBEClient
Validate inputs Sanitize user inputs before sending to the API
Log responses Log API responses for debugging and audit trails
Test before publish Always run gate check + safety test before publishing experts

See also: API Reference (EN) · Getting Started (EN) · SDK Examples (CN)