{ "cells": [ { "cell_type": "markdown", "id": "1d983d23", "metadata": {}, "source": [ "# This is a tutorial on how to use IOAI's provided LLM proxy" ] }, { "cell_type": "markdown", "id": "f5033564", "metadata": {}, "source": [ "## Step 1: initialize your OpenAI client\n", "\n", "Please use your provided api key here." ] }, { "cell_type": "code", "execution_count": null, "id": "699ae2b2", "metadata": {}, "outputs": [], "source": [ "from openai import AsyncClient\n", "\n", "BASE_URL = \"https://ioai-llm-proxy.up.railway.app/prox/v1\"\n", "API_KEY = \"\"\n", "\n", "openai_client = AsyncClient(\n", " base_url=BASE_URL,\n", " api_key=API_KEY,\n", ")" ] }, { "cell_type": "markdown", "id": "8f2b8e77", "metadata": {}, "source": [ "## Step 2: Generate output\n", "\n", "Note that we have an allowlist on model ids:\n", "\n", "- `openai/gpt-4.1`\n", "- `openai/gpt-4.1-mini`\n", "- `openai/gpt-4.1-nano`\n", "- `openai/gpt-4o`\n", "- `openai/gpt-4o-mini`\n", "- `gpt-4o-mini`\n", "- `gpt-4o`\n", "- `gpt-4.1`\n", "- `gpt-4.1-mini`\n", "- `gpt-4.1-nano`\n", "- `google/gemini-2.5-pro`\n", "- `google/gemini-2.5-flash`\n", "- `moonshotai/kimi-k2`\n", "- `qwen/qwen3-235b-a22b-07-25`\n", "- `anthropic/claude-sonnet-4`" ] }, { "cell_type": "code", "execution_count": null, "id": "96895459", "metadata": {}, "outputs": [], "source": [ "response = await openai_client.chat.completions.create(\n", " model=\"openai/gpt-4o-mini\",\n", " messages=[{\"role\": \"user\", \"content\": \"Hello, world!\"}],\n", ")\n", "\n", "print(response)\n", "print(response.choices[0].message.content)" ] }, { "cell_type": "markdown", "id": "6c0b2e3e", "metadata": {}, "source": [ "## Advanced: Structured Outputs\n", "\n", "You can use structured outputs to generate objects that fit a specific structure." ] }, { "cell_type": "code", "execution_count": null, "id": "4f67373b", "metadata": {}, "outputs": [], "source": [ "from pydantic import BaseModel\n", "from rich import print as rprint\n", "\n", "class CalendarItem(BaseModel):\n", " title: str\n", " month: int\n", " date: int\n", " year: int\n", " description: str\n", "\n", "result = await openai_client.beta.chat.completions.parse(\n", " model=\"openai/gpt-4o-mini\",\n", " messages=[\n", " {\"role\": \"system\", \"content\": \"You are a helpful assistant that generates calendar items.\"},\n", " {\"role\": \"user\", \"content\": \"IOAI opening ceremony at Aug. 1, 2025\"}\n", " ],\n", " response_format=CalendarItem,\n", ")\n", "\n", "print(result)\n", "rprint(result.choices[0].message.parsed)" ] }, { "cell_type": "markdown", "id": "d1d6dafa", "metadata": {}, "source": [ "## Batch requests with retry\n", "\n", "To generate large amounts of LLM completions efficiently and rhobustly, we can leverage:\n", "\n", "- Concurrent requests capped by an async Semaphore -- so that we can make multiple requests at the same time without overwhelming our bandwidth\n", "- Exponential backoff based retry for each request -- so that we gracefully retry when unexpected network / provider errors happen\n", "\n", "The below is an example:" ] }, { "cell_type": "code", "execution_count": null, "id": "f591a91f", "metadata": {}, "outputs": [], "source": [ "class RankingExtraction(BaseModel):\n", " ranking: int\n", " contest: str\n", "\n", "texts = [f\"We ranked {i}th in the IOAI 2025\" for i in range(1, 101)]\n", "len(texts)" ] }, { "cell_type": "code", "execution_count": null, "id": "80f7dafa", "metadata": {}, "outputs": [], "source": [ "from typing import List\n", "from tenacity import retry, stop_after_attempt, wait_exponential\n", "from asyncio import Semaphore\n", "from tqdm.notebook import tqdm\n", "from tqdm.asyncio import tqdm as tqdm_asyncio\n", "\n", "@retry(\n", " stop=stop_after_attempt(3),\n", " wait=wait_exponential(multiplier=1, min=4, max=10),\n", ")\n", "async def process_one(txt: str) -> RankingExtraction:\n", " result = await openai_client.beta.chat.completions.parse(\n", " model=\"openai/gpt-4o-mini\",\n", " messages=[{\"role\": \"user\", \"content\": txt}],\n", " response_format=RankingExtraction,\n", " )\n", " return result.choices[0].message.parsed" ] }, { "cell_type": "code", "execution_count": null, "id": "13380165", "metadata": {}, "outputs": [], "source": [ "print(texts[0])\n", "print(await process_one(texts[0]))" ] }, { "cell_type": "code", "execution_count": null, "id": "be960117", "metadata": {}, "outputs": [], "source": [ "async def process_all(texts: List[str]):\n", " semaphore = Semaphore(50) # we limit to making 50 requests concurrently\n", " async def _process_with_sema(txt: str):\n", " async with semaphore:\n", " return await process_one(txt)\n", " return await tqdm_asyncio.gather(\n", " *[_process_with_sema(txt) for txt in texts],\n", " desc=\"Processing\",\n", " total=len(texts),\n", " )\n", "\n", "results = await process_all(texts)\n", "\n", "results[:10]" ] }, { "cell_type": "markdown", "id": "80bee95e", "metadata": {}, "source": [ "# Check your credits\n", "\n", "You get $10 of credits, so use it economically! You can run the following cell to check the amount of credits you have used." ] }, { "cell_type": "code", "execution_count": null, "id": "81d2e662", "metadata": {}, "outputs": [], "source": [ "from httpx import get\n", "\n", "result = get(f\"https://ioai-llm-proxy.up.railway.app/credits/{API_KEY}\")\n", "\n", "resp = result.json()\n", "\n", "print(f\"\"\"\n", "Credits limit: ${resp['limit']}\n", "Used: ${resp['usage']}\n", "Credits remaining: ${resp['limit'] - resp['usage']}\n", "\"\"\")" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.11" } }, "nbformat": 4, "nbformat_minor": 5 }