Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Build a System-User-Assistant Message List in Python
Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Message:
role: str
content: str
@dataclass
class Conversation:
messages: List[Message] = field(default_factory=list)
def add_system(self, content: str) -> None:
self.messages.append(Message(role="system", con…
How to Mock OpenAI Tool Call Messages in Python
Create an assistant message with a function tool call in OpenAI's chat format, useful for testing and mocking.
from openai import OpenAI
def mock_tool_call(tool_name: str, arguments: dict) -> dict:
"""Simulate a tool call message in OpenAI style."""
return {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_" + "a1b2c3d4e5f6",
"type…
How to Parse Chat Completion JSON in Python
Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.
import json
def parse_chat_response(raw: str) -> dict:
data = json.loads(raw)
choice = data["choices"][0]
return {
"content": choice["message"]["content"],
"finish_reason": choice["finish_reason"],
"model": data["model"],
}
if __name__ == "__main__":
mock_response = '''
…
How to Truncate Text to a Token Budget in Python
Truncate a string to a maximum token budget for LLM context using the tiktoken library and OpenAI's tokenizer.
import tiktoken
def truncate_to_token_budget(text, max_tokens, model="gpt-3.5-turbo"):
enc = tiktoken.encoding_for_model(model)
tokens = enc.encode(text)
if len(tokens) <= max_tokens:
return text
truncated_tokens = tokens[:max_tokens]
return enc.decode(truncated_tokens)
if __name__ == "__…
How to build a function calling schema dict in Python
Build an OpenAI-compatible function calling schema dictionary with a helper function that takes name, description, parameters, and required fields.
import json
from typing import Dict, Any, List, Optional
def build_function_schema(
name: str,
description: str,
parameters: Optional[Dict[str, Any]] = None,
required: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Build an OpenAI-compatible function calling schema dictionary."""
schema: …
How to Mock a Whisper API Transcription Stub in Python
Simulate an OpenAI Whisper-style transcription response with a dataclass request model and a mock function that returns structured audio transcription output.
import json
from dataclasses import dataclass
from typing import Optional
@dataclass
class AudioRequest:
file_path: str
language: Optional[str] = None
def to_api_payload(self) -> dict:
return {"file": self.file_path, "language": self.language}
def mock_whisper_transcribe(payload: dict) -> dict:
…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.