ram
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Preparing Azure Functions ![image](https://hackmd.io/_uploads/BJXAduwt6.png) What is azure functions? Azure Functions is a serverless computing service used for a variety of scenarios including microservices, data processing, and task automation. Event-driven Azure Functions provides an event-driven programming model where functions are executed in response to triggers For example, HTTP Triggers can be requests, new messages to the message queue, database changes, etc. Supported triggers and bindings Various triggers and bindings are supported, including HTTP triggers, timer events, Blob storage changes, and receiving queue messages. This allows for easy integration with external resources Support for multiple programming languages Azure Functions supports different programming languages ​​(C#, JavaScript, Python, PowerShell, etc.), allowing developers to choose the language of their choice. You can create a function by ## How to create functions Since functions cannot be created using Python from the Portal, create functions using VSCode (text editor). ### About HTTP triggers HTTP Trigger is a type of trigger type used in Azure Functions, which allows you to create functions that respond to external HTTP requests. When using HTTP Trigger, processing defined in Azure Functions is executed in response to HTTP requests from external systems or clients. * What are HTTP requests POST and GET? [click here](https://medium-company.com/http-get-post-%E9%81%95%E3%81%84/) * If you want to know what you can receive with HTTP Trigger [Click here](https://learn.microsoft.com/ja-jp/python/api/azure-functions/azure.functions.httprequest?view=azure-python) ### Purpose * Be able to implement and debug Azure Functions template functions * By implementing Cognitive Search and AOAI processing in Azure Functions functions and skipping the question text with Postman, "Receive a question with an HTTP trigger and start a function" → "Search internal documents based on a question with Cognitive Search" → You will be able to create a series of steps in which you can send internal documents and questions to AOAI and have them respond. ## [Configure your environment](https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python?pivots=python-mode-decorators) Before you begin, make sure that you have the following requirements in place: An Azure account with an active subscription. Create an account for free. Python versions that are supported by Azure Functions. For more information, see How to install Python. Visual Studio Code on one of the supported platforms. The Python extension for Visual Studio Code. The Azure Functions extension for Visual Studio Code, version 1.8.1 or later. The Azurite V3 extension local storage emulator. While you can also use an actual Azure storage account, this article assumes you're using the Azurite emulator. ### Execution steps * [Create Azure Function Resource From Portal](https://hackmd.io/q094aW8ER7qhF_gj4ugTqg) for hosting, select consumption (serverless) OR * [Create Azure Function Resources from VScode](https://balconia.backlog.jp/alias/wiki/1331431) * [Official Demo JP](https://learn.microsoft.com/ja-jp/azure/azure-functions/create-first-function-vs-code-python?pivots=python-mode-decorators) * [Official Demo EN](https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-python?pivots=python-mode-decorators) 2. Create an HTTP trigger function and incorporate the Cognitive Search and AOAI processing you have learned so far into the function You have to replace two files: 0. local.settings.json should as below There is a automatic way to fix ... I need to revisit ``` { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=functionappstorageaoi;AccountKey=erB+uVvn1LsWNOZ7UqwIVIOtsoh9Xo0PQ0fkqtWXwykhgjxb0p4Lum8WBWu3ctqLdPULSk7PdcHM+AStAQ/yTA==;EndpointSuffix=core.windows.net", "FUNCTIONS_WORKER_RUNTIME": "python", "AzureWebJobsFeatureFlags": "EnableWorkerIndexing", "FUNCTIONS_EXTENSION_VERSION": "~4", "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING": "DefaultEndpointsProtocol=https;AccountName=functionappstorageaoi;AccountKey=erB+uVvn1LsWNOZ7UqwIVIOtsoh9Xo0PQ0fkqtWXwykhgjxb0p4Lum8WBWu3ctqLdPULSk7PdcHM+AStAQ/yTA==;EndpointSuffix=core.windows.net", "WEBSITE_CONTENTSHARE": "aoi-search-app92e6" } } ``` 2. requirements.txt with the following contents ``` azure-functions azure-search-documents==11.4.0b6 openai[datalib]==0.27.8 # additional libraries Flask==2.0.2 gunicorn==21.2.0 Werkzeug==2.2.2 # openai==0.28.1 # azure-search-documents==11.4.0b6 # azure-common==1.1.28 # azure-core==1.29.4 numpy ``` 3. another is function_app.py by following contents ``` import azure.functions as func from azure.search.documents import SearchClient from azure.core.credentials import AzureKeyCredential import logging import json from azure.search.documents.models import QueryType import openai app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS) base_resource_name = "oai-jp-gpt35" search_service_name = "cognitivesearch-jpeast-aoi-standard" # Cognitive Searchのデプロイ名 search_index_name = "search_index_name" # index名 search_api_key = "api_key" # cognitive search/search service APIキー search_endpoint = f"https://{search_service_name}.search.windows.net" # Endポイント vector_field_name = "vector" # index内でベクトルを格納しているフィールド名 特に変更していなければ「vector」 context_field_name = "chunk" # index内でchunkを格納しているフィールド名 特に変更していなければ「chunk」 semantic_vector_name = "vector-1706155385792-semantic-configuration" openai.api_type = "azure" # AOAIを使用するためazure openai.api_base = f"https://{base_resource_name}.openai.azure.com/" #endポイント openai.api_version = "2023-07-01-preview" #Azure AI Studioのチャットプレイグランドで送信例のコード表示から openai.api_key = "api_key" # APIキー embedding_deploy_name = "text-embedding-AOI" # AOAIのembeddingモデルのデプロイ名 chat_deploy_name = "gpt35" # AOAIのChatモデルのデプロイ名 search_client = SearchClient(endpoint=search_endpoint, index_name=search_index_name, credential=AzureKeyCredential(search_api_key)) # endpoint = "https://aid-cosmosdb.documents.azure.com:443/" # key = "<azure cosmos db apikey>" def search(query_text): query_vector = openai.Embedding.create(engine=embedding_deploy_name, input=query_text)["data"][0]["embedding"] #queryベクトルに変換 if query_text: results = list( search_client.search( query_text, filter=None, query_type=QueryType.SEMANTIC, query_language="ja-jp", # 日本語の場合は ja-jp query_speller="none", semantic_configuration_name=semantic_vector_name, top=3, query_caption="extractive|highlight-false" if True else None, vector=query_vector, top_k=50 if query_vector else None, vector_fields=vector_field_name if query_vector else None ) ) return results def chat(query_text, results): if results: context = results[0][context_field_name] response = openai.ChatCompletion.create( engine=chat_deploy_name, messages=[{ "role": "user", "content": f"{query_text}/n以下のcontextを使って質問に回答してください。/n### context ###/n{context}" # "content": "shree" }], temperature=0, max_tokens=2000, top_p=0.95, frequency_penalty=0, presence_penalty=0, stop=None ) r = response.choices[0].message['content'] return r @app.route(route="http_trigger") def http_trigger(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') body = req.get_json() message = body['message'] search_result = search(message) output_text = chat(message, search_result) if body: # UnicodeDecodeError with the following code # 'output_text': output_text logging.info(output_text) # Convert bytes to string before JSON serialization output_text_str = output_text return func.HttpResponse(json.dumps({ 'message': message, 'output_text': output_text }), status_code=200, mimetype="applicatuin/json" ) else: return func.HttpResponse( "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.", status_code=200 ) ``` note: a bit confusing here Sign in to your visual studio code and follow the instruction provided to create azure function with http trigger ## Run the function app to check Click F1 > Azurite start or click debug in WORKSPACE >Local Project > Functions > Error Function_app.py and requirements.txt created in execution step 2 Replace the following files with Note: function may gives error when you click the url (value error) Continue to postman debug 3. Postman Debug [Postman](https://www.postman.com/downloads/) Note: Web version needs registration can use gmail Note: Application version doesnt requires registration * Download and create workspace as below and change GET to POST ![image](https://hackmd.io/_uploads/SkhrKrstT.png) 2. Switch to Body and raw with POST ![image](https://hackmd.io/_uploads/rkRsYrsFp.png) 3. Set up POST URL generated from azure function eg. http://localhost:7071/api/http_trigger ![image](https://hackmd.io/_uploads/BJHrjrjKT.png) create a message in json format and send 4. Error on the function_app Fix implemented ``` if body: # UnicodeDecodeError with the following code # 'output_text': output_text logging.info(output_text) # Convert bytes to string before JSON serialization output_text_str = output_text return func.HttpResponse(json.dumps({ 'message': message, 'output_text': output_text }), status_code=200, mimetype="applicatuin/json" ) else: return func.HttpResponse( "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.", status_code=200 ) ``` 5. Preview of result ![image](https://hackmd.io/_uploads/Bkt8N_iKp.png) Succesfully message received: Now it is ready to be deployed

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully