Tool Use Mathematics and Implementation: From JSON Schema to Pydantic AI — Production Agent Engineering
Internal mathematics of tool use and production implementation: JSON schema standard detail, full anatomy of OpenAI function calling, ReAct prompt engineering techniques, MCP protocol implementation (Python stdio + SSE). Turkish tool calling examples (TC ID validation, e-invoice query). Clean, type-safe agent with Pydantic AI. Modern approach as LangChain alternative. Error handling, retry logic, tool timeout management.
Şükrü Yusuf KAYA
85 min read
Advanced🔧 Tool Use — Tasarım Kararlarından Production Code'a
Tool use teorik fikir değil — gerçek kod. Bu ders implementation tarafına odaklanıyor:
- JSON Schema standardı: function calling'in dili. OpenAPI'den türemiş ama LLM-spesifik. Detayları anlamadan production ajan kurulamaz.
- ReAct prompt mühendisliği: open-source modellerle (Llama-3, Mistral) tool kullanmak istiyorsan kritik. Prompt format, parsing strategy, error handling.
- MCP protokol implementation: Python'da sıfırdan MCP server kur. JSON-RPC, stdio transport.
- Pydantic AI: 2024 sonu çıkan modern alternatif. LangChain'in 200+ abstraction yerine 20 abstraction. Type-safe, anlaşılır, hızlı.
- Error handling + retry: production'da tool'lar fail eder. Network hatası, rate limit, malformed response. Robust ajan için kritik.
85 dakikada: kendi Türkçe ajanınızı sıfırdan kurabilecek seviyede production knowledge. TC kimlik validasyonu, Türk e-fatura sorgulama gibi pratik tool örnekleri.
Bu Derste Neler Var? (12 Bölüm)#
- JSON Schema standardı — function calling'in dili
- OpenAI function calling tam akış
- Türkçe tool örnekleri — TC kimlik, e-fatura
- ReAct prompt engineering — open-source modeller için
- MCP protokol detayı — JSON-RPC + transports
- MCP Python server implementation
- Pydantic AI — modern LangChain alternatifi
- Pydantic AI Türkçe ajan örnek
- Error handling stratejileri — retry, timeout, fallback
- Tool composability — birden fazla tool zinciri
- Cost + latency optimizasyonu
- Egzersizler
python
# OpenAI Function Calling — Türkçe Tool Örnekfrom openai import OpenAIfrom typing import Literalimport jsonimport re client = OpenAI() # 1. Tool fonksiyonu — gerçek işdef tc_kimlik_dogrula(tc_no: str) -> dict: '''Türkiye TC kimlik numarası algoritmik doğrulama.''' if len(tc_no) != 11 or not tc_no.isdigit(): return {'gecerli': False, 'hata': 'TC kimlik 11 rakam olmalı'} if tc_no[0] == '0': return {'gecerli': False, 'hata': 'İlk rakam 0 olamaz'} digits = [int(d) for d in tc_no] sum_odd = sum(digits[i] for i in [0, 2, 4, 6, 8]) sum_even = sum(digits[i] for i in [1, 3, 5, 7]) check_10 = (sum_odd * 7 - sum_even) % 10 check_11 = sum(digits[:10]) % 10 if digits[9] == check_10 and digits[10] == check_11: return {'gecerli': True, 'tc_no': tc_no} return {'gecerli': False, 'hata': 'Kontrol algoritması başarısız'} def e_fatura_sorgula(fatura_uuid: str) -> dict: '''Türk e-fatura UUID'siyle sorgulama (mock).''' return { 'uuid': fatura_uuid, 'durum': 'onaylandı', 'toplam': 1250.50, 'tarih': '2025-03-15', 'satici': 'XYZ Ltd. Şti.', 'alici': 'ABC A.Ş.', } # 2. JSON Schema tanımıtools = [ { 'type': 'function', 'function': { 'name': 'tc_kimlik_dogrula', 'description': 'Türkiye Cumhuriyeti kimlik numarasını algoritmik olarak doğrular', 'parameters': { 'type': 'object', 'properties': { 'tc_no': { 'type': 'string', 'description': '11 haneli TC kimlik numarası', }, }, 'required': ['tc_no'], }, }, }, { 'type': 'function', 'function': { 'name': 'e_fatura_sorgula', 'description': 'Türk e-fatura UUID\'siyle fatura detaylarını sorgular', 'parameters': { 'type': 'object', 'properties': { 'fatura_uuid': { 'type': 'string', 'description': 'E-fatura UUID (36 karakter, dash\'lerle)', }, }, 'required': ['fatura_uuid'], }, }, },] # 3. Ajan döngüsümessages = [ {'role': 'system', 'content': 'Sen Türkçe muhasebe asistanısın. TC kimlik doğrulama ve e-fatura sorgulama tool\'larına erişimin var.'}, {'role': 'user', 'content': 'Müşterimin TC\'sini doğrula: 12345678901. Sonra e-fatura uuid 6f1b9c2a-3e4d-5f6a-7b8c-9d0e1f2a3b4c hakkında bilgi ver.'},] while True: response = client.chat.completions.create( model='gpt-4o', messages=messages, tools=tools, tool_choice='auto', ) msg = response.choices[0].message messages.append(msg) if not msg.tool_calls: # Final answer print(msg.content) break # Tool çağrılarını işle for tool_call in msg.tool_calls: func_name = tool_call.function.name func_args = json.loads(tool_call.function.arguments) if func_name == 'tc_kimlik_dogrula': result = tc_kimlik_dogrula(**func_args) elif func_name == 'e_fatura_sorgula': result = e_fatura_sorgula(**func_args) else: result = {'hata': f'Bilinmeyen tool: {func_name}'} messages.append({ 'role': 'tool', 'tool_call_id': tool_call.id, 'content': json.dumps(result, ensure_ascii=False), }) # Beklenen output:# 'TC numarası 12345678901 geçersiz (kontrol algoritması başarısız). E-fatura ... onaylanmış, 1250.50 TL toplam...' Türkçe Function Calling — TC Kimlik + E-Fatura Tool
7-8. Pydantic AI — Modern LangChain Alternatifi#
7.1 Niye Pydantic AI?#
LangChain'in 200+ abstraction'ı geliştiriciler için yıpratıcı oldu. Aralık 2024'te Pydantic ekibi (Samuel Colvin) yeni framework: Pydantic AI.
Felsefe:
- Type-safe: Python type hints + Pydantic schemas
- Minimal abstraction: 20 abstraction (LangChain 200+)
- Multi-provider: OpenAI, Anthropic, Google, Mistral, Ollama tek API ile
- Production-ready: built-in retry, logging, instrumentation
GitHub Mart 2025 itibarıyla: 4K+ star. Hızla büyüyor.
7.2 Pydantic AI Türkçe Ajan Örnek#
from pydantic_ai import Agent from pydantic_ai.tools import Tool from pydantic import BaseModel # Pydantic model — type-safe class HavaDurumu(BaseModel): sehir: str sicaklik: float aciklama: str # Tool fonksiyonu (Pydantic AI otomatik schema üretir) def hava_durumu_getir(sehir: str) -> HavaDurumu: '''Şehir için hava durumunu döndürür.''' # Mock implementation return HavaDurumu(sehir=sehir, sicaklik=22.5, aciklama='Açık') # Agent agent = Agent( 'openai:gpt-4o', system_prompt='Sen yardımsever bir Türkçe asistansın.', tools=[hava_durumu_getir], ) # Çalıştır result = agent.run_sync('İstanbul ve Ankara için hava durumu nedir?') print(result.data) # 'İstanbul'da hava 22.5°C, açık. Ankara'da hava 22.5°C, açık.' print(result.cost()) # Cost: $0.0023 (tokens kullanıldı)
50 satır kod, type-safe, multi-provider. LangChain'de aynı şey 200+ satır + 5 farklı class.
8.1 Pydantic AI Production avantajları#
- Streaming: native support
- Async: full async/await
- Validation: tool output Pydantic ile doğrulanır
- Instrumentation: Logfire (Pydantic'in observability tool'u) ile native entegrasyon
- Multi-step: ReAct loop built-in
Önerim: yeni projeler için Pydantic AI, mevcut LangChain code'larını gerek yoksa migrate etme.
✅ Ders 20.2 Özeti — Tool Use Implementation
Tool use'un production tarafı: JSON Schema function calling'in standart dili. OpenAI function calling Türkçe tool örnekleri (TC kimlik, e-fatura). ReAct prompt engineering open-source modeller için kritik. MCP protokol açık standart, Python'da implement edilebilir. Pydantic AI modern LangChain alternatifi — type-safe, minimal, 50 satırda Türkçe ajan. Error handling: retry, timeout, fallback strateji. Sonraki ders: multi-agent system'ler ve Türkçe production ajan capstone'u.
Sonraki Ders: Multi-Agent + Türkçe Production#
Ders 20.3'te multi-agent system'ler. CrewAI ile role-based agent collaboration, AutoGen ile dynamic conversation, agent orchestration patterns. Türkçe e-ticaret asistanı multi-agent örnek: research agent + price compare agent + recommendation agent. Production deployment + cost management.
Frequently Asked Questions
**For 2025 new project: Pydantic AI**.
**Pydantic AI preferred because**:
- 20 abstractions vs LangChain 200+
- Type-safe (Pydantic native)
- Multi-provider single API
- Modern Python (async-first)
- Less 'magic'
**LangChain still valuable scenarios**:
- Existing LangChain codebase
- Niche features (LangGraph, LangSmith)
- Need very wide ecosystem
**Practical decision**: greenfield → Pydantic AI. Brownfield (existing LangChain code) → not worth migrating.
Note: LangChain v0.3+ simpler, not as complex as before. But Pydantic AI still cleaner.
Yorumlar & Soru-Cevap
(0)Yorum yazmak için giriş yap.
Yorumlar yükleniyor...
Related Content
Module 0: Course Framework & Workshop Setup
Who Is an LLM Engineer? The AI Engineering Career Ladder from Junior to Staff
Start LearningModule 0: Course Framework & Workshop Setup
Course Philosophy: Why This Path, Why This Order — The Skeleton of an 8-Month Curriculum
Start LearningModule 0: Course Framework & Workshop Setup