搜尋
首頁後端開發Python教學使用 Anthropic 的 Claude Sonnet 產生報告

利用Anthropic的Claude 3.5 Sonnet產生報表:兩種方法的比較

Using Anthropic

大家好!我是Raphael,巴西房地產公司Pilar的共同創辦人兼CTO。 Pilar為房地產經紀人和經紀公司提供軟體和服務,採用低成功費模式。我們不收取高昂的前期費用,而是從每次成功的交易中收取少量佣金,使我們的成功直接與客戶的成功掛鉤。我們由20位技術人員組成的團隊不斷創新,最新產品是Pilar Homes,一個全新的房地產入口網站,旨在為購屋者和房地產經紀人提供最佳體驗。

在這篇文章中,我將分享我們使用人工智慧產生報告的經驗,特別是Anthropic的Claude 3.5 Sonnet,並比較兩種不同的方法。

我們處理任務的理念將在未來的文章中詳細介紹(敬請關注!),但簡而言之,這些任務最終以Jira工單的形式出現在「技術服務台」看板上。產生報告就是這樣一項任務,大多數任務需要工程師花費大約30分鐘來解決,複雜報告很少超過幾個小時。但情況正在改變。我們最初只與一兩個合作夥伴合作的精品品牌正在擴張,成為更大的經紀公司,我們也與業內老牌公司簽訂了更多合約。雖然增加工程師的工作時間可以解決日益增長的報告需求,但我看到了探索人工智慧代理並在現實環境中學習架構模式的機會。

方法一:讓AI全權處理並達到max_tokens限制

在我們的初始方法中,我們將工具暴露給Claude的3.5 Sonnet模型,使其能夠執行資料庫查詢、將檢索到的文檔轉換為CSV並將其結果寫入.csv檔案。

以下是我們的結構,很大程度上受到了上面部落格文章的啟發:

<code># 每个collection对象描述一个MongoDB集合及其字段
# 这有助于Claude理解我们的数据模式
COLLECTIONS = [
    {
        'name': 'companies',
        'description': 'Companies are the real estate brokerages. If the user provides a code to filter the data, it will be a company code. The _id may be retrieved by querying the company with the given code. Company codes are not used to join data.',
        'fields': {
            '_id': 'The ObjectId is the MongoDB id that uniquely identifies a company document. Its JSON representation is \"{"$oid": "the id"}\"',
            'code': 'The company code is a short and human friendly string that uniquely identifies the company. Never use it for joining data.',
            'name': 'A string representing the company name',
        }
    },
    # 此处之后描述了更多集合,但思路相同...
]

# 这是client.messages.create的“system”参数
ROLE_PROMPT = "You are an engineer responsible for generating reports in CSV based on a user's description of the report content"

# 这是“user”消息
task_prompt = f"{report_description}.\nAvailable collections: {COLLECTIONS}\nCompany codes: {company_codes}\n.Always demand a company code from the user to filter the data -- the user may use the terms imobiliária, marca, brand or company to reference a company. If the user wants a field that does not exist in a collection, don't add it to the report and don't ask the user for the field."
</code>

report_description只是一個透過argparse讀取的命令列參數,company_codes是從資料庫中檢索到的,並將其暴露給模型,以便它知道哪些公司存在以及用戶輸入中什麼是公司代碼。範例:(MO - Mosaic Homes,NV - Nova Real Estate,等等)。

模型可用的工具包括:find和docs2csv。

<code>def find(collection: str, query: str, fields: list[str]) -> Cursor:
    """Find documents in a collection filtering by "query" and retrieving fields via projection"""
    return db.get_collection(collection).find(query, projection={field: 1 for field in fields})

def docs2csv(documents: list[dict]) -> list[str]:
    """
    Convert a dictionary to a CSV string.
    """
    print(f"Converting {len(documents)} documents to CSV")
    with open('report.csv', mode='w', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=documents[0].keys())
        writer.writeheader()
        writer.writerows(documents)
    return "report.csv"</code>

Claude能夠呼叫find函數對我們的資料庫執行結構良好的查詢和投影,並使用docs2csv工具產生小型CSV報告(少於500行)。但是,較大的報告會觸發max_tokens錯誤。

在分析了我們的令牌使用模式後,我們意識到大部分令牌消耗都來自透過模型處理單一記錄。這促使我們探索另一種方法:讓Claude產生處理程式碼,而不是直接處理資料。

方法二:Python程式碼產生作為解決方法

雖然解決max_tokens限制在技術上並不困難,但它需要我們重新思考解決問題的方法。

解決方案?讓Claude產生將在我們的CPU上運行的Python程式碼,而不是透過AI處理每個文件。

我必須修改角色和任務提示並刪除工具。

以下是報告產生程式碼的要點。

產生報告的命令是:

