# Chat project Ang proyektong ito ay nagpapakita kung paano bumuo ng isang Chat Assistant gamit ang GitHub Models. Ganito ang magiging hitsura ng natapos na proyekto:
Chat app
Kaunting konteksto, ang paggawa ng Chat assistants gamit ang generative AI ay isang mahusay na paraan upang magsimulang matuto tungkol sa AI. Sa araling ito, matututuhan mong isama ang generative AI sa isang web app. Simulan na natin. ## Pagkonekta sa generative AI Para sa backend, gagamit tayo ng GitHub Models. Isa itong mahusay na serbisyo na nagbibigay-daan sa iyo na gumamit ng AI nang libre. Pumunta sa playground nito at kunin ang code na tumutugma sa napili mong backend na wika. Ganito ang itsura nito sa [GitHub Models Playground](https://github.com/marketplace/models/azure-openai/gpt-4o-mini/playground)
GitHub Models AI Playground
Tulad ng nabanggit, piliin ang tab na "Code" at ang runtime na gusto mo.
playground choice
### Gamit ang Python Sa kasong ito, pipiliin natin ang Python, kaya't ito ang code na gagamitin: ```python """Run this model in Python > pip install openai """ import os from openai import OpenAI # To authenticate with the model you will need to generate a personal access token (PAT) in your GitHub settings. # Create your PAT token by following instructions here: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens client = OpenAI( base_url="https://models.github.ai/inference", api_key=os.environ["GITHUB_TOKEN"], ) response = client.chat.completions.create( messages=[ { "role": "system", "content": "", }, { "role": "user", "content": "What is the capital of France?", } ], model="openai/gpt-4o-mini", temperature=1, max_tokens=4096, top_p=1 ) print(response.choices[0].message.content) ``` Linisin natin ang code na ito upang magamit muli: ```python def call_llm(prompt: str, system_message: str): response = client.chat.completions.create( messages=[ { "role": "system", "content": system_message, }, { "role": "user", "content": prompt, } ], model="openai/gpt-4o-mini", temperature=1, max_tokens=4096, top_p=1 ) return response.choices[0].message.content ``` Sa pamamagitan ng function na `call_llm`, maaari na nating kunin ang isang prompt at isang system prompt, at ang function ay magbabalik ng resulta. ### I-customize ang AI Assistant Kung nais mong i-customize ang AI assistant, maaari mong tukuyin kung paano ito dapat kumilos sa pamamagitan ng paglalagay ng system prompt tulad nito: ```python call_llm("Tell me about you", "You're Albert Einstein, you only know of things in the time you were alive") ``` ## I-expose ito sa pamamagitan ng Web API Magaling, tapos na natin ang AI na bahagi. Tingnan natin kung paano natin ito maisasama sa isang Web API. Para sa Web API, gagamit tayo ng Flask, ngunit anumang web framework ay maaaring gamitin. Narito ang code para dito: ### Gamit ang Python ```python # api.py from flask import Flask, request, jsonify from llm import call_llm from flask_cors import CORS app = Flask(__name__) CORS(app) # * example.com @app.route("/", methods=["GET"]) def index(): return "Welcome to this API. Call POST /hello with 'message': 'my message' as JSON payload" @app.route("/hello", methods=["POST"]) def hello(): # get message from request body { "message": "do this taks for me" } data = request.get_json() message = data.get("message", "") response = call_llm(message, "You are a helpful assistant.") return jsonify({ "response": response }) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000) ``` Dito, lumikha tayo ng isang Flask API at nagtakda ng default na ruta na "/" at "/chat". Ang huli ay gagamitin ng ating frontend upang maipasa ang mga tanong dito. Upang maisama ang *llm.py*, narito ang mga hakbang na kailangan gawin: - I-import ang function na `call_llm`: ```python from llm import call_llm from flask import Flask, request ``` - Tawagin ito mula sa ruta na "/chat": ```python @app.route("/hello", methods=["POST"]) def hello(): # get message from request body { "message": "do this taks for me" } data = request.get_json() message = data.get("message", "") response = call_llm(message, "You are a helpful assistant.") return jsonify({ "response": response }) ``` Dito, ini-parse natin ang papasok na request upang makuha ang property na `message` mula sa JSON body. Pagkatapos, tatawagin natin ang LLM gamit ang tawag na ito: ```python response = call_llm(message, "You are a helpful assistant") # return the response as JSON return jsonify({ "response": response }) ``` Magaling, natapos na natin ang kailangan. ## I-configure ang Cors Dapat nating banggitin na nag-set up tayo ng isang bagay tulad ng CORS, o cross-origin resource sharing. Nangangahulugan ito na dahil ang ating backend at frontend ay tatakbo sa magkaibang ports, kailangan nating payagan ang frontend na tumawag sa backend. ### Gamit ang Python Narito ang isang piraso ng code sa *api.py* na nagse-set up nito: ```python from flask_cors import CORS app = Flask(__name__) CORS(app) # * example.com ``` Sa kasalukuyan, naka-set up ito upang payagan ang "*" o lahat ng origins, ngunit hindi ito ligtas. Dapat natin itong limitahan kapag nasa production na. ## Patakbuhin ang iyong proyekto Upang patakbuhin ang iyong proyekto, kailangan mong simulan muna ang iyong backend at pagkatapos ang iyong frontend. ### Gamit ang Python Ok, mayroon tayong *llm.py* at *api.py*. Paano natin ito mapapagana sa backend? Narito ang dalawang hakbang: - I-install ang mga dependencies: ```sh cd backend python -m venv venv source ./venv/bin/activate pip install openai flask flask-cors openai ``` - Simulan ang API: ```sh python api.py ``` Kung nasa Codespaces ka, pumunta sa Ports sa ibabang bahagi ng editor, i-right-click ito at i-click ang "Port Visibility" at piliin ang "Public". ### Gumawa ng frontend Ngayon na may API na tayong tumatakbo, gumawa tayo ng frontend para dito. Isang pinakasimpleng frontend na unti-unti nating pagagandahin. Sa isang *frontend* folder, gumawa ng mga sumusunod: ```text backend/ frontend/ index.html app.js styles.css ``` Simulan natin sa **index.html**: ```html