-
Notifications
You must be signed in to change notification settings - Fork 26
Managed LLM (with Provider) Sample #372
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
957cd42
add provider sample for managed llms
commit111 baedc2f
rename provider service to docker model provider
commit111 5b1b1d7
fix link for model provider
commit111 0dbf9d6
refine wording for model access
commit111 9e1de3a
add in x-defang-llm
commit111 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
|
|
||
| FROM mcr.microsoft.com/devcontainers/python:alpine3.13 |
11 changes: 11 additions & 0 deletions
11
samples/managed-llm-provider/.devcontainer/devcontainer.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| { | ||
| "build": { | ||
| "dockerfile": "Dockerfile", | ||
| "context": ".." | ||
| }, | ||
| "features": { | ||
| "ghcr.io/defanglabs/devcontainer-feature/defang-cli:1.0.4": {}, | ||
| "ghcr.io/devcontainers/features/docker-in-docker:2": {}, | ||
| "ghcr.io/devcontainers/features/aws-cli:1": {} | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # Default .dockerignore file for Defang | ||
| **/__pycache__ | ||
| **/.git | ||
| **/.github | ||
| **/compose.*.yaml | ||
| **/compose.*.yml | ||
| **/compose.yaml | ||
| **/compose.yml | ||
| **/docker-compose.*.yaml | ||
| **/docker-compose.*.yml | ||
| **/docker-compose.yaml | ||
| **/docker-compose.yml | ||
| Dockerfile | ||
| *.Dockerfile |
25 changes: 25 additions & 0 deletions
25
samples/managed-llm-provider/.github/workflows/deploy.yaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| name: Deploy | ||
|
|
||
| on: | ||
| push: | ||
| branches: | ||
| - main | ||
|
|
||
| jobs: | ||
| deploy: | ||
| environment: playground | ||
| runs-on: ubuntu-latest | ||
| permissions: | ||
| contents: read | ||
| id-token: write | ||
|
|
||
| steps: | ||
| - name: Checkout Repo | ||
| uses: actions/checkout@v4 | ||
|
|
||
| - name: Deploy | ||
| uses: DefangLabs/defang-github-action@v1.2.0 | ||
| with: | ||
| config-env-vars: MODEL | ||
| env: | ||
| MODEL: ${{ secrets.MODEL }} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| .env | ||
| myenv | ||
| __pycache__/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,73 @@ | ||||||
| # Managed LLM with Provider | ||||||
|
||||||
| # Managed LLM with Provider | |
| # Managed LLM with Docker Model Runner |
Outdated
Member
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Suggested change
| This sample application demonstrates using Managed LLMs with a Provider Service, deployed with Defang. | |
| This sample application demonstrates using Docker Model Runner locally and Managed LLMs (AWS Bedrock or Google VertexAI) when deployed with Defang. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # Default .dockerignore file for Defang | ||
| **/__pycache__ | ||
| **/.direnv | ||
| **/.DS_Store | ||
| **/.envrc | ||
| **/.git | ||
| **/.github | ||
| **/.idea | ||
| **/.next | ||
| **/.vscode | ||
| **/compose.*.yaml | ||
| **/compose.*.yml | ||
| **/compose.yaml | ||
| **/compose.yml | ||
| **/docker-compose.*.yaml | ||
| **/docker-compose.*.yml | ||
| **/docker-compose.yaml | ||
| **/docker-compose.yml | ||
| **/node_modules | ||
| **/Thumbs.db | ||
| Dockerfile | ||
| *.Dockerfile | ||
| # Ignore our own binary, but only in the root to avoid ignoring subfolders | ||
| defang | ||
| defang.exe | ||
| # Ignore our project-level state | ||
| .defang |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| FROM public.ecr.aws/docker/library/python:3.12-slim | ||
|
|
||
| # Set working directory | ||
| WORKDIR /app | ||
|
|
||
| # Copy requirement files first (for better Docker cache) | ||
| COPY requirements.txt . | ||
|
|
||
| # Install dependencies | ||
| RUN pip install --no-cache-dir -r requirements.txt | ||
|
|
||
| # Copy the rest of the code | ||
| COPY . . | ||
|
|
||
| # Expose the port that Uvicorn will run on | ||
| EXPOSE 8000 | ||
|
|
||
| # Set environment variable for the port | ||
| ENV PORT=8000 | ||
|
|
||
| # Run the app with the correct module path using shell form to interpolate environment variable | ||
| CMD ["sh", "-c", "uvicorn app:app --host 0.0.0.0 --port $PORT"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| import os | ||
| import json | ||
| import logging | ||
| from fastapi import FastAPI, Form, Request | ||
| from fastapi.responses import HTMLResponse | ||
| import requests | ||
|
|
||
| app = FastAPI() | ||
|
|
||
| # Configure basic logging | ||
| logging.basicConfig(level=logging.INFO) | ||
|
|
||
| # Set the environment variables for the chat model | ||
| ENDPOINT_URL = os.getenv("ENDPOINT_URL", "https://api.openai.com/v1/chat/completions") | ||
| # Fallback to OpenAI Model if not set in environment | ||
| MODEL_ID = os.getenv("MODEL", "gpt-4-turbo") | ||
|
|
||
| # Get the API key for the LLM | ||
| # For development, you can use your local API key. In production, the LLM gateway service will override the need for it. | ||
| def get_api_key(): | ||
| return os.getenv("OPENAI_API_KEY", "API key not set") | ||
|
|
||
| # Home page form | ||
| @app.get("/", response_class=HTMLResponse) | ||
| async def home(): | ||
| return """ | ||
| <html> | ||
| <head><title>Ask the AI Model</title></head> | ||
| <body> | ||
| <h1>Ask the AI Model</h1> | ||
| <form method="post" action="/ask" onsubmit="document.getElementById('loader').style.display='block'"> | ||
| <textarea name="prompt" autofocus="autofocus" rows="5" cols="60" placeholder="Enter your question here..." | ||
| onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();this.form.submit();}"> | ||
| </textarea> | ||
| <br><br> | ||
| <input type="submit" value="Ask"> | ||
| </form> | ||
| </body> | ||
|
|
||
| </html> | ||
| """ | ||
|
|
||
| # Handle form submission | ||
| @app.post("/ask", response_class=HTMLResponse) | ||
| async def ask(prompt: str = Form(...)): | ||
| headers = { | ||
| "Content-Type": "application/json" | ||
| } | ||
|
|
||
| api_key = get_api_key() | ||
| headers["Authorization"] = f"Bearer {api_key}" | ||
|
|
||
| payload = { | ||
| "model": MODEL_ID, | ||
| "messages": [ | ||
| {"role": "user", "content": prompt} | ||
| ], | ||
| "stream": False | ||
| } | ||
|
|
||
| # Log request details | ||
| logging.info(f"Sending POST to {ENDPOINT_URL}") | ||
| logging.info(f"Request Headers: {headers}") | ||
| logging.info(f"Request Payload: {payload}") | ||
|
|
||
| response = None | ||
| reply = None | ||
| try: | ||
| response = requests.post(f"{ENDPOINT_URL}", headers=headers, data=json.dumps(payload)) | ||
| except requests.exceptions.HTTPError as errh: | ||
| reply = f"HTTP error:", errh | ||
| except requests.exceptions.ConnectionError as errc: | ||
| reply = f"Connection error:", errc | ||
| except requests.exceptions.Timeout as errt: | ||
| reply = f"Timeout error:", errt | ||
| except requests.exceptions.RequestException as err: | ||
| reply = f"Unexpected error:", err | ||
|
|
||
| if response is not None: | ||
| # logging.info(f"Response Status Code: {response.status_code}") | ||
| # logging.info(f"Response Headers: {response.headers}") | ||
| # logging.info(f"Response Body: {response.text}") | ||
| if response.status_code == 200: | ||
| data = response.json() | ||
| try: | ||
| reply = data["choices"][0]["message"]["content"] | ||
| except (KeyError, IndexError): | ||
| reply = "Model returned an unexpected response." | ||
| elif response.status_code == 400: | ||
| reply = f"Connect Error: {response.status_code} - {response.text}" | ||
| elif response.status_code == 500: | ||
| reply = f"Error from server: {response.status_code} - {response.text}" | ||
| else: | ||
| # Log error details | ||
| reply = f"Error from server: {response.status_code} - {response.text}" | ||
| logging.error(f"Error from server: {response.status_code} - {response.text}") | ||
|
|
||
| # Return result | ||
| return f""" | ||
| <html> | ||
| <head><title>Ask the AI Model</title></head> | ||
| <body> | ||
| <h1>Ask the AI Model</h1> | ||
| <form method="post" action="/ask" onsubmit="document.getElementById('loader').style.display='block'"> | ||
| <textarea name="prompt" autofocus="autofocus" rows="5" cols="60" placeholder="Enter your question here..." | ||
| onkeydown="if(event.key==='Enter'&&!event.shiftKey){{event.preventDefault();this.form.submit();}}"></textarea><br><br> | ||
| <input type="submit" value="Ask"> | ||
| </form> | ||
| <h2>You Asked:</h2> | ||
| <p>{prompt}</p> | ||
| <hr> | ||
| <h2>Model's Reply:</h2> | ||
| <p>{reply}</p> | ||
| </body> | ||
| </html> | ||
| """ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| dotenv | ||
| fastapi | ||
| python-multipart | ||
| requests | ||
| uvicorn |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| services: | ||
| app: | ||
| extends: | ||
| file: compose.yaml | ||
| service: app | ||
| llm: | ||
| extends: | ||
| file: compose.yaml | ||
| service: llm | ||
| # if using AWS Bedrock for local development, include this section: | ||
| environment: | ||
| - AWS_REGION=${AWS_REGION} # replace with your AWS region | ||
| - AWS_PROFILE=${AWS_PROFILE} # replace with your AWS profile name | ||
| volumes: | ||
| - type: bind | ||
| source: ~/.aws | ||
| target: /root/.aws |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| services: | ||
| app: | ||
| build: | ||
| context: ./app | ||
| dockerfile: Dockerfile | ||
| ports: | ||
| - "8000:8000" | ||
| restart: always | ||
| environment: | ||
| - ENDPOINT_URL=http://llm/api/v1/chat/completions # endpoint to the Provider Service | ||
| - MODEL=anthropic.claude-3-5-sonnet-20241022-v2:0 # LLM model ID used in the Provider Service | ||
| - OPENAI_API_KEY=FAKE_TOKEN # the actual value will be ignored when using the Provider Service | ||
| healthcheck: | ||
| test: ["CMD", "python3", "-c", "import sys, urllib.request; urllib.request.urlopen(sys.argv[1]).read()", "http://localhost:8000/"] | ||
| interval: 30s | ||
| timeout: 5s | ||
| retries: 3 | ||
| start_period: 5s | ||
|
|
||
| # Provider Service | ||
| # This service is used to route requests to the LLM API | ||
| llm: | ||
| provider: | ||
| type: model |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's rename this directory to something that includes
docker-model-runnerthe word "provider" doesn't mean anything without more context.