Claude Code for OpenAI Advanced: Assistants API, Batch, and Fine-Tuning — Claude Skills 360 Blog
Blog / AI / Claude Code for OpenAI Advanced: Assistants API, Batch, and Fine-Tuning
AI

Claude Code for OpenAI Advanced: Assistants API, Batch, and Fine-Tuning

Published: December 31, 2026
Read time: 10 min read
By: Claude Skills 360

OpenAI’s platform offers more than chat completions: the Assistants API manages stateful threads with file retrieval and code execution. The Batch API processes millions of requests at half the cost, results available within 24 hours. Fine-tuning adapts GPT-4o-mini to domain-specific tasks with a fraction of prompt engineering overhead. Structured Outputs with response_format: { type: "json_schema" } guarantees valid JSON matching your schema. The Realtime API handles bidirectional audio for voice applications. Claude Code generates Assistants API integrations, batch job scripts, fine-tuning dataset preparation, and the structured output schemas for production OpenAI deployments.

CLAUDE.md for OpenAI Projects

## OpenAI Stack
- SDK: openai >= 1.50 (Python) or openai >= 4.60 (Node.js)
- Models: gpt-4o (smart), gpt-4o-mini (fast/cheap), o3 (reasoning)
- Assistants: for stateful multi-turn with file retrieval
- Batch: for offline bulk tasks — ~50% cost reduction
- Fine-tuning: gpt-4o-mini for domain adaptation (not basic prompting)
- Embeddings: text-embedding-3-large (1536d), text-embedding-3-small (1536d cheaper)
- Structured outputs: response_format with json_schema — validate client-side too
- Rate limits: implement exponential backoff with openai.Error.is_retryable()
# assistants/knowledge_assistant.py
from openai import OpenAI
import time

client = OpenAI()


def create_knowledge_assistant(name: str, instructions: str) -> str:
    """Create an assistant with file_search and code_interpreter tools."""

    assistant = client.beta.assistants.create(
        name=name,
        instructions=instructions,
        model="gpt-4o",
        tools=[
            {"type": "file_search"},
            {"type": "code_interpreter"},
        ],
        tool_resources={
            "file_search": {
                "vector_stores": [
                    {
                        "name": f"{name}-knowledge-base",
                    }
                ]
            }
        },
        temperature=0.1,
        response_format={"type": "text"},
    )

    return assistant.id


def upload_documents(vector_store_id: str, file_paths: list[str]) -> list[str]:
    """Upload documents to the assistant's file search vector store."""
    file_ids = []

    for path in file_paths:
        with open(path, "rb") as f:
            file = client.files.create(file=f, purpose="assistants")
            file_ids.append(file.id)

    # Add files to vector store (triggers automatic chunking + embedding)
    batch = client.beta.vector_stores.file_batches.create_and_poll(
        vector_store_id=vector_store_id,
        file_ids=file_ids,
    )

    print(f"Files processed: {batch.file_counts.completed}/{batch.file_counts.total}")
    return file_ids


def chat_with_assistant(assistant_id: str, user_message: str, thread_id: str | None = None) -> tuple[str, str]:
    """Send a message and get a response. Returns (response_text, thread_id)."""

    # Create or continue thread
    thread = (
        client.beta.threads.retrieve(thread_id)
        if thread_id
        else client.beta.threads.create()
    )

    # Add user message to thread
    client.beta.threads.messages.create(
        thread_id=thread.id,
        role="user",
        content=user_message,
    )

    # Run the assistant and wait for completion
    run = client.beta.threads.runs.create_and_poll(
        thread_id=thread.id,
        assistant_id=assistant_id,
        max_completion_tokens=2048,
    )

    if run.status != "completed":
        raise RuntimeError(f"Run failed with status: {run.status}")

    # Get the latest assistant message
    messages = client.beta.threads.messages.list(
        thread_id=thread.id,
        limit=1,
        order="desc",
    )

    response_text = messages.data[0].content[0].text.value

    # Log citations from file search
    for annotation in messages.data[0].content[0].text.annotations:
        if annotation.type == "file_citation":
            print(f"Citation from file: {annotation.file_citation.file_id}")

    return response_text, thread.id


