2025年4月13日日曜日

emacs の copilot-chat で copilot-chat-add-current-buffer を使うと現在のバッファを質問のコンテクストとして加えることができる

emacs の copilot-chat で copilot-chat-add-current-buffer を使うと現在のバッファを質問のコンテクストとして加えることができる

概要

タイトルの通りです
手元のコードを学習させたりコンテキストとして持たせたりするベストプラクティスは何がいいのでしょうか

環境

  • emacs 30.1
  • copilot-chat 2.0.1

チャット履歴

まずはコンテキストを与えないで質問します

* *[11:06:32]* You                 :you:
Please provide a sample python code that uses the Message class.

** *[11:06:34]* Copilot(gpt-4o)                 :copilot:
*** Sample Python Code Using the Message Class

Here is a sample Python code that demonstrates the use of the `Message` class from the `email.message` module. This example creates an email message, sets its headers, and adds content.

#+BEGIN_SRC python
from email.message import EmailMessage

def create_email():
    # Create an instance of the EmailMessage class
    msg = EmailMessage()
    
    # Set the email headers
    msg['From'] = 'sender@example.com'
    msg['To'] = 'recipient@example.com'
    msg['Subject'] = 'Sample Email Subject'
    
    # Add the email content
    msg.set_content('This is the plain text content of the email.')
    
    # Add an HTML version of the content
    msg.add_alternative("""
    <html>
        <body>
            <h1>This is the HTML content of the email.</h1>
            <p>It includes <b>bold</b> and <i>italic</i> text.</p>
        </body>
    </html>
    """, subtype='html')
    
    return msg

# Example usage
if __name__ == "__main__":
    email_message = create_email()
    print(email_message)
#+END_SRC

*** Key Points
+ The `EmailMessage` class is part of Python's built-in `email` module.
+ The `set_content` method is used to add plain text content.
+ The `add_alternative` method is used to add an HTML version of the email content.
+ Headers like ~From~, ~To~, and ~Subject~ are set using dictionary-like syntax.

次に以下のファイルを開いて copilot-chat-add-current-buffer で開いたファイルをコンテキストに追加します

  • vim my_lib/utils.py
import time


class Message:
    def say(self, **kwargs):
        print("Start say")
        print(kwargs)
        time.sleep(10)
        raise ValueError()
        # print("End say")

そして更に質問します
するとコンテキストとして追加したクラスをちゃんと使って修正してくれます

* *[11:07:47]* You                 :you:
Use the Message class in my_libs/utils.py

** *[11:07:48]* Copilot(gpt-4o)                 :copilot:
*** Sample Code Using the ~Message~ Class in ~my_libs/utils.py~

Below is an example of how to use the ~Message~ class from your provided code in ~my_libs/utils.py~.

#+BEGIN_SRC python
from my_libs.utils import Message

def main():
    # Create an instance of the Message class
    msg = Message()
    
    # Call the say method with keyword arguments
    try:
        msg.say(text="Hello, World!", sender="user@example.com", recipient="recipient@example.com")
    except ValueError:
        print("An error occurred while executing the say method.")

if __name__ == "__main__":
    main()
#+END_SRC

*** Explanation
+ The ~Message~ class is imported from ~my_libs/utils.py~.
+ An instance of the ~Message~ class is created using ~msg = Message()~.
+ The ~say~ method is called with keyword arguments like ~text~, ~sender~, and ~recipient~.
+ A ~try-except~ block is used to handle the ~ValueError~ raised by the ~say~ method.

更に Message クラスに機能を追加する依頼をしてみます
ちゃんと元の Message クラスの構成をキープしつつ追加してくれました

* *[11:11:04]* You                 :you:
Add a field to the Message class to manage the message body.


** *[11:11:06]* Copilot(gpt-4o)                 :copilot:
*** Updated ~Message~ Class with a Field for the Message Body

Below is the updated ~Message~ class with a new field to manage the message body.

#+BEGIN_SRC python
import time

class Message:
    def __init__(self, body=""):
        """
        Initialize the Message class with an optional body field.
        """
        self.body = body

    def say(self, **kwargs):
        """
        Print the message body and additional keyword arguments.
        """
        print("Start say")
        print("Message Body:", self.body)
        print("Additional Arguments:", kwargs)
        time.sleep(10)
        raise ValueError()
        # print("End say")
#+END_SRC

*** Explanation of Changes
+ A new field ~body~ is added to the ~Message~ class, initialized in the constructor (~__init__~).
+ The ~say~ method now prints the value of the ~body~ field along with the additional keyword arguments.

*** Example Usage
Here is an example of how to use the updated ~Message~ class:

#+BEGIN_SRC python
from my_libs.utils import Message

def main():
    # Create an instance of the Message class with a custom body
    msg = Message(body="This is the message body.")
    
    # Call the say method with keyword arguments
    try:
        msg.say(sender="user@example.com", recipient="recipient@example.com")
    except ValueError:
        print("An error occurred while executing the say method.")

if __name__ == "__main__":
    main()
#+END_SRC

*** Key Points
+ The ~body~ field allows you to store and manage the message content directly within the ~Message~ class.
+ The ~say~ method now includes the ~body~ field in its output for better context.


* ╭──── Chat Input ────╮ :copilotChatInput:

最後に

emacs の copilot-chat でコンテキストを追加する方法を紹介しました
こんな感じで公開されていないコードや手元にあるライブラリ情報をコンテキストとして追加すればそれを考慮したコードを書いてくれるようです

以下懸念点です

  • 複数のバッファをコンテキストとして追加するにはどうすればいいのか
  • 一度コンテキストとして追加したバッファを復元するにはどうすればいいのか
    • chat を開くたびに追加しなければならない

参考サイト

0 件のコメント:

コメントを投稿