<code># 每个collection对象描述一个MongoDB集合及其字段
# 这有助于Claude理解我们的数据模式
COLLECTIONS = [
    {
        'name': 'companies',
        'description': 'Companies are the real estate brokerages. If the user provides a code to filter the data, it will be a company code. The _id may be retrieved by querying the company with the given code. Company codes are not used to join data.',
        'fields': {
            '_id': 'The ObjectId is the MongoDB id that uniquely identifies a company document. Its JSON representation is \"{"$oid": "the id"}\"',
            'code': 'The company code is a short and human friendly string that uniquely identifies the company. Never use it for joining data.',
            'name': 'A string representing the company name',
        }
    },
    # 此处之后描述了更多集合,但思路相同...
]

# 这是client.messages.create的“system”参数
ROLE_PROMPT = "You are an engineer responsible for generating reports in CSV based on a user's description of the report content"

# 这是“user”消息
task_prompt = f"{report_description}.\nAvailable collections: {COLLECTIONS}\nCompany codes: {company_codes}\n.Always demand a company code from the user to filter the data -- the user may use the terms imobiliária, marca, brand or company to reference a company. If the user wants a field that does not exist in a collection, don't add it to the report and don't ask the user for the field."
</code>

Claude產生的Python內容(運作良好):

<code>def find(collection: str, query: str, fields: list[str]) -> Cursor:
    """Find documents in a collection filtering by "query" and retrieving fields via projection"""
    return db.get_collection(collection).find(query, projection={field: 1 for field in fields})

def docs2csv(documents: list[dict]) -> list[str]:
    """
    Convert a dictionary to a CSV string.
    """
    print(f"Converting {len(documents)} documents to CSV")
    with open('report.csv', mode='w', encoding='utf-8') as file:
        writer = csv.DictWriter(file, fieldnames=documents[0].keys())
        writer.writeheader()
        writer.writerows(documents)
    return "report.csv"</code>

結論

我們與Claude 3.5 Sonnet的歷程表明,人工智慧可以顯著提高營運效率,但成功的關鍵在於選擇正確的架構。程式碼產生方法被證明比直接的AI處理更強大,同時保持了自動化的優勢。

除了正確建立報告外,程式碼產生方法還允許工程師審查AI的工作,這是一件非常好的事情。

為了完全自動化流程,消除人工參與並處理更大數量的報告,跨多個代理實例分配工作——每個實例處理更少的令牌——將是該系統的自然演變。對於這類分散式AI系統中的架構挑戰,我強烈推薦Phil Calçado關於建構AI產品的最新文章。

此實現的主要經驗教訓:

  • 直接AI處理適用於較小的資料集
  • 程式碼產生提供更好的可擴充性和可維護性
  • 人工審查增加了可靠性

參考文獻

  • Anthropic 文件
  • Thomas Taylor 使用 Python SDK 的帶工具的 Anthropic Claude
  • Phil Calçado 所寫的建構 AI 產品-第一部分:後端架構

以上是使用 Anthropic 的 Claude Sonnet 產生報告的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何解決Linux終端中查看Python版本時遇到的權限問題?如何解決Linux終端中查看Python版本時遇到的權限問題?Apr 01, 2025 pm 05:09 PM

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

python對象的序列化和避難所化:第1部分python對象的序列化和避難所化:第1部分Mar 08, 2025 am 09:39 AM

Python 對象的序列化和反序列化是任何非平凡程序的關鍵方面。如果您將某些內容保存到 Python 文件中,如果您讀取配置文件,或者如果您響應 HTTP 請求,您都會進行對象序列化和反序列化。 從某種意義上說,序列化和反序列化是世界上最無聊的事情。誰會在乎所有這些格式和協議?您想持久化或流式傳輸一些 Python 對象,並在以後完整地取回它們。 這是一種在概念層面上看待世界的好方法。但是,在實際層面上,您選擇的序列化方案、格式或協議可能會決定程序運行的速度、安全性、維護狀態的自由度以及與其他系

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

Python中的數學模塊:統計Python中的數學模塊:統計Mar 09, 2025 am 11:40 AM

Python的statistics模塊提供強大的數據統計分析功能,幫助我們快速理解數據整體特徵,例如生物統計學和商業分析等領域。無需逐個查看數據點,只需查看均值或方差等統計量,即可發現原始數據中可能被忽略的趨勢和特徵,並更輕鬆、有效地比較大型數據集。 本教程將介紹如何計算平均值和衡量數據集的離散程度。除非另有說明,本模塊中的所有函數都支持使用mean()函數計算平均值,而非簡單的求和平均。 也可使用浮點數。 import random import statistics from fracti

用美麗的湯在Python中刮擦網頁:搜索和DOM修改用美麗的湯在Python中刮擦網頁:搜索和DOM修改Mar 08, 2025 am 10:36 AM

該教程建立在先前對美麗湯的介紹基礎上,重點是簡單的樹導航之外的DOM操縱。 我們將探索有效的搜索方法和技術,以修改HTML結構。 一種常見的DOM搜索方法是EX

哪些流行的Python庫及其用途?哪些流行的Python庫及其用途?Mar 21, 2025 pm 06:46 PM

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

如何使用Python創建命令行接口(CLI)?如何使用Python創建命令行接口(CLI)?Mar 10, 2025 pm 06:48 PM

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具