# Usage
assistant_id = create_knowledge_assistant(
    name="Support Assistant",
    instructions="Answer customer questions using the knowledge base. Cite sources. Be concise.",
)

response, thread_id = chat_with_assistant(assistant_id, "What is your return policy?")
print(response)

# Continue conversation in same thread
followup, _ = chat_with_assistant(
    assistant_id,
    "What about electronics specifically?",
    thread_id=thread_id
)

Batch API for Bulk Inference

# batch/process_batch.py — cost-efficient bulk processing
import json
import time
from openai import OpenAI
from pathlib import Path

client = OpenAI()


def create_batch_file(requests: list[dict], output_path: str) -> str:
    """Create a JSONL file for batch submission."""
    with open(output_path, "w") as f:
        for i, req in enumerate(requests):
            batch_request = {
                "custom_id": f"request-{i}",
                "method": "POST",
                "url": "/v1/chat/completions",
                "body": req,
            }
            f.write(json.dumps(batch_request) + "\n")

    return output_path


def submit_and_wait(input_file_path: str, description: str = "") -> list[dict]:
    """Submit batch and poll until complete."""

    # Upload batch file
    with open(input_file_path, "rb") as f:
        batch_file = client.files.create(file=f, purpose="batch")

    # Create batch job
    batch = client.batches.create(
        input_file_id=batch_file.id,
        endpoint="/v1/chat/completions",
        completion_window="24h",
        metadata={"description": description},
    )

    print(f"Batch {batch.id} submitted. Waiting...")

    # Poll status
    while True:
        batch = client.batches.retrieve(batch.id)
        print(f"Status: {batch.status} | {batch.request_counts.completed}/{batch.request_counts.total}")

        if batch.status == "completed":
            break
        elif batch.status in ("failed", "expired", "cancelled"):
            raise RuntimeError(f"Batch failed: {batch.status}")

        time.sleep(30)

    # Download results
    result_file = client.files.content(batch.output_file_id)
    results = []

    for line in result_file.text.strip().split("\n"):
        result = json.loads(line)
        if result.get("error"):
            print(f"Failed: {result['custom_id']}: {result['error']}")
        else:
            results.append({
                "id": result["custom_id"],
                "content": result["response"]["body"]["choices"][0]["message"]["content"],
                "model": result["response"]["body"]["model"],
                "tokens": result["response"]["body"]["usage"]["total_tokens"],
            })

    return results


# Usage: classify 50,000 customer reviews
def classify_reviews_batch(reviews: list[str]) -> list[str]:
    requests = [
        {
            "model": "gpt-4o-mini",
            "messages": [
                {"role": "system", "content": "Classify sentiment as: positive, negative, or neutral. Reply with only the label."},
                {"role": "user", "content": review},
            ],
            "max_tokens": 10,
            "temperature": 0,
        }
        for review in reviews
    ]

    input_file = create_batch_file(requests, "/tmp/review_batch.jsonl")
    results = submit_and_wait(input_file, "Review sentiment classification")

    return [r["content"].lower().strip() for r in results]

Structured Outputs

# structured/extraction.py — guaranteed JSON schema compliance
from openai import OpenAI
from pydantic import BaseModel
import json

client = OpenAI()


class OrderExtraction(BaseModel):
    customer_name: str | None
    items: list[dict]  # [{product, quantity, price}]
    total: float | None
    currency: str = "USD"
    delivery_address: str | None
    special_instructions: str | None


def extract_order_structured(text: str) -> OrderExtraction:
    """Extract order details with guaranteed JSON schema compliance."""

    completion = client.beta.chat.completions.parse(
        model="gpt-4o-2024-08-06",
        messages=[
            {
                "role": "system",
                "content": "Extract order information from the text. Only include explicitly mentioned information.",
            },
            {"role": "user", "content": text},
        ],
        response_format=OrderExtraction,  # Pydantic model → JSON schema
    )

    # Guaranteed to parse successfully — OpenAI enforces the schema
    return completion.choices[0].message.parsed


