<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Amri on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Amri on Medium]]></description>
        <link>https://medium.com/@amri369?source=rss-c62450552611------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_ZVX4qzB3YvkCc_z</url>
            <title>Stories by Mohamed Amri on Medium</title>
            <link>https://medium.com/@amri369?source=rss-c62450552611------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:28:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amri369/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build Production Grade Agents Using MCP, Temporal and OpenAI Agents SDK]]></title>
            <link>https://medium.com/@amri369/build-production-grade-agents-using-mcp-temporal-and-openai-agents-sdk-c49c928bc4ec?source=rss-c62450552611------2</link>
            <guid isPermaLink="false">https://medium.com/p/c49c928bc4ec</guid>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Mohamed Amri]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 23:38:09 GMT</pubDate>
            <atom:updated>2025-09-01T07:08:42.461Z</atom:updated>
            <content:encoded><![CDATA[<p>Dear friends, the last month brought two announcements that will change how we ship production-ready agents. Temporal announced integrations with two major players:</p><ul><li><strong>OpenAI Agents SDK</strong>: so your agent loops run with <a href="https://temporal.io/blog/announcing-openai-agents-sdk-integration">Temporal’s Durable Execution</a>.</li><li><strong>Pydantic AI</strong>: so you can pair typed agent logic with the same <a href="https://ai.pydantic.dev/temporal/">Durable Execution</a> model.</li></ul><p><strong>Why this matters?</strong></p><p>Most agent frameworks shine at <em>agentic orchestration</em> (tools, guardrails, handoffs, tracing). But when it’s time to serve millions of requests with real SLAs, you still need an orchestrator that gives you durability, retries, observability, versioning, and scale.</p><p>That’s exactly where Temporal fits: it becomes the execution layer between your agent framework and your infra, so your agents keep making progress even across crashes, deploys, rate limits, and flaky networks.</p><p><strong>What you‘ll’ learn?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpTgdUHdX4bJdMFQ4y2HOg.png" /><figcaption>Architecture of MCP — OpenAI Agents SDK — Temporal integration</figcaption></figure><p>We’ll use MCP purely as a versioned prompt registry, while Temporal Activities run the agents. To do so, we’ll use a multi-agent example originally published in the OpenAI Agents SDK GitHub repo:</p><ul><li><a href="https://github.com/openai/openai-agents-python/tree/main/examples/financial_research_agent">Without Temporal orchestration</a></li><li><a href="https://github.com/temporalio/samples-python/tree/main/openai_agents/financial_research_agent">With Temporal orchestration</a>, but without the MCP piece.</li></ul><p>To simplify the example, we’ll use an HTTPStreamable MCP server to serve the prompts. In the future, we’ll add more examples with tools and unlock the full potential of this integration.</p><p><strong>Tracing with Logfire:</strong></p><p>We will additionally use <a href="https://github.com/pydantic/logfire">Logfire</a> to trace the agents. This tool is developed by the Pydantic team and excels in agents observability while keeping the implementation simple.</p><p>All the code is publicly available in <a href="https://github.com/amri369/mcp-temporal-agents">this link</a>.</p><p><strong>Quick note:</strong></p><p>At Alpheya, where I serve as Director of AI Engineering, we prize excellence and a positive, builder‑first engineering culture. We contribute to open source too. Most recently swe open-sourced <a href="https://github.com/alpheya/sealed-secrets-ui">Sealed Secrets UI</a> to simplify Kubernetes secrets management.</p><p>As our CEO Roger Rouhana puts it, we’re building “a next‑generation, AI‑powered platform that allows financial institutions to provide personalized, data‑driven investment solutions at scale,” as highlighted in <a href="https://www.mediaoffice.abudhabi/en/economy/abu-dhabi-investment-office-partners-with-alpheya-to-accelerate-ai-led-digital-wealth-management-capabilities-in-the-emirate/">our ADIO partnership announcement</a>.</p><h3>1- MCP Server</h3><p>First, move <a href="https://github.com/openai/openai-agents-python/tree/main/examples/financial_research_agent/agents">all agent prompts</a> into a single MCP server. Treat them like code, not config.</p><p><strong>Why this helps</strong></p><ul><li><strong>Single source of truth:</strong> one place to read, review, and ship prompts.</li><li><strong>No database needed:</strong> prompts live as files, served by MCP.</li><li><strong>Built-in versioning:</strong> Git gives you history, diffs, PR review, and instant rollbacks.</li><li><strong>Reproducibility:</strong> pin runs to a specific tag/commit; you always know exactly which prompt produced a result.</li><li><strong>Env isolation:</strong> use branches/tags (dev, staging, prod) for safe promotion.</li></ul><pre>from mcp.server.fastmcp import FastMCP<br><br>mcp = FastMCP(&quot;Financial Research Server&quot;)<br><br>@mcp.prompt()<br>def financials_prompt():<br>    return (<br>    &quot;You are a financial analyst focused on company fundamentals such as revenue, &quot;<br>    &quot;profit, margins and growth trajectory. Given a collection of web (and optional file) &quot;<br>    &quot;search results about a company, write a concise analysis of its recent financial &quot;<br>    &quot;performance. Pull out key metrics or quotes. Keep it under 2 paragraphs.&quot;<br>)<br><br>@mcp.prompt()<br>def planner_prompt():<br>    return (<br>    &quot;You are a financial research planner. Given a request for financial analysis, &quot;<br>    &quot;produce a set of web searches to gather the context needed. Aim for recent &quot;<br>    &quot;headlines, earnings calls or 10‑K snippets, analyst commentary, and industry background. &quot;<br>    &quot;Output between 5 and 15 search terms to query for.&quot;<br>)<br><br>@mcp.prompt()<br>def risk_prompt():<br>    return (<br>    &quot;You are a risk analyst looking for potential red flags in a company&#39;s outlook. &quot;<br>    &quot;Given background research, produce a short analysis of risks such as competitive threats, &quot;<br>    &quot;regulatory issues, supply chain problems, or slowing growth. Keep it under 2 paragraphs.&quot;<br>)<br><br>@mcp.prompt()<br>def search_prompt():<br>    return (<br>    &quot;You are a research assistant specializing in financial topics. &quot;<br>    &quot;Given a search term, use web search to retrieve up‑to‑date context and &quot;<br>    &quot;produce a short summary of at most 300 words. Focus on key numbers, events, &quot;<br>    &quot;or quotes that will be useful to a financial analyst.&quot;<br>)<br><br>@mcp.prompt()<br>def verifier_prompt():<br>    return (<br>    &quot;You are a meticulous auditor. You have been handed a financial analysis report. &quot;<br>    &quot;Your job is to verify the report is internally consistent, clearly sourced, and makes &quot;<br>    &quot;no unsupported claims. Point out any issues or uncertainties.&quot;<br>)<br><br>@mcp.prompt()<br>def writer_prompt():<br>    return (<br>    &quot;You are a senior financial analyst. You will be provided with the original query and &quot;<br>    &quot;a set of raw search summaries. Your task is to synthesize these into a long‑form markdown &quot;<br>    &quot;report (at least several paragraphs) including a short executive summary and follow‑up &quot;<br>    &quot;questions. If needed, you can call the available analysis tools (e.g. fundamentals_analysis, &quot;<br>    &quot;risk_analysis) to get short specialist write‑ups to incorporate.&quot;<br>)</pre><p>Spin up an <strong>HTTP-streamable MCP server</strong> behind FastAPI. The lifespan hook cleanly starts/stops the MCP session manager.</p><pre>import contextlib<br>from fastapi import FastAPI<br><br>from examples.mcp_server.financial_research_server import mcp as mcp_server<br><br>@contextlib.asynccontextmanager<br>async def lifespan(app_: FastAPI):<br>    async with contextlib.AsyncExitStack() as stack:<br>        await stack.enter_async_context(mcp_server.session_manager.run())<br>        yield<br>app = FastAPI(lifespan=lifespan)<br>app.mount(&quot;/financials&quot;, mcp_server.streamable_http_app())</pre><p>Run it:</p><pre>uv run uvicorn examples.mcp_server.main:app --reload --port 9000</pre><p>You now have a local MCP endpoint at http://localhost:9000/financials that your agents will use next.</p><h3>2- MCP Based Agents</h3><p>We define agents as <strong>async context managers</strong> that:</p><ul><li><strong>Fetch prompts from MCP</strong> at startup (s.get_prompt(...)) and keep the MCP connection alive.</li><li><strong>Pin prompt version/hash</strong> in memory (for reproducibility and deterministic replays in Temporal Activities).</li><li><strong>Emit typed outputs</strong> (AnalysisSummary, FinancialReportData) so downstream steps are schema-safe.</li><li><strong>Compose agents as tools</strong> via .as_tool(...) with a <strong>custom output extractor</strong> to normalize sub-agent returns.</li></ul><h4>Pattern A — simple agent (no sub-tools)</h4><pre>from contextlib import asynccontextmanager<br>from typing import AsyncIterator<br><br>from agents import Agent, WebSearchTool<br><br>from examples.financial_research_agent.models import AnalysisSummary<br>from examples.financial_research_agent.utils import get_agent, make_server<br><br>@asynccontextmanager<br>async def get_search_agent() -&gt; AsyncIterator[Agent]:<br>    server = make_server()<br>    async with server as s:<br>        instructions = await s.session.get_prompt(&quot;search_prompt&quot;)<br>        prompt_text = instructions.messages[0].content.text<br>        agent = get_agent(<br>            name=&quot;FinancialSearchAgent&quot;,<br>            instructions=prompt_text,<br>            mcp_servers=[s],<br>            tools=[WebSearchTool()],<br>            output_type=AnalysisSummary,<br>        )<br>        yield agent</pre><p><strong>Pattern B — composer agent (uses two agents as tools)</strong></p><pre>from contextlib import AsyncExitStack, asynccontextmanager<br>from typing import AsyncIterator<br><br>from agents import Agent, RunResult<br><br>from examples.financial_research_agent.models import FinancialReportData<br>from examples.financial_research_agent.utils import get_agent, make_server<br>from examples.financial_research_agent.openai_agents.risk_agent import get_risk_agent<br>from examples.financial_research_agent.openai_agents.financials_agent import get_financials_agent<br><br>@asynccontextmanager<br>async def get_writer_agent() -&gt; AsyncIterator[Agent]:<br>    server = make_server()<br>    async with server as s:<br>        instructions = await s.get_prompt(&quot;writer_prompt&quot;)<br>        prompt_text = instructions.messages[0].content.text<br>        agent = get_agent(<br>            name=&quot;FinancialWriterAgent&quot;,<br>            instructions=prompt_text,<br>            mcp_servers=[s],<br>            output_type=FinancialReportData,<br>        )<br>        yield agent<br><br>async def _summary_extractor(run_result: RunResult) -&gt; str:<br>    &quot;&quot;&quot;Custom output extractor for sub‑agents that return an AnalysisSummary.&quot;&quot;&quot;<br>    # The financial/risk analyst agents emit an AnalysisSummary with a `summary` field.<br>    # We want the tool call to return just that summary text so the writer can drop it inline.<br>    return str(run_result.final_output.summary)<br><br>@asynccontextmanager<br>async def get_writer_agent_with_tools() -&gt; AsyncIterator[Agent]:<br>    &quot;&quot;&quot;<br>    Clone the writer agent and attach:<br>      - fundamentals_analysis (backed by FinancialsAnalystAgent)<br>      - risk_analysis (backed by RiskAnalystAgent)<br>    Keeps all three agents alive for the duration of the context.<br>    &quot;&quot;&quot;<br>    async with AsyncExitStack() as stack:<br>        writer_agent = await stack.enter_async_context(get_writer_agent())<br>        financials_agent = await stack.enter_async_context(get_financials_agent())<br>        risk_agent = await stack.enter_async_context(get_risk_agent())<br><br>        fundamentals_tool = financials_agent.as_tool(<br>            tool_name=&quot;fundamentals_analysis&quot;,<br>            tool_description=&quot;Use to get a short write-up of key financial metrics&quot;,<br>            custom_output_extractor=_summary_extractor,<br>        )<br>        risk_tool = risk_agent.as_tool(<br>            tool_name=&quot;risk_analysis&quot;,<br>            tool_description=&quot;Use to get a short write-up of potential red flags&quot;,<br>            custom_output_extractor=_summary_extractor,<br>        )<br><br>        writer_with_tools = writer_agent.clone(tools=[fundamentals_tool, risk_tool])<br>        yield writer_with_tools</pre><h3>3- Orchestration with Temporal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4du49cDIKCAXsuwwkcR_Gg.png" /><figcaption>Temporal UI Showing Agents Running on Temporal Server</figcaption></figure><p>Temporal activities and workflows accept only serializable input/output — an Agent instance doesn’t. The workaround is simple and safe: pass a tiny JSON-friendly envelope (AgentRunnerParams), pick a factory from a name→factory map, construct the agent inside the activity, run it, return the <em>final_output</em>.</p><pre>from temporalio import activity<br>from agents import Runner<br>from examples.financial_research_agent.openai_agents.planner_agent import get_planner_agent<br>from examples.financial_research_agent.openai_agents.search_agent import get_search_agent<br>from examples.financial_research_agent.openai_agents.writer_agent import get_writer_agent_with_tools<br>from examples.financial_research_agent.openai_agents.verifier_agent import get_verification_agent<br>from examples.financial_research_agent.models import AgentRunnerParams<br><br>agents_mapper = {<br>    &quot;FinancialPlannerAgent&quot;: get_planner_agent,<br>    &quot;FinancialSearchAgent&quot;: get_search_agent,<br>    &quot;FinancialWriterAgent&quot;: get_writer_agent_with_tools,<br>    &quot;VerificationAgent&quot;: get_verification_agent,<br>}<br><br>@activity.defn<br>async def run_agent_activity(params: AgentRunnerParams):<br>    factory = agents_mapper[params.agent_choice]<br>    async with factory() as agent:<br>        activity.logger.info(f&quot;Running agent: {params.agent_choice}&quot;)<br>        result = await Runner.run(starting_agent=agent, input=params.message)<br>        return result.final_output</pre><p>Now, we turn the agent factories into one deterministic workflow. A planner converts the user query into a structured <em>FinancialSearchPlan</em>. Each search item is then dispatched as its own activity, so the lookups run in parallel within the same 60s timeout window.</p><p>When all searches complete, the writer consumes the aggregated results and emits a typed <em>FinancialReportData</em>. A verifier reviews that report and returns a <em>VerificationResult</em>. Only JSON-safe payloads move between workflow and activities, which keeps history small and retries clean.</p><pre>import asyncio<br><br>from datetime import timedelta<br>from temporalio import workflow<br><br>with workflow.unsafe.imports_passed_through():<br>    from examples.financial_research_agent.models import (<br>        AgentRunnerParams, AgentsChoices,<br>        FinancialSearchPlan, FinancialReportData,<br>        VerificationResult, FinancialReportWorkflowOutput<br>    )<br>    from examples.financial_research_agent.temporal.activities import run_agent_activity<br><br>@workflow.defn<br>class FinancialResearchWorkflow:<br>    @workflow.run<br>    async def run(self, query: str):<br>        payload = AgentRunnerParams(<br>            agent_choice=AgentsChoices.FinancialPlannerAgent,<br>            message=query<br>        )<br>        search_plan = await workflow.execute_activity(<br>            run_agent_activity,<br>            payload,<br>            start_to_close_timeout=timedelta(<br>                seconds=60<br>            ),<br>            schedule_to_close_timeout=timedelta(<br>                seconds=60<br>            ),<br>        )<br><br>        search_plan = FinancialSearchPlan(**search_plan)<br><br>        search_activities = []<br>        for search_item in search_plan.searches:<br>            payload = AgentRunnerParams(<br>                agent_choice=AgentsChoices.FinancialSearchAgent,<br>                message=search_item.query<br>            )<br>            search_activities.append(<br>                workflow.execute_activity(<br>                    run_agent_activity,<br>                    payload,<br>                    start_to_close_timeout=timedelta(<br>                        seconds=60<br>                    ),<br>                    schedule_to_close_timeout=timedelta(<br>                        seconds=60<br>                    ),<br>                )<br>            )<br><br>        search_results = await asyncio.gather(*search_activities)<br><br>        payload = AgentRunnerParams(<br>            agent_choice=AgentsChoices.FinancialWriterAgent,<br>            message=str(search_results)<br>        )<br><br>        report = await workflow.execute_activity(<br>            run_agent_activity,<br>            payload,<br>            start_to_close_timeout=timedelta(<br>                seconds=60<br>            ),<br>            schedule_to_close_timeout=timedelta(<br>                seconds=60<br>            ),<br>        )<br><br>        report = FinancialReportData(**report)<br>        payload = AgentRunnerParams(<br>            agent_choice=AgentsChoices.VerificationAgent,<br>            message=str(report)<br>        )<br><br>        verification = await workflow.execute_activity(<br>            run_agent_activity,<br>            payload,<br>            start_to_close_timeout=timedelta(<br>                seconds=60<br>            ),<br>            schedule_to_close_timeout=timedelta(<br>                seconds=60<br>            ),<br>        )<br><br>        verification = VerificationResult(**verification)<br><br>        print(&quot;\n\n=====REPORT=====\n\n&quot;)<br>        print(f&quot;Report:\n{report.markdown_report}&quot;)<br>        print(&quot;\n\n=====FOLLOW UP QUESTIONS=====\n\n&quot;)<br>        print(&quot;\n&quot;.join(report.follow_up_questions))<br>        print(&quot;\n\n=====VERIFICATION=====\n\n&quot;)<br>        print(verification)<br><br>        return FinancialReportWorkflowOutput(<br>            search_plan=search_plan,<br>            report=report,<br>            verification=verification,<br>        )</pre><h3>4- Observability with Logfire</h3><p><a href="https://logfire.pydantic.dev/docs/integrations/llms/openai/#openai-agents">Logfire ships with an OpenAI Agents SDK integration</a>. Turn it on and you get span-level traces for each agent loop, sub-agent/tool call, and MCP interaction.</p><pre>logfire.configure(token=settings.logfire_token)<br>logfire.instrument_openai_agents()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBAhrl1Pzf131EpRVaKLWA.png" /><figcaption>Tracing with Pydantic Logfire</figcaption></figure><p>The screenshot shows a timeline of agent runs: repeated “Agent workflow” traces with nested spans like “MCP: list tools …”, “Agent run: ‘FinancialSearchAgent’”, and in the writer phase the tool calls “fundamentals_analysis” and “risk_analysis”. On the right, duration bars make hot paths obvious and you can see parallel searches completing while the writer and its tools run longer.</p><p>What we gain</p><ul><li>end-to-end visibility across planner → search → writer → verifier</li><li>latency per span to spot bottlenecks, retries, and slow tools</li><li>clear correlation of failures to specific MCP/tool/model calls</li><li>quick validation that parallelism is working without extra logs</li></ul><h3><strong>5- Conclusion</strong></h3><p>We now have a production pattern:</p><ul><li>Prompts live in an mcp server (versioned with git)</li><li>Agents are built on demand inside temporal activities, the workflow orchestrates planner → parallel search → writer → verifier</li><li>Logfire gives us end-to-end traces.</li></ul><p>The net effect is durability, retries, and clean observability without coupling agent state to the orchestrator. this keeps workflows deterministic and histories small, while still letting you compose richer agents over time.</p><p>From here you can extend the same shape: add more tools/agents behind factories, promote prompt versions via tags/branches, and tighten slas by tuning activity timeouts and backoff. the tracing view makes it easy to spot hot paths and validate parallelism as you scale.</p><h3>Credits</h3><ul><li><a href="https://github.com/openai/openai-agents-python/tree/main/examples/financial_research_agent?utm_source=chatgpt.com">OpenAI Agents SDK — Financial Research Agent example</a></li><li><a href="https://github.com/temporalio/samples-python/tree/main/openai_agents/financial_research_agent?utm_source=chatgpt.com">Temporal — Financial Research example</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c49c928bc4ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Agents with OpenAI SDK using any LLM Provider (Claude, Deepseek, Perplexity, Gemini…)]]></title>
            <link>https://medium.com/@amri369/build-agents-with-openai-sdk-using-any-llm-provider-claude-deepseek-perplexity-gemini-5c80185b3cc2?source=rss-c62450552611------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c80185b3cc2</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llms-reasoning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Mohamed Amri]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 08:05:02 GMT</pubDate>
            <atom:updated>2025-03-17T06:46:20.653Z</atom:updated>
            <content:encoded><![CDATA[<pre>from agents import Agent, Runner, AsyncOpenAI, OpenAIChatCompletionsModel<br><br>claude_client = AsyncOpenAI(base_url=&quot;https://api.anthropic.com/v1/&quot;, api_key=claude_api_key)<br><br>code_refactoring_agent = Agent(<br>    name=&quot;Claude agent&quot;,<br>    instructions=&quot;You only respond to queries about code refactoring queries.&quot;,<br>    model=OpenAIChatCompletionsModel( <br>        model=&quot;claude-3-7-sonnet-20250219&quot;,<br>        openai_client=claude_client,<br>    ),<br>)<br><br>triage_agent = Agent(<br>    name=&quot;Openai agent&quot;,<br>    instructions=&quot;Handoff to the appropriate agent based on the user query.&quot;,<br>    handoffs=[code_refactoring_agent],<br>    model=&quot;gpt-3.5-turbo&quot;,<br>)<br><br>messy_code = &quot;&quot;&quot;<br>a = &quot;a&quot;<br>b = &quot;b&quot;<br>c = &quot;c&quot;<br>d = &quot;d&quot;<br>l = [a, b, c]<br>&quot;&quot;&quot;<br><br>result = await Runner.run(triage_agent, input=f&quot;Pleaserefactor my code:\n{messy_code}&quot;)<br>print(result.final_output)<br><br>&quot;&quot;&quot;<br>Sure! Here is the refactored code:<br><br>```python<br>l = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]<br>```<br>&quot;&quot;&quot;<br></pre><p>OpenAI recently released its Agents SDK — a promising tool that accelerates the development of agentic applications using a suite of off-the-shelf components.</p><p>This approach enables developers to concentrate on crafting innovative, use-case-specific solutions while the library manages the low-level components with a minimum of abstraction.</p><p>While the SDK is initially designed to support OpenAI models, this article demonstrates how to extend its capabilities to other LLM providers, whether open-source or commercial.</p><p>In this article, you’ll learn about:</p><ul><li>The core components of the OpenAI Agents API</li><li>How to integrate other LLM providers such as Deepseek, Anthropic, and Perplexity</li><li>Tracing dashboard to monitor agents workflows</li><li>Considerations for production systems</li></ul><h3>1. Introducing OpenAPI Agents SDK</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IEH1s-22v3Jl7qR1LfZRw.png" /><figcaption>OpenAI Agents SDK Architecture</figcaption></figure><p>The core concepts of OpenAI Agents are the following:</p><ol><li><a href="https://openai.github.io/openai-agents-python/agents">Agents</a>: They are defined as LLMs configured with instructions and tools. They serve as the foundational building blocks for agent-driven applications.</li><li><a href="https://openai.github.io/openai-agents-python/handoffs/">Handoffs</a>: This orchestration mechanism enables agents to seamlessly transfer control to one another, ensuring that specialized tasks are managed by the most appropriate agent.</li><li><a href="https://openai.github.io/openai-agents-python/guardrails/">Guardrails</a>: Running alongside agents, guardrails perform essential checks and validations on both user inputs and LLM outputs, ensuring safety and reliability.</li><li><a href="https://openai.github.io/openai-agents-python/tracing/">Tracing</a>: This feature offers built-in tracking of agent operations, allowing you to view, debug, and optimize workflows. It also includes a fine-tuning capability — potentially leveraging reinforcement learning — to enhance agents’ problem-solving skills.</li></ol><p>In the following sections, we examine deploying agents across various LLM providers — a feature that is essential for:</p><ul><li><strong>Cost Efficiency:</strong> Matches tasks with the most cost-effective models to reduce expenses.</li><li><strong>Performance Optimization:</strong> Leverages each model’s strengths for higher quality and accuracy.</li><li><strong>Reliability:</strong> Enhances resilience by reducing dependency on a single provider.</li><li><strong>Specialized Use Cases:</strong> Selects models tailored for specific domain tasks.</li><li><strong>Integration Complexity:</strong> Involves managing varied APIs and ensuring robust monitoring.</li><li><strong>Effective Guard-Railing:</strong> Uses a separate LLM for fact-checking to minimize bias risks.</li></ul><h3>2. Building AI agents with any LLM provider</h3><p><a href="https://github.com/openai/openai-agents-python/blob/main/src/agents/agent.py">The Agent class</a> enables the instantiation of agents objects with custom configurations. Below we highlight the essential ones:</p><ul><li><strong><em>instructions</em>:</strong> The instructions for the agent. Will be used as the “system prompt” when this agent is invoked. Describes what the agent should do, and how it responds.</li><li><strong><em>handoffs</em>:</strong> Handoffs are sub-agents that the agent can delegate to. You can provide a list of handoffs, and the agent can choose to delegate to them if relevant. Allows for separation of concerns and modularity.</li><li><strong><em>tools</em></strong>: A list of tools that the agent can use.</li><li><strong><em>model</em></strong>: <a href="https://github.com/openai/openai-agents-python/blob/main/src/agents/models/interface.py">The model implementation</a> to use when invoking the LLM.</li></ul><p>Two steps are required to create an agent with custom LLMs:</p><ol><li>Create an LLM client.</li><li>Use it to instantiate an Agent object by providing the LLM model.</li></ol><p><strong>2.1. Instantiating an LLM Client</strong></p><p>Below is an example demonstrating how to instantiate an LLM client independently of the provider — whether it’s Deepseek, Perplexity, Claude, or Gemini. Developers can also integrate custom LLMs, including open-source models, as long as they expose <a href="https://medium.com/@amri369/how-to-serve-deepseek-flagship-models-for-inference-with-vllm-and-tgi-using-openai-sdk-176b6cb801ef">OpenAI-compatible endpoints</a>. Don’t forget to install the library with this command pip install openai-agents.</p><pre>from agents import AsyncOpenAI<br><br>deepseek_client = AsyncOpenAI(base_url=&quot;https://api.deepseek.com&quot;, api_key=deepseek_api_key)<br>perplexity_client = AsyncOpenAI(base_url=&quot;https://api.perplexity.ai/chat/completions&quot;, api_key=perplexity_api_key)<br>claude_client = AsyncOpenAI(base_url=&quot;https://api.anthropic.com/v1/&quot;, api_key=claude_api_key)<br>gemini_client = AsyncOpenAI(base_url=&quot;https://generativelanguage.googleapis.com/v1beta/openai/&quot;, api_key=gemini_api_key)<br>huggingface_client = AsyncOpenAI(base_url=&quot;https://generativelanguage.googleapis.com/v1beta/openai/&quot;, api_key=hf_api_key)</pre><p>The AsyncOpenAI client is an optimal choice for production setups, as asynchronous LLM calls provide several key advantages:</p><ul><li><strong>Non-Blocking Execution:</strong> Asynchronous calls ensure the server remains responsive, as it isn’t held up waiting for a response.</li><li><strong>Task Parallelization:</strong> Multiple LLM requests can be processed simultaneously, boosting overall throughput.</li><li><strong>Enhanced Resource Utilization:</strong> Efficiently manages server resources by concurrently handling several tasks.</li><li><strong>Improved Scalability:</strong> Better equipped to handle high loads and scale as demand increases.</li><li><strong>Faster User Experience:</strong> Reduces wait times, leading to quicker responses and improved user satisfaction.</li></ul><p><strong>2.2. Declaring an LLM model</strong></p><p>The Agents SDK comes with out-of-the-box support for OpenAI compatible models in two flavors:</p><ul><li><a href="https://openai.github.io/openai-agents-python/ref/models/openai_responses/#agents.models.openai_responses.OpenAIResponsesModel">OpenAIResponsesModel</a>, which calls OpenAI APIs using the new <a href="https://platform.openai.com/docs/api-reference/responses">Responses API</a>.</li><li><a href="https://openai.github.io/openai-agents-python/ref/models/openai_chatcompletions/#agents.models.openai_chatcompletions.OpenAIChatCompletionsModel">OpenAIChatCompletionsModel</a>, which calls OpenAI APIs using the <a href="https://platform.openai.com/docs/api-reference/chat">Chat Completions API</a>.</li></ul><p>Below is an example of agent objects instantiation with different LLM providers:</p><pre>from agents import Agent, OpenAIChatCompletionsModel ,OpenAIResponsesModel<br>claude_agent = Agent(<br>    name=&quot;Claude agent&quot;,<br>    instructions=&quot;You only respond to queries about code refactoring queries.&quot;,<br>    model=OpenAIChatCompletionsModel( <br>        model=&quot;claude-3-7-sonnet-20250219&quot;,<br>        openai_client=claude_client,<br>    ),<br>)<br><br>perplexity_agent = Agent(<br>    name=&quot;Perplexity agent&quot;,<br>    instructions=&quot;You only respond to queries about documentation search.&quot;,<br>    model=OpenAIResponsesModel( <br>        model=&quot;sonar-deep-research&quot;,<br>        openai_client=perplexity_client,<br>    ),<br>)</pre><p>While OpenAI SDK supports both the OpenAIResponsesModel and the OpenAIChatCompletionsModel, we recommend using a single model shape per workflow.</p><p>Each model shape offers a distinct set of features and tools, so mixing them can lead to inconsistencies. If you must combine model shapes, ensure that every feature you require is supported across both.</p><p><strong>2.3. Known limitations with other LLM providers</strong></p><ul><li><strong>Tracing client 401 error:</strong> If none of the Agents uses OpenAI client, a 401 exception can occur.</li><li><strong>Absence of support for structured output</strong></li></ul><p><a href="https://openai.github.io/openai-agents-python/models/">This documentation</a> provides several strategies to overcome these issues.</p><h3>3. Tracing agents for a better observability</h3><p>The Agents SDK features robust built-in tracing that logs every significant event during an agent run — including LLM generations, tool calls, handoffs, guardrails, and even custom events. With <a href="https://platform.openai.com/traces">the Traces dashboard</a>, you can efficiently debug, visualize, and monitor your workflows throughout development and production.</p><p>To showcase some of the tracing features, let’s consider the multi-agent system below specialized in coding:</p><pre>from agents import Agent, Runner, AsyncOpenAI, OpenAIChatCompletionsModel<br><br>deepseek_client = AsyncOpenAI(base_url=&quot;https://api.deepseek.com&quot;, api_key=deepseek_api_key)<br>perplexity_client = AsyncOpenAI(base_url=&quot;https://api.perplexity.ai/chat/completions&quot;, api_key=perplexity_api_key)<br>claude_agent = AsyncOpenAI(base_url=&quot;https://api.anthropic.com/v1/&quot;, api_key=claude_api_key)<br><br><br>bugs_agent = Agent(<br>    name=&quot;Deepseek agent&quot;,<br>    instructions=&quot;You only respond to queries about bugs detection.&quot;,<br>    model=OpenAIChatCompletionsModel( <br>        model=&quot;deepseek-chat&quot;,<br>        openai_client=deepseek_client,<br>    ),<br>)<br><br>documentation_agent = Agent(<br>    name=&quot;Perplexity agent&quot;,<br>    instructions=&quot;You only respond to queries about documentation search.&quot;,<br>    model=OpenAIChatCompletionsModel( <br>        model=&quot;sonar-deep-research&quot;,<br>        openai_client=perplexity_client,<br>    ),<br>)<br><br>code_refactoring_agent = Agent(<br>    name=&quot;Claude agent&quot;,<br>    instructions=&quot;You only respond to queries about code refactoring queries.&quot;,<br>    model=OpenAIChatCompletionsModel( <br>        model=&quot;claude-3-7-sonnet-20250219&quot;,<br>        openai_client=claude_agent,<br>    ),<br>)<br><br>triage_agent = Agent(<br>    name=&quot;Openai agent&quot;,<br>    instructions=&quot;Handoff to the appropriate agent based on the user query.&quot;,<br>    handoffs=[bugs_agent, documentation_agent, code_refactoring_agent],<br>    model=&quot;gpt-4o-2024-08-06&quot;,<br>)<br><br>messy_code = &quot;&quot;&quot;<br>a = &quot;a&quot;<br>b = &quot;b&quot;<br>c = &quot;c&quot;<br>l = [a, b, c]<br>&quot;&quot;&quot;<br><br>result = await Runner.run(triage_agent, input=f&quot;Refactor the following code:\n{messy_code}&quot;)<br>print(result.final_output)</pre><p>The triage_agent is running on OpenAI client by default. Ensure ensure you set the OPENAI_API_KEY environment variable using this command:</p><pre>export OPENAI_API_KEY=sk-...</pre><p>After running these command (in a Notebook for instance), we can see what exactly happened by accessing the <a href="https://platform.openai.com/traces">Tracing Dashboard</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fC0mo7OKvwZvxDzvTlextw.png" /><figcaption>snapshot from tracings showing query handoff from gpt-4o-2024–08–06 model to claude-3–7-sonnet-20250219</figcaption></figure><p>The screenshot above shows successful handoff of the code refactoring task from GPT-4o model to Claude-3.7-sonnet. It should be mentioned that depending on the situation, the triage agent may execute the task itself or delegate it to the wrong agent. Hence it’s important to craft detailed instructions for every agent, especially the triage one. Also it’s recommended to choose a more advanced model for this orchestration agent. For instance, we noticed that GPT-4o performs better than GPT-3.5 for this scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vT0KyaThk6sVf8DiakbY4w.png" /><figcaption>Logs showing task execution by claude-3–7-sonnet-20250219</figcaption></figure><p>The logs above show the task transfer from the triage agent to Claude agent. This is great tool for debugging and understanding what’s going on under the hoods in complex agents setup.</p><p><strong>Important:</strong> When using the OpenAI SDK, some of its tracing features (like generation_span() and function_span) record detailed information — including sensitive inputs and outputs. This can be risky if you’re working with private data. To protect confidentiality, disable these traces by setting RunConfig.trace_include_sensitive_data to false. Alternatively, consider switching to another tracing tool that doesn’t capture sensitive data.</p><h3>4. Considerations for production systems</h3><p>OpenAI Agents SDK is an interesting alternative to libraries like <a href="https://www.anthropic.com/engineering/building-effective-agents">LangChain and LanGraph</a>. It provides ready-to-use tools to orchestrate agents with minimal abstraction and a focus on simplicity, while supporting integration with a wide range of other LLM providers.</p><p>One of its key features is the built-in tracing tool, which offers detailed logging and debugging. This transparency allows developers to clearly see the sequence of LLM instructions and their outcomes, making it easier to fine-tune behavior and ensure smooth operation.</p><p>While the OpenAI Agents SDK offers many advantages, there are a few limitations to consider during prototyping and production deployment:</p><ul><li><strong>Memory Management:</strong><br>The current solution lacks robust short-term and long-term memory management. Although OpenAI provides some memory tools, relying solely on them could lead to vendor lock-in — a significant risk if you need flexibility or wish to avoid dependency on a single stack.</li><li><strong>Tracing Dashboard:</strong><br>The tracing dashboard is hosted on OpenAI servers, which may not be suitable for environments that handle sensitive data, as it could expose confidential information.</li><li><strong>LLM Orchestration Precision:</strong><br>Orchestrating via an LLM is not always precise. In many cases, relying on code-based orchestration <a href="https://openai.github.io/openai-agents-python/multi_agent/">can offer better control and reliability</a>.</li></ul><p>Addressing these challenges early on is crucial to ensure a robust, flexible, and secure deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c80185b3cc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to serve Deepseek flagship models for inference with vLLM and TGI using OpenAI SDK]]></title>
            <link>https://medium.com/@amri369/how-to-serve-deepseek-flagship-models-for-inference-with-vllm-and-tgi-using-openai-sdk-176b6cb801ef?source=rss-c62450552611------2</link>
            <guid isPermaLink="false">https://medium.com/p/176b6cb801ef</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Mohamed Amri]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 09:33:48 GMT</pubDate>
            <atom:updated>2025-02-03T09:33:48.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Fcx5Hj4arnRutdDlmkUVw.jpeg" /></figure><pre>from openai import OpenAI<br><br>client = OpenAI(api_key=&quot;&lt;api-key&gt;&quot;, base_url=&quot;&lt;openai-compatible-url&gt;&quot;)</pre><p>One single line of code. That’s all it takes to serve Deepseek models (or any open-source LLM) using the OpenAI SDK and benefit from all the features / maintenance provided by OpenAI and the open-source community.</p><p>This approach enables developers to serve open-source models for downstream applications without the hassle of managing API requests.</p><p>It turns out that this pattern is adopted by many technology providers across languages like Python, NodeJS, and Go:</p><ul><li><a href="https://api-docs.deepseek.com/">DeepSeek</a></li><li><a href="https://huggingface.co/playground?modelId=deepseek-ai/DeepSeek-R1-Distill-Qwen-32B">Hugging Face</a></li><li>Perplexity AI</li><li>And many others</li></ul><p>But to get to this point, you first need to self-deploy a suitable Deepseek model for inference in your production environment.</p><p>The content of the article is the following:</p><ol><li>Introducing Deepseek models</li><li>A high-level architecture for LLM based applications</li><li>Inference with vLLM and TGI</li><li>Building on top of OpenAI SDK</li></ol><h3>1. Introducing Deepseek models</h3><p>In this section, we will present a high-level description of Deepseek models introduced in <a href="https://github.com/deepseek-ai/DeepSeek-V3/blob/main/DeepSeek_V3.pdf">this paper</a>. These models come in two different flavors:</p><ul><li>Dense models with 685B parameters: <a href="https://huggingface.co/deepseek-ai/DeepSeek-R1">Deepseek-R1</a> and <a href="https://huggingface.co/deepseek-ai/DeepSeek-V3">Deepseek-V3</a>.</li><li>Distilled models with 1.5B, 8B, 32B and 70B. More details about model cards can be found <a href="https://huggingface.co/models?search=deepseek-ai/deepseek">here</a>.</li></ul><p>These models are based on the same decoder-autoregressive <a href="https://arxiv.org/abs/1706.03762">transformers architecture</a> introduced in 2017 by Google. However, the authors developed an innovative training paradigm that uses Reinforcement Learning to enforce models to “reason” during the training process. The authors claim that they achieved a performance on par with closed-source providers like OpenAI and Claude. Below is a snapshot of a comparison using traditional benchmarks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gRc42yTLllf2zFx_JTQlQ.png" /><figcaption>Benchmark of Deepseek models (<a href="https://github.com/deepseek-ai/DeepSeek-V3/blob/main/DeepSeek_V3.pdf">source</a>)</figcaption></figure><p>In the following section, we will explore how to effectively deploy open-source LLMs in production environments, focusing on using libraries such as vLLM and Text Generation Inference (TGI).</p><p>These tools are designed to optimize LLM deployment, provided you have the necessary hardware and software infrastructure.</p><h3>2. High-level Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PPSqVj4bFPHvjKQO-nUFw.png" /><figcaption>High Level Architecture for AI-based apps</figcaption></figure><p>The diagram above highlights a typical architecture for AI-based applications. It’s important to note that the application server primarily handles user requests, API integrations, and delivering results from AI processing.</p><p>The LLM inference service is separated from the application service, as it has different hardware and software infrastructure requirements. Additionally, this separation enhances fault tolerance and reliability, ensuring that failures or high workloads in the AI processing layer do not impact the core application functionalities.</p><p>This solution is scalable as the application server doesn’t manage heavy tasks like LLM inference, which are fully handled by the orchestrator. The orchestrator has the ability to delegate tasks to workers and manage asynchronous workflows.</p><h3>3. Serving Deepseek models for inference</h3><p>To ensure production-ready deployments of LLMs, we recommend utilizing Docker containers for serving inference tasks. This approach facilitates horizontal scaling and allows for the integration of orchestration and load balancing tools like Kubernetes when necessary.</p><p>While Kubernetes implementation is beyond the scope of this article, we will introduce two open-source libraries — vLLM and Text Generation Inference (TGI) — that enable the creation of Docker images optimized for low-latency LLM inference, thereby reducing operational costs. We will use DeepSeek-R1-Distill-Qwen-32B as an example.</p><h4>3.1. Inference with vLLM</h4><p>An end-to-end approach for using vLLM can be found in <a href="https://medium.com/@amri369/self-host-llama-3-1-8-b-in-ec2-using-vllm-and-docker-1aefe4584b9a">this article</a>. Assuming that you have provisioned the required hardware for serving DeepSeek-R1-Distill-Qwen-32B , you can use this command to launch an instance of vLLM server (using a VM or EC2 for example):</p><pre>docker run \<br>  --runtime nvidia \<br>  --gpus all \<br>  -v ~/.cache/huggingface:/root/.cache/huggingface \<br>  --env &quot;HUGGING_FACE_HUB_TOKEN=&lt;HF_TOKEN&gt;&quot; \<br>  --env &quot;VLLM_API_KEY=&lt;VLLM_API_KEY&gt;&quot; \<br>  -p 8000:8000 \<br>  --ipc=host \<br>  vllm/vllm-openai:latest \<br>  --model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \<br>  --max_model_len 10000</pre><p>This docker run command initializes a Docker container configured for GPU-accelerated inference using the vllm-openai image. Here&#39;s a breakdown of its components:</p><ul><li><strong>--runtime nvidia</strong>: Specifies the use of NVIDIA&#39;s runtime for GPU support within the container.</li><li><strong>--gpus all</strong>: Allocates all available GPUs to the container, ensuring it can utilize the necessary hardware for processing.</li><li><strong>-v ~/.cache/huggingface:/root/.cache/huggingface</strong>: Mounts the local Hugging Face cache directory into the container, allowing shared access to pre-downloaded model files and preventing redundant downloads.</li><li><strong>--env &quot;HUGGING_FACE_HUB_TOKEN=&lt;HF_TOKEN&gt;&quot;</strong>: Sets the HUGGING_FACE_HUB_TOKEN environment variable within the container, enabling authenticated access to Hugging Face&#39;s model repository. Replace &lt;HF_TOKEN&gt; with your actual token.</li><li><strong>--env &quot;VLLM_API_KEY=&lt;VLLM_API_KEY&gt;&quot;</strong>: Sets the VLLM_API_KEY environment variable, which may be required for specific functionalities within the vllm framework. Replace &lt;VLLM_API_KEY&gt; with your actual API key.</li><li><strong>-p 8000:8000</strong>: Maps port 8000 of the container to port 8000 on the host machine, making the container&#39;s services accessible via <a href="http://localhost:8000.">http://localhost:8000.</a></li><li><strong>--ipc=host</strong>: Shares the host&#39;s inter-process communication namespace with the container, which can improve performance for certain operations.</li><li><strong>vllm/vllm-openai:latest</strong>: Specifies the Docker image to use, in this case, the latest version of vllm-openai.</li><li><strong>--model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B</strong>: Indicates the specific model to load within the container.</li><li><strong>--max_model_len 10000</strong>: Sets the maximum sequence length for the model to 10,000 tokens.</li></ul><p>Once you’ve executed the command, your server will be up and running at <a href="http://localhost:8000/">http://localhost:8000</a>. This server is designed to be compatible with OpenAI’s API, allowing you to seamlessly use OpenAI’s SDKs and tools with it.</p><p>To ensure secure access to your server, it’s important to generate a secret API key. This key will help protect your endpoint from unauthorized use.</p><p>For those interested in enhancing the server’s capabilities, vLLM offers a “reasoning mode.” This feature enables the model to provide detailed reasoning steps along with its answers, offering deeper insights into its decision-making process. To learn more about enabling and using this mode, you can refer to the <a href="https://docs.vllm.ai/en/latest/features/reasoning_outputs.html">vLLM Reasoning Outputs documentation</a>.</p><h4>3.1. Inference with TGI</h4><p>Similarly to vLLM, you can run a Docker container using <a href="https://github.com/huggingface/text-generation-inference?tab=readme-ov-file#docker">the official TGI Docker image</a>:</p><pre>docker run \<br>  --gpus all \<br>  --shm-size 1g \<br>  -p 8000:80 \<br>  -v ~/.cache/huggingface:/data \<br>  -e HF_TOKEN=&lt;your_huggingface_token&gt; \<br>  ghcr.io/huggingface/text-generation-inference:2.0 \<br>  --model-id deepseek-ai/DeepSeek-R1-Distill-Qwen-32B</pre><p>Once executed, the server will be accessible at <a href="http://localhost:8000.">http://localhost:8000</a>. This server is also OpenAI-compatible.</p><h3>4. Integration with OpenAI SDK in downstream applications</h3><p>Now that you have successfully deployed DeepSeek-R1-Distill-Qwen-32B locally, let’s explore how to integrate it into your downstream application using the OpenAI SDK. But first, let’s understand why this is important.</p><h4>4.1. Why using the OpenAI SDK is an optimal choice</h4><p>Below is a non-exhaustive list of benefits:</p><ul><li><strong>Switch from OpenAI to Open-Source Models:</strong> Imagine you have built an application using the OpenAI API. Later, you may want to experiment with or fully transition to an open-source model. With the OpenAI-compatible endpoints deployed via vLLM and TGI, you can switch seamlessly.</li><li><strong>Asynchronous Operations:</strong> Use async/await to perform non-blocking calls, which significantly improves efficiency in concurrent environments.</li><li><strong>Streaming Support:</strong> The SDK supports real-time token streaming, enhancing the user experience by delivering output as it’s generated.</li><li><strong>Unified API Interface:</strong> Enjoy a consistent interface for both synchronous and asynchronous operations, simplifying integration and maintenance across various parts of your application.</li><li><strong>Robust Error Handling:</strong> Built-in error management with automatic retries minimizes disruptions, even when network issues occur.</li><li><strong>Scalability and Flexibility:</strong> With configurable options for timeouts, logging, and rate limiting, your application can easily scale to handle high volumes of requests.</li><li><strong>Ease of Transition:</strong> The SDK’s design minimizes vendor lock-in, making it easier to transition between proprietary and open-source models without overhauling your codebase.</li></ul><h4>4.2. How to use the OpenAI SDK</h4><p>In this article, we have shown how to deploy an OpenAI-compatible server using vLLM and TGI. This setup allows you to experiment with open-source models like DeepSeek-R1-Distill-Qwen-32B seamlessly, while also maintaining compatibility with applications built for the OpenAI API.</p><p>Python:</p><pre># Please install OpenAI SDK first: `pip3 install openai`<br><br>from openai import OpenAI<br><br>client = OpenAI(api_key=&quot;&lt;api-key-if-applicable&gt;&quot;, base_url=&quot;http://localhost:8000&quot;)<br><br>response = client.chat.completions.create(<br>    model=&quot;DeepSeek-R1-Distill-Qwen-32B&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Tell me story.&quot;},<br>    ],<br>    stream=False<br>)<br><br>print(response.choices[0].message.content)</pre><p>NodeJS</p><pre>// Please install OpenAI SDK first: `npm install openai`<br><br>import OpenAI from &quot;openai&quot;;<br><br>const openai = new OpenAI({<br>        baseURL: &#39;http://localhost:8000&#39;,<br>        apiKey: &#39;&lt;api-key-if-applicable&gt;&#39;<br>});<br><br>async function main() {<br>  const completion = await openai.chat.completions.create({<br>    messages: [{ role: &quot;system&quot;, content: &quot;You are a helpful assistant.&quot; }],<br>    model: &quot;DeepSeek-R1-Distill-Qwen-32B&quot;,<br>  });<br><br>  console.log(completion.choices[0].message.content);<br>}<br><br>main();</pre><p>CURL</p><pre>curl http://localhost:8000 \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer &lt;api-key-if-applicable&gt;&quot; \<br>  -d &#39;{<br>        &quot;model&quot;: &quot;DeepSeek-R1-Distill-Qwen-32B&quot;,<br>        &quot;messages&quot;: [<br>          {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;},<br>          {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Tell me joke!&quot;}<br>        ],<br>        &quot;stream&quot;: false<br>      }&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=176b6cb801ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Analysis of YC’s AI Investment Strategy]]></title>
            <link>https://medium.com/@amri369/an-analysis-of-ycs-ai-investment-strategy-73aae99217a8?source=rss-c62450552611------2</link>
            <guid isPermaLink="false">https://medium.com/p/73aae99217a8</guid>
            <dc:creator><![CDATA[Mohamed Amri]]></dc:creator>
            <pubDate>Thu, 15 Aug 2024 09:14:40 GMT</pubDate>
            <atom:updated>2024-08-21T15:27:30.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS2TcxHw9Zljpm9eANcA6A.png" /></figure><h3>1. Summary</h3><p>Over the past 18 months, AI has dominated the technology conversation, particularly following the release of GPT-3.5 by OpenAI. The tech community — both technical experts and managerial leaders — has split into two camps:</p><ul><li>The optimists, who are deeply investing in and developing AI technologies</li><li>The skeptics, who warn that the AI hype could follow the same path as the recent Cryptocurrency crisis and the Dot Net bubble.</li></ul><p>In this article, we will focus on hard data and investment trends within the AI sector. Y Combinator (YC) will serve as a key indicator of these market trends, given its significant influence on the U.S. tech startup ecosystem. Over the past two decades, YC has played a pivotal role in shaping the technology landscape. All the data used here is publicly available at <a href="https://www.ycombinator.com/companies?batch=S24&amp;batch=W24&amp;tags=AI">YC website</a>.</p><p>This content is especially valuable for:</p><ul><li><strong>Tech Founders:</strong> Gain inspiration and insights into emerging trends and ideas that could attract investor interest. We emphasize commonly saturated ideas in the market — those that may not be worth pursuing, as there’s no need to reinvent the wheel.</li><li><strong>Investors:</strong> Discover market trends and access a clear, technical benchmark to help refine your investment strategy in early-stage AI startups.</li></ul><p><strong>Disclaimer</strong>: It’s important to note that most of the startups in this study are in the early stages (pre-seed and seed), having been founded in 2023 or 2024, and typically have small teams consisting of 2–3 founders. Additionally, it’s crucial to remember that our primary goal is to analyze investment dynamics in the AI sector. Therefore, this study may not necessarily reflect the situation for startups that have not yet raised funds or are not specialized in AI.</p><h3>2. Historical evolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D75IorKbX4iZO1clLVmfzA.png" /><figcaption>AI investment evolution with YC from 2020 to 2024</figcaption></figure><p>The chart illustrates a clear upward trend in the share of AI companies within the total YC batches from 2020 to 2024.</p><ul><li><strong>2020</strong>: AI companies constituted just under 4% of the total startups, indicating a relatively modest interest in AI at the time.</li><li><strong>2021</strong>: The share increased to around 5.6% (probably statistically non-significant), suggesting a growing recognition of AI’s potential but still at a cautious pace.</li><li><strong>2022</strong>: The trend gained momentum, with AI companies making up over 10% of the total, reflecting a significant shift as more investors and founders began to see AI as a critical area for innovation and growth.</li><li><strong>2023</strong>: This year marked a substantial leap, with AI companies representing nearly 25% of the total startups, demonstrating a robust surge in AI-related investments and a broader acceptance of AI as a transformative technology.</li><li><strong>2024</strong>: The upward trajectory continued, with AI companies comprising over 31% of the total, solidifying AI’s dominant position in the tech investment landscape.</li></ul><p>This progression demonstrates the increasing confidence in AI’s potential to drive future innovation and economic value, as well as a more focused allocation of resources towards AI startups by investors and tech leaders.</p><h3>3. Statistical Analysis</h3><p>The figure below illustrates the distribution of startup categories in the YC 2024 batch. It is evident that the number of startups in the deep tech sector is relatively low, particularly in the Infrastructure and Engineering categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUdC4BONsKIwS5FSoQC03Q.png" /><figcaption>Startups categories for YC 2024 batch</figcaption></figure><p><strong>Infrastructure:</strong></p><p>Only three startups received funding in this area. This can be attributed to the inherent challenges and high risks associated with the sector. The difficulty of securing specialized and affordable talent presents a significant barrier for early-stage startups. Moreover, the financial burden of these projects is substantial. For example, developing an AI chip to compete with established players like Nvidia is not only prohibitively expensive but also fraught with considerable risk.</p><p><strong>Engineering, Product and Design:</strong></p><p>This category includes startups focused on developing software tools, such as developer copilots and MLOps platforms for training and serving large language models (LLMs). Investment in this category has remained stable, with 20 startups funded in 2023 and 21 in 2024. Notably, there has been a significant increase in startups developing AI agents — autonomous systems designed to perform tasks, make decisions, and interact with their environments.</p><p>It’s worth noting that MLOps for LLM orchestration, both in public clouds and on-premises solutions, is already a well-covered space with numerous startups outside the YC ecosystem. This raises an important question: Why is YC continuing to invest in such a crowded and competitive area?</p><p>Additionally, there is a noticeable decline in investment in foundational models. <a href="https://arxiv.org/abs/1706.03762">The foundational Transformers architecture</a>, introduced by Google in 2017, continues to underpin state-of-the-art LLMs. As this technology is open-source and highly effective, major players are now shifting their focus toward acquiring high-quality proprietary datasets and investing in infrastructure, rather than developing new foundational models.</p><p><strong>Downstream Applications:</strong></p><p>This category includes startups focused on developing use cases that leverage LLMs as their core technology. It encompasses all startups creating wrappers around LLMs, whether using closed-source models like ChatGPT, Claude, and Gemini, or open-source models like Mistral, LLaMA, and Falcon, which may be used as-is or fine-tuned.</p><p>Investment in this category rose from 73% of all AI investments in 2023 to 83% in 2024. Healthcare, Finance, and Fintech have seen the most significant gains from YC investments, despite these sectors being heavily regulated. This focus is likely driven by the increasing maturity of LLMs. Meanwhile, investment in B2C apps remains low, as YC primarily targets the B2B sector.</p><p>It’s also worth noting that certain industries, such as Oil and Gas and other traditional sectors, have yet to see significant YC investment. This is likely due to the challenges in acquiring proprietary data in these areas and the difficulties associated with scaling such ventures.</p><h3>4. Regional investments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFShrGLfFC80D54gL0grRQ.png" /><figcaption>Regional distribution of YC investments in 2023 and 2024</figcaption></figure><p><strong>a- Main Investment Regions:</strong></p><ul><li><strong>America/Canada</strong>: Dominates the investment landscape with <strong>193 startups</strong>, accounting for <strong>67.0%</strong> of the total investments. This highlights a strong focus on the US market, which continues to be a primary hub for innovation and startup growth.</li><li><strong>Remote</strong>: Represents the second-largest investment category with <strong>75 startups</strong> (<strong>26.0%</strong>), reflecting a growing trend towards decentralized and location-agnostic ventures.</li></ul><p><strong>b- Secondary Investment Region:</strong></p><ul><li><strong>Europe</strong>: With <strong>16 startups</strong> (<strong>5.6%</strong> of the total), Europe ranks as the third most significant region for investment, reflecting a noticeable, though comparatively smaller, focus on the European market. Despite Europe’s strong talent pools, particularly in countries like France, YC’s strategy appears to deprioritize these regions. The stringent regulatory environment in Europe likely hinders its attractiveness to top investors, making it a less favorable destination for significant investment compared to other regions.</li></ul><p><strong>c- Minimal Investment Regions:</strong></p><ul><li><strong>South Asia</strong>: Only <strong>2 startups</strong> received funding, representing <strong>0.7%</strong> of the total.</li><li><strong>Latin America</strong> and <strong>Middle East and North Africa</strong>: Each region received investment in just <strong>1 startup</strong> (accounting for <strong>0.3%</strong> each), showing minimal engagement. Notably, the investment in the Middle East is limited to a single Israeli startup, underscoring the lack of broader regional involvement.</li></ul><p><strong>d- Negligible or No Investment:</strong></p><ul><li><strong>Africa</strong> and <strong>Southeast Asia</strong>: These regions received no investments, reflecting an almost complete lack of focus on these areas.</li></ul><h3>5. Key takeaways</h3><ul><li><strong>Low Investment in Infrastructure</strong>: Investment in infrastructure remains limited, as this area is highly challenging and presents greater risks. The complexity, high costs, and specialized talent required make it a less attractive option for early-stage investors.</li><li><strong>Cautious Investment in Software Tools</strong>: Investment in software tools, including copilots and models, is progressing carefully. There is a notable absence of investment in foundational models, which are now open-sourced and widely established. These technologies are crucial, but their value is dependent on their application in downstream solutions.</li><li><strong>Focus on Downstream Applications</strong>: Investment is increasingly shifting towards downstream applications, which represent the most promising area for growth. However, there are still significant opportunities in underexplored sectors such as law, banking, oil and gas, and other traditional industries. These areas present untapped potential for innovation and investment.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73aae99217a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-host Llama 3.1 8 B in EC2 using VLLM and Docker]]></title>
            <link>https://medium.com/@amri369/self-host-llama-3-1-8-b-in-ec2-using-vllm-and-docker-1aefe4584b9a?source=rss-c62450552611------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aefe4584b9a</guid>
            <dc:creator><![CDATA[Mohamed Amri]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 06:29:30 GMT</pubDate>
            <atom:updated>2024-08-13T07:23:06.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRzGIg-iAKAuKG_gEl9haw.jpeg" /><figcaption>Llama 3.1 8 B in an open-source model used for text generation</figcaption></figure><h3>Summary</h3><p><a href="https://ai.meta.com/research/publications/the-llama-3-herd-of-models/">Llama 3.1 herd of models</a> has gained a considerable amount of attention in the open-source community given the models capabilities to achieve state-of-the-art performance compared to commercial models.</p><p>There is currently a lack of documentation on self-hosting these models for inference, which is crucial for on-premises applications. In fields like healthcare and law, data classification often involves sensitive and confidential information that is heavily regulated. A data breach can result in significant financial costs and damage to an organization’s reputation.</p><p>Consequently, in these applications, communicating with an external API is prohibited to ensure data security and compliance.</p><p>In this article, we will guide you through deploying the Llama 3.1 8B model for inference on an EC2 instance using a VLLM Docker image. <a href="https://github.com/vllm-project/vllm">VLLM</a> is an open-source library designed specifically for deploying and serving large language models (LLMs).</p><p>This approach can also be adapted for deployment on other cloud infrastructures like Azure VMs or on-premises environments.</p><p>The content of the article is the following:</p><p>1. Model architecture</p><p>2. Deployment of Llama 3.1 8B on EC2</p><p>3. Inference using Python and CURL</p><p>4. Scalability and security considerations</p><h3>1. Model architecture</h3><p>All Llama 3.1 models use an Autoregressive Decoder similarly to the architecture in <a href="https://arxiv.org/abs/1706.03762">Attention is All you Need paper</a>.</p><p>It’s important to note that the only architectural improvements introduced in Llama 3.1 compared to Llama 1 and 2 are:</p><ul><li>Grouped Query Attention to optimize for inference</li><li>Attention Mask to improve training</li></ul><p>The architecture of the three models 8B, 70B and 405B is depicted in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zizj41cf7rNTLyT9B_-sqw.png" /><figcaption>Source: <a href="https://ai.meta.com/research/publications/the-llama-3-herd-of-models/">Meta</a></figcaption></figure><p>In the following sections, we will only focus on the inference of the smallest model of Llama 3.1 which has the following properties:</p><ul><li>Trainable parameters: 8B</li><li>Attention heads: 32</li><li>Number of layers (self-attention | FNN blocks): 32</li><li>Context window: 128,000 tokens</li></ul><p>Model fine-tuning and training are out of the scope of this article.</p><h3>2. Deployment of Llama 3.1 8B on EC2</h3><h4>2.1. Scope:</h4><p>In this article we will focus on deploying a FastAPI endpoint to serve Llama 3.1 8B for inference.</p><p>Even though we use an API token to protect the access to the serve endpoints, we only cover HTTP data exchange which means that data is not encrypted when invoking the endpoints.</p><p>HTTPS and other security measures are required in production.</p><h4>2.2. Prerequisites:</h4><p>To reproduce this tutorial, you need the following:</p><ul><li>An AWS account</li><li>Access to one of these EC2 instances: G4dn, G5, G6, Gr6, P4, P4de, P5. This is needed given the intensive resources required to deploy model’s weights and to store KV cache. Follow <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-resource-limits.html">this guide</a> to manage your AWS quota.</li><li>HuggingFace API Key: find instructions <a href="https://huggingface.co/docs/hub/en/security-tokens">here</a></li><li>Python interpreter like Pycharm</li></ul><h4>2.2. Create an EC2 instance:</h4><p>We will follow a similar workflow than <a href="https://medium.com/@chinmayd49/self-host-llm-with-ec2-vllm-langchain-fastapi-llm-cache-and-huggingface-model-7a2efa2dcdab">this article</a>. The first step consists in searching for EC2 then click on EC2 as shown below.</p><figure><img alt="Searrch for EC2 in AWS Cloud" src="https://cdn-images-1.medium.com/max/1024/1*PVppW9W3nsNFeJXxIGDSAw.png" /><figcaption>Step 1: Search for EC2 in search tool bar</figcaption></figure><p>Once you land in EC2 workspace, click on Launch instance as depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Pe5vt4M228uzHW4tm6seWA.png" /><figcaption>Step 2: Launch instance</figcaption></figure><p>Then fill all the mandatory fields like instance name. In this tutorial, we will use <em>vllm-server</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9arqs4T8bXad6Cy-q7G0rA.png" /><figcaption>Step 3: Setup instance name</figcaption></figure><p>Step 4 consists on selecting the operating system that will be used to run the EC2 instance. Type <em>deep learning</em> in the seearch bar and select Deep Learning OSS Nvidia AMI GPU Pytorch 2.3 (Amazon Linux 2). This instance comes with Python, Pytorch and Cuda driver versions that will be suitable to run any LLM training or inference. However this is not mandatory as we will use VLLM and Docker removing any external dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETWtKZNBAlYqO4w9izcv4Q.png" /><figcaption>Step 4: Choose OS</figcaption></figure><p>Step 5 is very important as we will need to select the compute needed to run the LLM instance. Since Llama 3.1 has a large context window, we will need an instance with GPUs and large GPU memory to handle the KV cache. For the sake of this demo, we will select <em>g5.2xlarge</em> Amazon Machine Image. Make sure to shutdown this instance after testing to avoid unnecessary costs related to infrastructure usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qozmw8d0c9xz30S9tc6UOA.png" /><figcaption>Step 5: Select g5.2xlarge AMI</figcaption></figure><p>In step 6, create a new key pair to access the EC2 instance via SSH. You can name it <em>vllm-server </em>for instance. Once created, make sure sure to download the <em>vllm-server.pem</em> file and store it in a safe folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PNvws_G56RTmlWNaYnDwA.png" /><figcaption>Step 6: Create key pair</figcaption></figure><p>In step 7, enable SSH, HTTP and HTTPS accesses in the security groups settings. This will be needed to setup and experiment the LLM endpoint for inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hbc4q43rUcnMDCqLgqQbfA.png" /><figcaption>Step 7: Security groups</figcaption></figure><p>In step 8, set storage to 50 GB or more so we have enough space for the Docker container instance and model weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNCaVBZBfMNUbNZ4ryDCHA.png" /><figcaption>Step 8: Storage configuration</figcaption></figure><p>Finally, click on Launch instance until you see the message below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3ry4OvR09h7JYfay-A1Lw.png" /><figcaption>Instance successfully instantiated</figcaption></figure><h4>2.3. Run a Docker container using official VLLM image:</h4><p>Before executing this step, you need to generate an API key so you can securely access the endpoint. To do so, we will use Python’s <em>secrets</em> library which is built-in and designed for generating cryptographically strong random characters suitable for managing data such as authentication tokens.</p><pre>import secrets<br><br>def generate_api_key(length=32):<br>    return secrets.token_urlsafe(length)<br><br># Generate an API key of 32 characters<br>VLLM_API_KEY = generate_api_key()<br>print(&quot;Generated API Key:&quot;, VLLM_API_KEY)</pre><p>In the next step, we will access the EC2 instance remotely using the Linux command line. Begin by retrieving your instance’s public IP address from the EC2 dashboard within your AWS Management Console. Next, navigate to the directory containing your SSH key file, <em>vllm-server.pem</em>. To establish a secure connection, open your terminal and execute the following command:</p><pre>ssh -i &quot;vllm-server.pem&quot; ec2-user@&lt;Public IPv4 DNS&gt;</pre><p>Once you are logged in, you will see something like this:</p><pre>  ,     #_<br>   ~\_  ####_        Amazon Linux 2<br>  ~~  \_#####\<br>  ~~     \###|       AL2 End of Life is 2025-06-30.<br>  ~~       \#/ ___<br>   ~~       V~&#39; &#39;-&gt;<br>    ~~~         /    A newer version of Amazon Linux is available!<br>      ~~._.   _/<br>         _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.<br>       _/m/&#39;           https://aws.amazon.com/linux/amazon-linux-2023/<br><br>=============================================================================<br>AMI Name: Deep Learning OSS Nvidia Driver AMI GPU PyTorch 2.3.0 (Amazon Linux 2) <br>Supported EC2 instances: G4dn, G5, G6, Gr6, P4, P4de, P5<br>* To activate pre-built pytorch environment, run: &#39;source activate pytorch&#39;</pre><p>Then run this command to run a Docker container based on VLLM official docker image using the command below. Don’t forget to replace HF_TOKEN by your HuggingFace token and VLLM_API_KEY by your secure API key generated earlier.</p><pre>docker run \<br>  --runtime nvidia \<br>  --gpus all \<br>  -v ~/.cache/huggingface:/root/.cache/huggingface \<br>  --env &quot;HUGGING_FACE_HUB_TOKEN=&lt;HF_TOKEN&gt;&quot; \<br>  --env &quot;VLLM_API_KEY=&lt;VLLM_API_KEY&gt;&quot; \<br>  -p 8000:8000 \<br>  --ipc=host \<br>  vllm/vllm-openai:v0.5.3.post1 \<br>  --model meta-llama/Meta-Llama-3.1-8B \<br>  --max_model_len 10000</pre><p>Now let’s breakdown this command:</p><ul><li><strong>--runtime nvidia</strong>: Specifies the NVIDIA runtime, enabling the use of NVIDIA GPUs within the Docker container for tasks that require significant computational power.</li><li><strong>--gpus all</strong>: Allows the container to access all available GPUs on the host machine, essential for GPU-accelerated processes.</li><li><strong>-v ~/.cache/huggingface:/root/.cache/huggingface</strong>: Mounts the host machine’s Hugging Face cache directory inside the container, facilitating faster access to frequently used model data.</li><li><strong>--env &quot;HUGGING_FACE_HUB_TOKEN=&lt;HF_TOKEN&gt;&quot;</strong>: Sets an environment variable for the Hugging Face Hub token, necessary for authenticating and downloading models securely.</li><li><strong>--env &quot;VLLM_API_KEY=&lt;VLLM_API_KEY&gt;&quot;</strong>: Configures an API key for accessing specific APIs that require authentication, ensuring secure API communication.</li><li><strong>-p 8000:8000</strong>: Maps port 8000 on the host to port 8000 on the container, making the application hosted inside the container accessible at localhost:8000.</li><li><strong>--ipc=host</strong>: Uses the host’s IPC namespace, important for applications that need extensive process communication, like those running large-scale machine learning models.</li><li><strong>vllm/vllm-openai:v0.5.3.post1</strong>: Utilizes the vllm/vllm-openai Docker image with the version v0.5.3.post1, which includes all necessary software and libraries for the application.</li><li><strong>--model meta-llama/Meta-Llama-3.1-8B</strong>: Specifies which machine learning model to load and use within the application, targeting efficient and specific model operations.</li><li><strong>--max_model_len 10000</strong>: Sets a parameter that limits the model to a maximum length of 10,000, optimizing performance and resource allocation within operational constraints.</li></ul><p>Note that we are setting the maximum number of tokens to 10,000 for experimental purposes using the parameter max_model_len. Although the model&#39;s context window is 128,000, we are still limited by the GPU memory of the available machine.</p><p>Upon successful execution of the command, you will see the following screen at the end:</p><pre>Loading safetensors checkpoint shards:   0% Completed | 0/4 [00:00&lt;?, ?it/s]<br>Loading safetensors checkpoint shards:  25% Completed | 1/4 [00:00&lt;00:01,  1.74it/s]<br>Loading safetensors checkpoint shards:  50% Completed | 2/4 [00:01&lt;00:01,  1.46it/s]<br>Loading safetensors checkpoint shards:  75% Completed | 3/4 [00:01&lt;00:00,  1.96it/s]<br>Loading safetensors checkpoint shards: 100% Completed | 4/4 [00:02&lt;00:00,  1.82it/s]<br>Loading safetensors checkpoint shards: 100% Completed | 4/4 [00:02&lt;00:00,  1.78it/s]<br><br>INFO 08-07 05:21:29 model_runner.py:692] Loading model weights took 14.9888 GB<br>INFO 08-07 05:21:32 gpu_executor.py:102] # GPU blocks: 1633, # CPU blocks: 2048<br>INFO 08-07 05:21:34 model_runner.py:980] Capturing the model for CUDA graphs. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set &#39;enforce_eager=True&#39; or use &#39;--enforce-eager&#39; in the CLI.<br>INFO 08-07 05:21:34 model_runner.py:984] CUDA graphs can take additional 1~3 GiB memory per GPU. If you are running out of memory, consider decreasing `gpu_memory_utilization` or enforcing eager mode. You can also reduce the `max_num_seqs` as needed to decrease memory usage.<br>INFO 08-07 05:21:47 model_runner.py:1181] Graph capturing finished in 12 secs.<br>WARNING 08-07 05:21:47 serving_embedding.py:170] embedding_mode is False. Embedding API will not work.<br>INFO 08-07 05:21:47 api_server.py:292] Available routes are:<br>INFO 08-07 05:21:47 api_server.py:297] Route: /openapi.json, Methods: GET, HEAD<br>INFO 08-07 05:21:47 api_server.py:297] Route: /docs, Methods: GET, HEAD<br>INFO 08-07 05:21:47 api_server.py:297] Route: /docs/oauth2-redirect, Methods: GET, HEAD<br>INFO 08-07 05:21:47 api_server.py:297] Route: /redoc, Methods: GET, HEAD<br>INFO 08-07 05:21:47 api_server.py:297] Route: /health, Methods: GET<br>INFO 08-07 05:21:47 api_server.py:297] Route: /tokenize, Methods: POST<br>INFO 08-07 05:21:47 api_server.py:297] Route: /detokenize, Methods: POST<br>INFO 08-07 05:21:47 api_server.py:297] Route: /v1/models, Methods: GET<br>INFO 08-07 05:21:47 api_server.py:297] Route: /version, Methods: GET<br>INFO 08-07 05:21:47 api_server.py:297] Route: /v1/chat/completions, Methods: POST<br>INFO 08-07 05:21:47 api_server.py:297] Route: /v1/completions, Methods: POST<br>INFO 08-07 05:21:47 api_server.py:297] Route: /v1/embeddings, Methods: POST<br>INFO:     Started server process [1]<br>INFO:     Waiting for application startup.<br>INFO:     Application startup complete.<br>INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)<br>INFO 08-07 05:21:57 metrics.py:396] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.</pre><p>This indicates that a FastAPI application is currently running on port 8000. This application includes the endpoints necessary for model inference. In the next step, we will demonstrate how to invoke these endpoints from an external source, such as your laptop.</p><p>Additionally, note that the application is logging inference usage, as evident from the line:</p><pre>INFO 08-07 05:21:57 metrics.py:396] Avg prompt throughput: 0.0 tokens/s, Avg generation throughput: 0.0 tokens/s, Running: 0 reqs, Swapped: 0 reqs, Pending: 0 reqs, GPU KV cache usage: 0.0%, CPU KV cache usage: 0.0%.</pre><h3>3. Inference using Python and CURL</h3><p>In this step we are going to invoke the endpoint. For the sake of the demo, we will use a very basic security configuration. First make sure to update your security group in the virtual Firewall of your EC2 instance. You will need to add a new rule where type is Custom TCP, port range is 8000 and IP range to0.0.0.0/0 to accept all requests from any IP address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVnQmjCIbRL24HZ4rsigeA.png" /><figcaption>Add a custom TCP</figcaption></figure><p>Once done, we will use a Python script to invoke the endpoint. But first, let’s check if the app is accessible by running the following script. Don’t forget to replace ec2_public_ip_address.</p><pre>import requests<br><br># Replace with the public IP or DNS name of your EC2 instance<br>url = &quot;http://&lt;ec2_public_ip_address&gt;:8000/version&quot;<br><br>response = requests.get(url)<br>if response.status_code == 200:<br>    print(&quot;API Version:&quot;, response.json())<br>else:<br>    print(&quot;Failed to get version. Status code:&quot;, response.status_code)</pre><p>If this is successful, you will see the following prompt:</p><pre>API Version: {&#39;version&#39;: &#39;0.5.3.post1&#39;}</pre><p>Now let’s invoke the chat completion endpoint:</p><pre>import requests<br>import json<br><br><br># Define your API URL and API Key<br>api_url = &quot;http:&lt;ec2_public_ip_address&gt;:8000/v1/completions&quot;<br><br># Define the headers<br>headers = {<br>    &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    &quot;Authorization&quot;: f&quot;Bearer {VLLM_API_KEY}&quot;<br>}<br><br># Define the payload<br><br>payload = {<br>  &quot;model&quot;: &quot;meta-llama/Meta-Llama-3.1-8B&quot;,<br>  &quot;prompt&quot;: &quot;You are a helpful assistant. Tell me a joke.&quot;,<br>  &quot;temperature&quot;: 0.7,<br>  &quot;top_k&quot;: -1,<br>  &quot;max_tokens&quot;: 500<br>}<br><br># Send the request<br>response = requests.post(api_url, headers=headers, data=json.dumps(payload))<br><br># Print the response<br>response.json()[&quot;choices&quot;][0][&quot;text&quot;]</pre><p>This one example of the outputs you may see:</p><pre>It&#39;s your turn.<br>The man was surprised when he saw the monkey dancing.<br>The old man is still in charge of the factory.<br>It&#39;s a stupid question.<br>The singer has a good voice.<br>I&#39;m not going to tell you my age.<br>The suggestion was well received.<br>I am not prepared to wait for my turn.<br>That was one of the best nights of my life.<br>The soup was lukewarm.<br>You know what happened.<br>This is a list of the names of the people that I&#39;ve met.<br>The sun doesn&#39;t set at the North Pole.<br>This is the last time you&#39;ll ever have to do that.<br>I am not going to do it.<br>I am going to write a letter to him.<br>I told him I don&#39;t like him.<br>I feel like a stranger in a strange land.<br>I&#39;m sure she&#39;s not lying.<br>The club is not yet fully matured.<br>She&#39;s not my girlfriend.<br>She&#39;s my best friend.<br>I have been trying to remember that.<br>The earthquake caused a tsunami.<br>He is a man of his word.<br>I&#39;m not very hungry.<br>The woman is talking to a man.<br>I will not give you a penny.<br>I&#39;ve been looking for this.<br>That&#39;s a very good image of a seagull.<br>I&#39;ve been thinking about that over and over.<br>I&#39;m not sure if I should go see Sue or not.<br>I need to go somewhere.<br>I&#39;ve never seen a movie with Barack Obama in it.<br>I think it&#39;s a good idea.<br>I was lucky to be able to get the job after all.<br>I&#39;ll be with you soon.<br>A man needs all the friends he can get.<br>I think that&#39;s a bad idea.<br>The &quot;Island of the Blue Dolphins&quot; was a best-selling book.<br>She is particular about the food she eats.<br>I had my reasons.<br>I haven&#39;t been here for a long time.<br>He has his own way of doing things.<br>I couldn&#39;t help but laugh at him.<br>I&#39;m worried about her.<br>I have nothing to say to him.<br>I see the forest as a place of solitude, a place to run to when you are tired of the city and its noise.<br>Have you told them?<br>Tuna is very big.<br>There&#39;s too much work to do.<br>The teacher said it would be OK.<br>I need to go home.<br>She was pleased with the outcome.<br>To me, it&#39;s obvious.<br>The sight of the sea makes me happy.</pre><p>Important note: the model still requires moderation, particularly if it is to be used in a production environment.</p><p>To use CURL, you can use this command:</p><pre>curl -X POST &quot;http://&lt;ec2_public_ip_address&gt;:8000/v1/completions&quot; \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -H &quot;Authorization: Bearer VLLM_API_KEY&quot; \<br>     -d &#39;{<br>          &quot;model&quot;: &quot;meta-llama/Meta-Llama-3.1-8B&quot;,<br>          &quot;prompt&quot;: &quot;You are a helpful assistant. Tell me a joke.&quot;,<br>          &quot;temperature&quot;: 0.7,<br>          &quot;top_k&quot;: -1,<br>          &quot;max_tokens&quot;: 500<br>         }&#39;<br><br>{&quot;id&quot;:&quot;cmpl-a27e3a65cf8d408a9cc8a50a93db3646&quot;,&quot;object&quot;:&quot;text_completion&quot;,&quot;created&quot;:1723009653,&quot;model&quot;:&quot;meta-llama/Meta-Llama-3.1-8B&quot;,&quot;choices&quot;:[{&quot;index&quot;:0,&quot;text&quot;:&quot; I don&#39;t know what to do with them. I know that I am going to regret this. I think he is a nice person. I don&#39;t think it&#39;s going to work. I&#39;m no longer a child. His prediction has come true. I&#39;m not in the mood for this. I have a new phone.\nI always come home early. He is under the weather. Your job doesn&#39;t interest me. I don&#39;t plan on staying long. It was a fine summer. Damon has a lot of friends. Don&#39;t worry about her. I have nothing to offer you. My parents told me that I could not go to the concert. I&#39;m pretty busy.\nShyam is trying to get a better job. The nurse gave the patient some water. It&#39;s great that he&#39;s working so hard. I was surprised to see him there. I had to apologize. I couldn&#39;t help hearing about it. He was arrested while trying to escape. Please make sure you keep your promise. It&#39;s a mystery to me. You need to learn to wait your turn.\nI am a Christian. You aren&#39;t listening to me. I was going to buy that. He became the \&quot;king of the hill\&quot; in the sales department. I&#39;m not sure what to do. You will not get a job in that condition. I spent the day playing cards with my uncle. I thought I might be able to help you. The dog is a nice pet. It is highly unlikely that the murderer was one of our guests.\nIt&#39;s unknown how many languages there were spoken in the world at any one time. He was sitting opposite me. They&#39;re really nice guys. That&#39;s fine, isn&#39;t it? You&#39;ve been on your own a long time. I don&#39;t want to be the only one who doesn&#39;t know how to do this. I want you to forget about it. I&#39;m hoping you can help me out. I&#39;ve seen it all before. I&#39;m sorry, but you&#39;ll have to wait.\nI love what you said. He&#39;s a nice man, but he&#39;s a bit of an idiot. You&#39;ll be OK. I think I know what you&#39;re trying to say. I am a native speaker of English. I was having lunch with her. You&#39;re a lawyer, right? I&#39;m sorry I don&#39;t know your name. I was the only one who didn&#39;t know what to do. I need to study harder.\nYou must&quot;,&quot;logprobs&quot;:null,&quot;finish_reason&quot;:&quot;length&quot;,&quot;stop_reason&quot;:null}],&quot;usage&quot;:{&quot;prompt_tokens&quot;:12,&quot;total_tokens&quot;:512,&quot;completion_tokens&quot;:500}}%</pre><h3>4. Scalability and security considerations</h3><p>VLLM and Docker offer a good compromise of packaging and orchestration capabilities to serve LLMs for inference. Users don’t need to worry about managing Python dependencies and the orchestration optimization. This is a great hands-on example that can be used for testing purposes.</p><p>Regarding scalability, this EC2 instance is a descent choice if the traffic is <a href="https://www.linkedin.com/feed/update/urn:li:activity:7224447542212587520/">less than 100 requests per second</a>. To manage a higher workload, advanced orchestration with Kubernetes is recommended.</p><p>For a more secure solution, the following measures are highly recommended:</p><ul><li>Restrict access exclusively to HTTPS requests. Although the application is safeguarded with a VLLM_API_KEY, it’s important to note that malicious actors could potentially intercept request data if it’s transmitted unencrypted. Using HTTPS ensures that all data sent to and from the server is securely encrypted, thereby protecting it from interception.</li><li>Implement advanced firewall settings to restrict IP addresses specifically according to the project’s requirements. This ensures that only authorized traffic can access the network, enhancing the security posture by minimizing potential exposure to unauthorized entities.</li><li>Rate limiting to prevent abuse of your API, such as DDoS attacks or brute force attempts. This limits how many requests a user or IP address can make in a given period.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aefe4584b9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>