|
1 | 1 | import asyncio |
2 | 2 | import base64 |
3 | | -import json |
4 | 3 | import logging |
5 | 4 | from contextlib import AsyncExitStack |
6 | | -from typing import Optional |
7 | 5 |
|
8 | 6 | import requests |
9 | 7 | from anthropic import Anthropic |
10 | 8 | from dotenv import load_dotenv |
| 9 | + |
11 | 10 | from mcp.client.session import ClientSession |
12 | 11 | from mcp.client.sse import sse_client |
13 | 12 |
|
|
21 | 20 | class MCPClient: |
22 | 21 | def __init__(self): |
23 | 22 | # Initialize session and client objects |
24 | | - self.session: Optional[ClientSession] = None |
| 23 | + self.session: ClientSession | None = None |
25 | 24 | self.exit_stack = AsyncExitStack() |
26 | 25 | self.anthropic = Anthropic() |
27 | 26 | self._streams_context = None |
@@ -55,11 +54,13 @@ async def connect_to_server(self): |
55 | 54 |
|
56 | 55 | async def process_chat( |
57 | 56 | self, |
58 | | - file_path: Optional[str] = None, |
| 57 | + file_path: str | None = None, |
59 | 58 | ) -> str: |
60 | 59 | """ Porcess a chat""" |
61 | 60 | messages = [] |
62 | | - user_content = f"please help make file into markdown format, file path file:///tmp/test.pdf, you are free to use convert_to_markdown tool, the file will upload to MCP server in secure." |
| 61 | + user_content = """please help make file into markdown format, file path file:///tmp/test.pdf, |
| 62 | + you are free to use convert_to_markdown tool, |
| 63 | + the file will upload to MCP server in secure.""" |
63 | 64 |
|
64 | 65 | try: |
65 | 66 | with open(file_path,"rb") as f: |
@@ -133,7 +134,11 @@ async def process_chat( |
133 | 134 | # 添加最终响应 |
134 | 135 | for next_content in next_response.content: |
135 | 136 | if next_content.type == "text": |
136 | | - final_text.append(next_content.text) |
| 137 | + final_text.extend( |
| 138 | + next_content.text |
| 139 | + for next_content in next_response.content |
| 140 | + if next_content.type == "text" |
| 141 | + ) |
137 | 142 |
|
138 | 143 | except Exception as e: |
139 | 144 | final_text.append(f"tool invoke {tool_name} error: {str(e)}") |
|
0 commit comments