# Alternative: raw JSON schema for Node.js or manual schema
def extract_with_raw_schema(text: str) -> dict:
    response = client.chat.completions.create(
        model="gpt-4o-2024-08-06",
        messages=[
            {"role": "user", "content": f"Extract entities from: {text}"},
        ],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "entities",
                "strict": True,
                "schema": {
                    "type": "object",
                    "properties": {
                        "people": {"type": "array", "items": {"type": "string"}},
                        "organizations": {"type": "array", "items": {"type": "string"}},
                        "dates": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["people", "organizations", "dates"],
                    "additionalProperties": False,
                },
            },
        },
    )

    return json.loads(response.choices[0].message.content)

Fine-Tuning Data Preparation

# finetuning/prepare_dataset.py — prepare training data for fine-tuning
import json
from openai import OpenAI

client = OpenAI()


def create_training_example(
    system: str,
    user: str,
    assistant: str,
) -> dict:
    """Create a single training example in chat format."""
    return {
        "messages": [
            {"role": "system", "content": system},
            {"role": "user", "content": user},
            {"role": "assistant", "content": assistant},
        ]
    }


def save_training_data(examples: list[dict], output_path: str) -> None:
    """Save training examples as JSONL."""
    with open(output_path, "w") as f:
        for example in examples:
            f.write(json.dumps(example) + "\n")

    print(f"Saved {len(examples)} examples to {output_path}")


def launch_fine_tuning(training_file_path: str, model: str = "gpt-4o-mini-2024-07-18") -> str:
    """Upload training file and start fine-tuning job."""

    # Upload training file
    with open(training_file_path, "rb") as f:
        training_file = client.files.create(file=f, purpose="fine-tune")

    print(f"Uploaded training file: {training_file.id}")

    # Create fine-tuning job
    job = client.fine_tuning.jobs.create(
        training_file=training_file.id,
        model=model,
        hyperparameters={
            "n_epochs": 3,
            "batch_size": "auto",
            "learning_rate_multiplier": "auto",
        },
        suffix="custom-classifier",  # Model will be: gpt-4o-mini-...-custom-classifier
    )

    print(f"Fine-tuning job created: {job.id}")
    return job.id


def monitor_job(job_id: str) -> str:
    """Monitor fine-tuning progress and return final model name."""
    import time

    while True:
        job = client.fine_tuning.jobs.retrieve(job_id)

        print(f"Status: {job.status}")

        # List recent events
        events = client.fine_tuning.jobs.list_events(job_id, limit=5)
        for event in reversed(events.data):
            print(f"  {event.message}")

        if job.status == "succeeded":
            print(f"Fine-tuning complete! Model: {job.fine_tuned_model}")
            return job.fine_tuned_model
        elif job.status in ("failed", "cancelled"):
            raise RuntimeError(f"Fine-tuning failed: {job.status}")

        time.sleep(60)


# Example: prepare customer service training data
training_data = [
    create_training_example(
        system="You are a concise customer support agent. Keep responses under 3 sentences.",
        user="How do I track my order?",
        assistant="Log into your account and navigate to 'Orders'. Click on your order to see real-time tracking. You'll also receive email updates at each shipping milestone.",
    ),
    create_training_example(
        system="You are a concise customer support agent. Keep responses under 3 sentences.",
        user="What's your return policy?",
        assistant="Items can be returned within 30 days of delivery in original condition. Initiate returns from your Orders page — we provide a free prepaid label. Refunds process within 5-7 business days.",
    ),
    # ... more examples (recommend 100-1000 for good results)
]

save_training_data(training_data, "training_data.jsonl")

For the Anthropic Claude API alternative with superior reasoning and longer context windows, see the Anthropic SDK guide for Claude integration patterns. For the Vercel AI SDK that unifies OpenAI and Anthropic under a single streaming interface, the Vercel AI SDK guide covers the React streaming patterns. The Claude Skills 360 bundle includes OpenAI skill sets covering Assistants API, Batch processing, and fine-tuning workflows. Start with the free tier to try OpenAI integration generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free