読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第2節 共通の窓口を作る

2.2 各社のアダプター

各社のSDKの呼び方は、それぞれのアダプターの中に閉じ込めます。AnthropicとGoogleのアダプターは、次のとおりです。

class ClaudeChat:
    def __init__(self, client, model):
        self.client, self.model = client, model

    def complete(self, system, user, max_tokens=800):
        m = self.client.messages.create(model=self.model, max_tokens=max_tokens, system=system,
                                        messages=[{"role": "user", "content": user}])
        text = "".join(b.text for b in m.content if b.type == "text")
        return Reply(text, m.usage.input_tokens, m.usage.output_tokens, self.model, "anthropic", m.stop_reason == "end_turn")


class GeminiChat:
    def complete(self, system, user, max_tokens=800):
        r = self.client.models.generate_content(
            model=self.model, contents=user,
            config=types.GenerateContentConfig(system_instruction=system, max_output_tokens=max_tokens),
        )
        u = r.usage_metadata
        finished = r.candidates[0].finish_reason == "STOP" if r.candidates else False
        return Reply(r.text or "", u.prompt_token_count or 0, u.candidates_token_count or 0, self.model, "gemini", finished)

OpenAIとOllamaのアダプターも、同じ形で書いています。1節の表の違いは、すべてアダプターの中で吸収されます。

解答例

return Reply(choice.message.content or "", c.usage.prompt_tokens, c.usage.completion_tokens, self.model, "ollama", choice.finish_reason == "stop")(c は応答、choice は c.choices[0])

7 / 20